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.07"
44 #include <arpa/inet.h>
48 #include <sys/resource.h>
50 #include "ae.h" /* Event driven programming library */
51 #include "sds.h" /* Dynamic safe strings */
52 #include "anet.h" /* Networking the easy way */
53 #include "dict.h" /* Hash tables */
54 #include "adlist.h" /* Linked lists */
55 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
61 /* Static server configuration */
62 #define REDIS_SERVERPORT 6379 /* TCP port */
63 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
64 #define REDIS_QUERYBUF_LEN 1024
65 #define REDIS_LOADBUF_LEN 1024
66 #define REDIS_MAX_ARGS 16
67 #define REDIS_DEFAULT_DBNUM 16
68 #define REDIS_CONFIGLINE_MAX 1024
69 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
70 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
72 /* Hash table parameters */
73 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
74 #define REDIS_HT_MINSLOTS 16384 /* Never resize the HT under this */
77 #define REDIS_CMD_BULK 1
78 #define REDIS_CMD_INLINE 2
81 #define REDIS_STRING 0
85 #define REDIS_SELECTDB 254
89 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
90 #define REDIS_SLAVE 2 /* This client is a slave server */
91 #define REDIS_MASTER 4 /* This client is a master server */
93 /* Server replication state */
94 #define REDIS_REPL_NONE 0 /* No active replication */
95 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
96 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
98 /* List related stuff */
102 /* Sort operations */
103 #define REDIS_SORT_GET 0
104 #define REDIS_SORT_DEL 1
105 #define REDIS_SORT_INCR 2
106 #define REDIS_SORT_DECR 3
107 #define REDIS_SORT_ASC 4
108 #define REDIS_SORT_DESC 5
109 #define REDIS_SORTKEY_MAX 1024
112 #define REDIS_DEBUG 0
113 #define REDIS_NOTICE 1
114 #define REDIS_WARNING 2
116 /* Anti-warning macro... */
117 #define REDIS_NOTUSED(V) ((void) V)
119 /*================================= Data types ============================== */
121 /* A redis object, that is a type able to hold a string / list / set */
122 typedef struct redisObject
{
128 /* With multiplexing we need to take per-clinet state.
129 * Clients are taken in a liked list. */
130 typedef struct redisClient
{
135 robj
*argv
[REDIS_MAX_ARGS
];
137 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
140 time_t lastinteraction
; /* time of the last interaction, used for timeout */
141 int flags
; /* REDIS_CLOSE | REDIS_SLAVE */
142 int slaveseldb
; /* slave selected db, if this client is a slave */
150 /* Global server state structure */
155 long long dirty
; /* changes to DB from the last save */
158 char neterr
[ANET_ERR_LEN
];
160 int cronloops
; /* number of times the cron function run */
161 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
162 time_t lastsave
; /* Unix time of last save succeeede */
163 int usedmemory
; /* Used memory in megabytes */
164 /* Fields used only for stats */
165 time_t stat_starttime
; /* server start time */
166 long long stat_numcommands
; /* number of processed commands */
167 long long stat_numconnections
; /* number of connections received */
175 int bgsaveinprogress
;
176 struct saveparam
*saveparams
;
181 /* Replication related */
187 /* Sort parameters - qsort_r() is only available under BSD so we
188 * have to take this state global, in order to pass it to sortCompare() */
194 typedef void redisCommandProc(redisClient
*c
);
195 struct redisCommand
{
197 redisCommandProc
*proc
;
202 typedef struct _redisSortObject
{
210 typedef struct _redisSortOperation
{
213 } redisSortOperation
;
215 struct sharedObjectsStruct
{
216 robj
*crlf
, *ok
, *err
, *zerobulk
, *nil
, *zero
, *one
, *pong
, *space
,
217 *minus1
, *minus2
, *minus3
, *minus4
,
218 *wrongtypeerr
, *nokeyerr
, *wrongtypeerrbulk
, *nokeyerrbulk
,
219 *syntaxerr
, *syntaxerrbulk
,
220 *select0
, *select1
, *select2
, *select3
, *select4
,
221 *select5
, *select6
, *select7
, *select8
, *select9
;
224 /*================================ Prototypes =============================== */
226 static void freeStringObject(robj
*o
);
227 static void freeListObject(robj
*o
);
228 static void freeSetObject(robj
*o
);
229 static void decrRefCount(void *o
);
230 static robj
*createObject(int type
, void *ptr
);
231 static void freeClient(redisClient
*c
);
232 static int loadDb(char *filename
);
233 static void addReply(redisClient
*c
, robj
*obj
);
234 static void addReplySds(redisClient
*c
, sds s
);
235 static void incrRefCount(robj
*o
);
236 static int saveDbBackground(char *filename
);
237 static robj
*createStringObject(char *ptr
, size_t len
);
238 static void replicationFeedSlaves(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
239 static int syncWithMaster(void);
241 static void pingCommand(redisClient
*c
);
242 static void echoCommand(redisClient
*c
);
243 static void setCommand(redisClient
*c
);
244 static void setnxCommand(redisClient
*c
);
245 static void getCommand(redisClient
*c
);
246 static void delCommand(redisClient
*c
);
247 static void existsCommand(redisClient
*c
);
248 static void incrCommand(redisClient
*c
);
249 static void decrCommand(redisClient
*c
);
250 static void incrbyCommand(redisClient
*c
);
251 static void decrbyCommand(redisClient
*c
);
252 static void selectCommand(redisClient
*c
);
253 static void randomkeyCommand(redisClient
*c
);
254 static void keysCommand(redisClient
*c
);
255 static void dbsizeCommand(redisClient
*c
);
256 static void lastsaveCommand(redisClient
*c
);
257 static void saveCommand(redisClient
*c
);
258 static void bgsaveCommand(redisClient
*c
);
259 static void shutdownCommand(redisClient
*c
);
260 static void moveCommand(redisClient
*c
);
261 static void renameCommand(redisClient
*c
);
262 static void renamenxCommand(redisClient
*c
);
263 static void lpushCommand(redisClient
*c
);
264 static void rpushCommand(redisClient
*c
);
265 static void lpopCommand(redisClient
*c
);
266 static void rpopCommand(redisClient
*c
);
267 static void llenCommand(redisClient
*c
);
268 static void lindexCommand(redisClient
*c
);
269 static void lrangeCommand(redisClient
*c
);
270 static void ltrimCommand(redisClient
*c
);
271 static void typeCommand(redisClient
*c
);
272 static void lsetCommand(redisClient
*c
);
273 static void saddCommand(redisClient
*c
);
274 static void sremCommand(redisClient
*c
);
275 static void sismemberCommand(redisClient
*c
);
276 static void scardCommand(redisClient
*c
);
277 static void sinterCommand(redisClient
*c
);
278 static void sinterstoreCommand(redisClient
*c
);
279 static void syncCommand(redisClient
*c
);
280 static void flushdbCommand(redisClient
*c
);
281 static void flushallCommand(redisClient
*c
);
282 static void sortCommand(redisClient
*c
);
283 static void lremCommand(redisClient
*c
);
284 static void infoCommand(redisClient
*c
);
285 static void mgetCommand(redisClient
*c
);
287 /*================================= Globals ================================= */
290 static struct redisServer server
; /* server global state */
291 static struct redisCommand cmdTable
[] = {
292 {"get",getCommand
,2,REDIS_CMD_INLINE
},
293 {"set",setCommand
,3,REDIS_CMD_BULK
},
294 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
},
295 {"del",delCommand
,2,REDIS_CMD_INLINE
},
296 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
297 {"incr",incrCommand
,2,REDIS_CMD_INLINE
},
298 {"decr",decrCommand
,2,REDIS_CMD_INLINE
},
299 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
300 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
},
301 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
},
302 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
303 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
304 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
305 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
306 {"lset",lsetCommand
,4,REDIS_CMD_BULK
},
307 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
308 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
309 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
310 {"sadd",saddCommand
,3,REDIS_CMD_BULK
},
311 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
312 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
313 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
314 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
},
315 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
},
316 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
317 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
},
318 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
},
319 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
320 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
321 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
322 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
323 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
324 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
325 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
326 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
327 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
328 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
329 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
330 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
331 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
332 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
333 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
334 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
335 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
336 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
},
337 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
341 /*============================ Utility functions ============================ */
343 /* Glob-style pattern matching. */
344 int stringmatchlen(const char *pattern
, int patternLen
,
345 const char *string
, int stringLen
, int nocase
)
350 while (pattern
[1] == '*') {
355 return 1; /* match */
357 if (stringmatchlen(pattern
+1, patternLen
-1,
358 string
, stringLen
, nocase
))
359 return 1; /* match */
363 return 0; /* no match */
367 return 0; /* no match */
377 not = pattern
[0] == '^';
384 if (pattern
[0] == '\\') {
387 if (pattern
[0] == string
[0])
389 } else if (pattern
[0] == ']') {
391 } else if (patternLen
== 0) {
395 } else if (pattern
[1] == '-' && patternLen
>= 3) {
396 int start
= pattern
[0];
397 int end
= pattern
[2];
405 start
= tolower(start
);
411 if (c
>= start
&& c
<= end
)
415 if (pattern
[0] == string
[0])
418 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
428 return 0; /* no match */
434 if (patternLen
>= 2) {
441 if (pattern
[0] != string
[0])
442 return 0; /* no match */
444 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
445 return 0; /* no match */
453 if (stringLen
== 0) {
454 while(*pattern
== '*') {
461 if (patternLen
== 0 && stringLen
== 0)
466 void redisLog(int level
, const char *fmt
, ...)
471 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
475 if (level
>= server
.verbosity
) {
477 fprintf(fp
,"%c ",c
[level
]);
478 vfprintf(fp
, fmt
, ap
);
484 if (server
.logfile
) fclose(fp
);
487 /*====================== Hash table type implementation ==================== */
489 /* This is an hash table type that uses the SDS dynamic strings libary as
490 * keys and radis objects as values (objects can hold SDS strings,
493 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
497 DICT_NOTUSED(privdata
);
499 l1
= sdslen((sds
)key1
);
500 l2
= sdslen((sds
)key2
);
501 if (l1
!= l2
) return 0;
502 return memcmp(key1
, key2
, l1
) == 0;
505 static void dictRedisObjectDestructor(void *privdata
, void *val
)
507 DICT_NOTUSED(privdata
);
512 static int dictSdsKeyCompare(void *privdata
, const void *key1
,
515 const robj
*o1
= key1
, *o2
= key2
;
516 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
519 static unsigned int dictSdsHash(const void *key
) {
521 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
524 static dictType setDictType
= {
525 dictSdsHash
, /* hash function */
528 dictSdsKeyCompare
, /* key compare */
529 dictRedisObjectDestructor
, /* key destructor */
530 NULL
/* val destructor */
533 static dictType hashDictType
= {
534 dictSdsHash
, /* hash function */
537 dictSdsKeyCompare
, /* key compare */
538 dictRedisObjectDestructor
, /* key destructor */
539 dictRedisObjectDestructor
/* val destructor */
542 /* ========================= Random utility functions ======================= */
544 /* Redis generally does not try to recover from out of memory conditions
545 * when allocating objects or strings, it is not clear if it will be possible
546 * to report this condition to the client since the networking layer itself
547 * is based on heap allocation for send buffers, so we simply abort.
548 * At least the code will be simpler to read... */
549 static void oom(const char *msg
) {
550 fprintf(stderr
, "%s: Out of memory\n",msg
);
556 /* ====================== Redis server networking stuff ===================== */
557 void closeTimedoutClients(void) {
561 time_t now
= time(NULL
);
563 li
= listGetIterator(server
.clients
,AL_START_HEAD
);
565 while ((ln
= listNextElement(li
)) != NULL
) {
566 c
= listNodeValue(ln
);
567 if (!(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
568 (now
- c
->lastinteraction
> server
.maxidletime
)) {
569 redisLog(REDIS_DEBUG
,"Closing idle client");
573 listReleaseIterator(li
);
576 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
577 int j
, size
, used
, loops
= server
.cronloops
++;
578 REDIS_NOTUSED(eventLoop
);
580 REDIS_NOTUSED(clientData
);
582 /* Update the global state with the amount of used memory */
583 server
.usedmemory
= zmalloc_used_memory();
585 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
586 * we resize the hash table to save memory */
587 for (j
= 0; j
< server
.dbnum
; j
++) {
588 size
= dictGetHashTableSize(server
.dict
[j
]);
589 used
= dictGetHashTableUsed(server
.dict
[j
]);
590 if (!(loops
% 5) && used
> 0) {
591 redisLog(REDIS_DEBUG
,"DB %d: %d keys in %d slots HT.",j
,used
,size
);
592 // dictPrintStats(server.dict);
594 if (size
&& used
&& size
> REDIS_HT_MINSLOTS
&&
595 (used
*100/size
< REDIS_HT_MINFILL
)) {
596 redisLog(REDIS_NOTICE
,"The hash table %d is too sparse, resize it...",j
);
597 dictResize(server
.dict
[j
]);
598 redisLog(REDIS_NOTICE
,"Hash table %d resized.",j
);
602 /* Show information about connected clients */
604 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %d bytes in use",
605 listLength(server
.clients
)-listLength(server
.slaves
),
606 listLength(server
.slaves
),
610 /* Close connections of timedout clients */
612 closeTimedoutClients();
614 /* Check if a background saving in progress terminated */
615 if (server
.bgsaveinprogress
) {
617 if (wait4(-1,&statloc
,WNOHANG
,NULL
)) {
618 int exitcode
= WEXITSTATUS(statloc
);
620 redisLog(REDIS_NOTICE
,
621 "Background saving terminated with success");
623 server
.lastsave
= time(NULL
);
625 redisLog(REDIS_WARNING
,
626 "Background saving error");
628 server
.bgsaveinprogress
= 0;
631 /* If there is not a background saving in progress check if
632 * we have to save now */
633 time_t now
= time(NULL
);
634 for (j
= 0; j
< server
.saveparamslen
; j
++) {
635 struct saveparam
*sp
= server
.saveparams
+j
;
637 if (server
.dirty
>= sp
->changes
&&
638 now
-server
.lastsave
> sp
->seconds
) {
639 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
640 sp
->changes
, sp
->seconds
);
641 saveDbBackground(server
.dbfilename
);
646 /* Check if we should connect to a MASTER */
647 if (server
.replstate
== REDIS_REPL_CONNECT
) {
648 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
649 if (syncWithMaster() == REDIS_OK
) {
650 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
656 static void createSharedObjects(void) {
657 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
658 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
659 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
660 shared
.zerobulk
= createObject(REDIS_STRING
,sdsnew("0\r\n\r\n"));
661 shared
.nil
= createObject(REDIS_STRING
,sdsnew("nil\r\n"));
662 shared
.zero
= createObject(REDIS_STRING
,sdsnew("0\r\n"));
663 shared
.one
= createObject(REDIS_STRING
,sdsnew("1\r\n"));
665 shared
.minus1
= createObject(REDIS_STRING
,sdsnew("-1\r\n"));
666 /* operation against key holding a value of the wrong type */
667 shared
.minus2
= createObject(REDIS_STRING
,sdsnew("-2\r\n"));
668 /* src and dest objects are the same */
669 shared
.minus3
= createObject(REDIS_STRING
,sdsnew("-3\r\n"));
670 /* out of range argument */
671 shared
.minus4
= createObject(REDIS_STRING
,sdsnew("-4\r\n"));
672 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
673 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
674 "-ERR Operation against a key holding the wrong kind of value\r\n"));
675 shared
.wrongtypeerrbulk
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%d\r\n%s",-sdslen(shared
.wrongtypeerr
->ptr
)+2,shared
.wrongtypeerr
->ptr
));
676 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
677 "-ERR no such key\r\n"));
678 shared
.nokeyerrbulk
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%d\r\n%s",-sdslen(shared
.nokeyerr
->ptr
)+2,shared
.nokeyerr
->ptr
));
679 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
680 "-ERR syntax error\r\n"));
681 shared
.syntaxerrbulk
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%d\r\n%s",-sdslen(shared
.syntaxerr
->ptr
)+2,shared
.syntaxerr
->ptr
));
682 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
683 shared
.select0
= createStringObject("select 0\r\n",10);
684 shared
.select1
= createStringObject("select 1\r\n",10);
685 shared
.select2
= createStringObject("select 2\r\n",10);
686 shared
.select3
= createStringObject("select 3\r\n",10);
687 shared
.select4
= createStringObject("select 4\r\n",10);
688 shared
.select5
= createStringObject("select 5\r\n",10);
689 shared
.select6
= createStringObject("select 6\r\n",10);
690 shared
.select7
= createStringObject("select 7\r\n",10);
691 shared
.select8
= createStringObject("select 8\r\n",10);
692 shared
.select9
= createStringObject("select 9\r\n",10);
695 static void appendServerSaveParams(time_t seconds
, int changes
) {
696 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
697 if (server
.saveparams
== NULL
) oom("appendServerSaveParams");
698 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
699 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
700 server
.saveparamslen
++;
703 static void ResetServerSaveParams() {
704 zfree(server
.saveparams
);
705 server
.saveparams
= NULL
;
706 server
.saveparamslen
= 0;
709 static void initServerConfig() {
710 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
711 server
.port
= REDIS_SERVERPORT
;
712 server
.verbosity
= REDIS_DEBUG
;
713 server
.maxidletime
= REDIS_MAXIDLETIME
;
714 server
.saveparams
= NULL
;
715 server
.logfile
= NULL
; /* NULL = log on standard output */
716 server
.bindaddr
= NULL
;
717 server
.glueoutputbuf
= 1;
718 server
.daemonize
= 0;
719 server
.pidfile
= "/var/run/redis.pid";
720 server
.dbfilename
= "dump.rdb";
721 ResetServerSaveParams();
723 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
724 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
725 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
726 /* Replication related */
728 server
.masterhost
= NULL
;
729 server
.masterport
= 6379;
730 server
.master
= NULL
;
731 server
.replstate
= REDIS_REPL_NONE
;
734 static void initServer() {
737 signal(SIGHUP
, SIG_IGN
);
738 signal(SIGPIPE
, SIG_IGN
);
740 server
.clients
= listCreate();
741 server
.slaves
= listCreate();
742 server
.objfreelist
= listCreate();
743 createSharedObjects();
744 server
.el
= aeCreateEventLoop();
745 server
.dict
= zmalloc(sizeof(dict
*)*server
.dbnum
);
746 if (!server
.dict
|| !server
.clients
|| !server
.slaves
|| !server
.el
|| !server
.objfreelist
)
747 oom("server initialization"); /* Fatal OOM */
748 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
749 if (server
.fd
== -1) {
750 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
753 for (j
= 0; j
< server
.dbnum
; j
++) {
754 server
.dict
[j
] = dictCreate(&hashDictType
,NULL
);
756 oom("dictCreate"); /* Fatal OOM */
758 server
.cronloops
= 0;
759 server
.bgsaveinprogress
= 0;
760 server
.lastsave
= time(NULL
);
762 server
.usedmemory
= 0;
763 server
.stat_numcommands
= 0;
764 server
.stat_numconnections
= 0;
765 server
.stat_starttime
= time(NULL
);
766 aeCreateTimeEvent(server
.el
, 1000, serverCron
, NULL
, NULL
);
769 /* Empty the whole database */
770 static void emptyDb() {
773 for (j
= 0; j
< server
.dbnum
; j
++)
774 dictEmpty(server
.dict
[j
]);
777 /* I agree, this is a very rudimental way to load a configuration...
778 will improve later if the config gets more complex */
779 static void loadServerConfig(char *filename
) {
780 FILE *fp
= fopen(filename
,"r");
781 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
786 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
789 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
795 line
= sdstrim(line
," \t\r\n");
797 /* Skip comments and blank lines*/
798 if (line
[0] == '#' || line
[0] == '\0') {
803 /* Split into arguments */
804 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
807 /* Execute config directives */
808 if (!strcmp(argv
[0],"timeout") && argc
== 2) {
809 server
.maxidletime
= atoi(argv
[1]);
810 if (server
.maxidletime
< 1) {
811 err
= "Invalid timeout value"; goto loaderr
;
813 } else if (!strcmp(argv
[0],"port") && argc
== 2) {
814 server
.port
= atoi(argv
[1]);
815 if (server
.port
< 1 || server
.port
> 65535) {
816 err
= "Invalid port"; goto loaderr
;
818 } else if (!strcmp(argv
[0],"bind") && argc
== 2) {
819 server
.bindaddr
= zstrdup(argv
[1]);
820 } else if (!strcmp(argv
[0],"save") && argc
== 3) {
821 int seconds
= atoi(argv
[1]);
822 int changes
= atoi(argv
[2]);
823 if (seconds
< 1 || changes
< 0) {
824 err
= "Invalid save parameters"; goto loaderr
;
826 appendServerSaveParams(seconds
,changes
);
827 } else if (!strcmp(argv
[0],"dir") && argc
== 2) {
828 if (chdir(argv
[1]) == -1) {
829 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
830 argv
[1], strerror(errno
));
833 } else if (!strcmp(argv
[0],"loglevel") && argc
== 2) {
834 if (!strcmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
835 else if (!strcmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
836 else if (!strcmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
838 err
= "Invalid log level. Must be one of debug, notice, warning";
841 } else if (!strcmp(argv
[0],"logfile") && argc
== 2) {
844 server
.logfile
= zstrdup(argv
[1]);
845 if (!strcmp(server
.logfile
,"stdout")) {
846 zfree(server
.logfile
);
847 server
.logfile
= NULL
;
849 if (server
.logfile
) {
850 /* Test if we are able to open the file. The server will not
851 * be able to abort just for this problem later... */
852 fp
= fopen(server
.logfile
,"a");
854 err
= sdscatprintf(sdsempty(),
855 "Can't open the log file: %s", strerror(errno
));
860 } else if (!strcmp(argv
[0],"databases") && argc
== 2) {
861 server
.dbnum
= atoi(argv
[1]);
862 if (server
.dbnum
< 1) {
863 err
= "Invalid number of databases"; goto loaderr
;
865 } else if (!strcmp(argv
[0],"slaveof") && argc
== 3) {
866 server
.masterhost
= sdsnew(argv
[1]);
867 server
.masterport
= atoi(argv
[2]);
868 server
.replstate
= REDIS_REPL_CONNECT
;
869 } else if (!strcmp(argv
[0],"glueoutputbuf") && argc
== 2) {
871 if (!strcmp(argv
[1],"yes")) server
.glueoutputbuf
= 1;
872 else if (!strcmp(argv
[1],"no")) server
.glueoutputbuf
= 0;
874 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
876 } else if (!strcmp(argv
[0],"daemonize") && argc
== 2) {
878 if (!strcmp(argv
[1],"yes")) server
.daemonize
= 1;
879 else if (!strcmp(argv
[1],"no")) server
.daemonize
= 0;
881 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
883 } else if (!strcmp(argv
[0],"pidfile") && argc
== 2) {
884 server
.pidfile
= zstrdup(argv
[1]);
886 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
888 for (j
= 0; j
< argc
; j
++)
897 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
898 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
899 fprintf(stderr
, ">>> '%s'\n", line
);
900 fprintf(stderr
, "%s\n", err
);
904 static void freeClientArgv(redisClient
*c
) {
907 for (j
= 0; j
< c
->argc
; j
++)
908 decrRefCount(c
->argv
[j
]);
912 static void freeClient(redisClient
*c
) {
915 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
916 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
917 sdsfree(c
->querybuf
);
918 listRelease(c
->reply
);
921 ln
= listSearchKey(server
.clients
,c
);
923 listDelNode(server
.clients
,ln
);
924 if (c
->flags
& REDIS_SLAVE
) {
925 ln
= listSearchKey(server
.slaves
,c
);
927 listDelNode(server
.slaves
,ln
);
929 if (c
->flags
& REDIS_MASTER
) {
930 server
.master
= NULL
;
931 server
.replstate
= REDIS_REPL_CONNECT
;
936 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
938 listNode
*ln
= c
->reply
->head
, *next
;
943 totlen
+= sdslen(o
->ptr
);
945 /* This optimization makes more sense if we don't have to copy
947 if (totlen
> 1024) return;
957 memcpy(buf
+copylen
,o
->ptr
,sdslen(o
->ptr
));
958 copylen
+= sdslen(o
->ptr
);
959 listDelNode(c
->reply
,ln
);
962 /* Now the output buffer is empty, add the new single element */
963 addReplySds(c
,sdsnewlen(buf
,totlen
));
967 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
968 redisClient
*c
= privdata
;
969 int nwritten
= 0, totwritten
= 0, objlen
;
974 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
975 glueReplyBuffersIfNeeded(c
);
976 while(listLength(c
->reply
)) {
977 o
= listNodeValue(listFirst(c
->reply
));
978 objlen
= sdslen(o
->ptr
);
981 listDelNode(c
->reply
,listFirst(c
->reply
));
985 if (c
->flags
& REDIS_MASTER
) {
986 nwritten
= objlen
- c
->sentlen
;
988 nwritten
= write(fd
, o
->ptr
+c
->sentlen
, objlen
- c
->sentlen
);
989 if (nwritten
<= 0) break;
991 c
->sentlen
+= nwritten
;
992 totwritten
+= nwritten
;
993 /* If we fully sent the object on head go to the next one */
994 if (c
->sentlen
== objlen
) {
995 listDelNode(c
->reply
,listFirst(c
->reply
));
999 if (nwritten
== -1) {
1000 if (errno
== EAGAIN
) {
1003 redisLog(REDIS_DEBUG
,
1004 "Error writing to client: %s", strerror(errno
));
1009 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1010 if (listLength(c
->reply
) == 0) {
1012 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1016 static struct redisCommand
*lookupCommand(char *name
) {
1018 while(cmdTable
[j
].name
!= NULL
) {
1019 if (!strcmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1025 /* resetClient prepare the client to process the next command */
1026 static void resetClient(redisClient
*c
) {
1031 /* If this function gets called we already read a whole
1032 * command, argments are in the client argv/argc fields.
1033 * processCommand() execute the command or prepare the
1034 * server for a bulk read from the client.
1036 * If 1 is returned the client is still alive and valid and
1037 * and other operations can be performed by the caller. Otherwise
1038 * if 0 is returned the client was destroied (i.e. after QUIT). */
1039 static int processCommand(redisClient
*c
) {
1040 struct redisCommand
*cmd
;
1043 sdstolower(c
->argv
[0]->ptr
);
1044 /* The QUIT command is handled as a special case. Normal command
1045 * procs are unable to close the client connection safely */
1046 if (!strcmp(c
->argv
[0]->ptr
,"quit")) {
1050 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1052 addReplySds(c
,sdsnew("-ERR unknown command\r\n"));
1055 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1056 (c
->argc
< -cmd
->arity
)) {
1057 addReplySds(c
,sdsnew("-ERR wrong number of arguments\r\n"));
1060 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1061 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1063 decrRefCount(c
->argv
[c
->argc
-1]);
1064 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1066 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1071 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1072 /* It is possible that the bulk read is already in the
1073 * buffer. Check this condition and handle it accordingly */
1074 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1075 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1077 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1082 /* Exec the command */
1083 dirty
= server
.dirty
;
1085 if (server
.dirty
-dirty
!= 0 && listLength(server
.slaves
))
1086 replicationFeedSlaves(cmd
,c
->dictid
,c
->argv
,c
->argc
);
1087 server
.stat_numcommands
++;
1089 /* Prepare the client for the next command */
1090 if (c
->flags
& REDIS_CLOSE
) {
1098 static void replicationFeedSlaves(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1099 listNode
*ln
= server
.slaves
->head
;
1100 robj
*outv
[REDIS_MAX_ARGS
*4]; /* enough room for args, spaces, newlines */
1103 for (j
= 0; j
< argc
; j
++) {
1104 if (j
!= 0) outv
[outc
++] = shared
.space
;
1105 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1108 lenobj
= createObject(REDIS_STRING
,
1109 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv
[j
]->ptr
)));
1110 lenobj
->refcount
= 0;
1111 outv
[outc
++] = lenobj
;
1113 outv
[outc
++] = argv
[j
];
1115 outv
[outc
++] = shared
.crlf
;
1118 redisClient
*slave
= ln
->value
;
1119 if (slave
->slaveseldb
!= dictid
) {
1123 case 0: selectcmd
= shared
.select0
; break;
1124 case 1: selectcmd
= shared
.select1
; break;
1125 case 2: selectcmd
= shared
.select2
; break;
1126 case 3: selectcmd
= shared
.select3
; break;
1127 case 4: selectcmd
= shared
.select4
; break;
1128 case 5: selectcmd
= shared
.select5
; break;
1129 case 6: selectcmd
= shared
.select6
; break;
1130 case 7: selectcmd
= shared
.select7
; break;
1131 case 8: selectcmd
= shared
.select8
; break;
1132 case 9: selectcmd
= shared
.select9
; break;
1134 selectcmd
= createObject(REDIS_STRING
,
1135 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
1136 selectcmd
->refcount
= 0;
1139 addReply(slave
,selectcmd
);
1140 slave
->slaveseldb
= dictid
;
1142 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
1147 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1148 redisClient
*c
= (redisClient
*) privdata
;
1149 char buf
[REDIS_QUERYBUF_LEN
];
1152 REDIS_NOTUSED(mask
);
1154 nread
= read(fd
, buf
, REDIS_QUERYBUF_LEN
);
1156 if (errno
== EAGAIN
) {
1159 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
1163 } else if (nread
== 0) {
1164 redisLog(REDIS_DEBUG
, "Client closed connection");
1169 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
1170 c
->lastinteraction
= time(NULL
);
1176 if (c
->bulklen
== -1) {
1177 /* Read the first line of the query */
1178 char *p
= strchr(c
->querybuf
,'\n');
1184 query
= c
->querybuf
;
1185 c
->querybuf
= sdsempty();
1186 querylen
= 1+(p
-(query
));
1187 if (sdslen(query
) > querylen
) {
1188 /* leave data after the first line of the query in the buffer */
1189 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
1191 *p
= '\0'; /* remove "\n" */
1192 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
1193 sdsupdatelen(query
);
1195 /* Now we can split the query in arguments */
1196 if (sdslen(query
) == 0) {
1197 /* Ignore empty query */
1201 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
1203 if (argv
== NULL
) oom("sdssplitlen");
1204 for (j
= 0; j
< argc
&& j
< REDIS_MAX_ARGS
; j
++) {
1205 if (sdslen(argv
[j
])) {
1206 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
1213 /* Execute the command. If the client is still valid
1214 * after processCommand() return and there is something
1215 * on the query buffer try to process the next command. */
1216 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
1218 } else if (sdslen(c
->querybuf
) >= 1024) {
1219 redisLog(REDIS_DEBUG
, "Client protocol error");
1224 /* Bulk read handling. Note that if we are at this point
1225 the client already sent a command terminated with a newline,
1226 we are reading the bulk data that is actually the last
1227 argument of the command. */
1228 int qbl
= sdslen(c
->querybuf
);
1230 if (c
->bulklen
<= qbl
) {
1231 /* Copy everything but the final CRLF as final argument */
1232 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1234 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1241 static int selectDb(redisClient
*c
, int id
) {
1242 if (id
< 0 || id
>= server
.dbnum
)
1244 c
->dict
= server
.dict
[id
];
1249 static redisClient
*createClient(int fd
) {
1250 redisClient
*c
= zmalloc(sizeof(*c
));
1252 anetNonBlock(NULL
,fd
);
1253 anetTcpNoDelay(NULL
,fd
);
1254 if (!c
) return NULL
;
1257 c
->querybuf
= sdsempty();
1262 c
->lastinteraction
= time(NULL
);
1263 if ((c
->reply
= listCreate()) == NULL
) oom("listCreate");
1264 listSetFreeMethod(c
->reply
,decrRefCount
);
1265 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1266 readQueryFromClient
, c
, NULL
) == AE_ERR
) {
1270 if (!listAddNodeTail(server
.clients
,c
)) oom("listAddNodeTail");
1274 static void addReply(redisClient
*c
, robj
*obj
) {
1275 if (listLength(c
->reply
) == 0 &&
1276 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
1277 sendReplyToClient
, c
, NULL
) == AE_ERR
) return;
1278 if (!listAddNodeTail(c
->reply
,obj
)) oom("listAddNodeTail");
1282 static void addReplySds(redisClient
*c
, sds s
) {
1283 robj
*o
= createObject(REDIS_STRING
,s
);
1288 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1292 REDIS_NOTUSED(mask
);
1293 REDIS_NOTUSED(privdata
);
1295 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
1296 if (cfd
== AE_ERR
) {
1297 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
1300 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
1301 if (createClient(cfd
) == NULL
) {
1302 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
1303 close(cfd
); /* May be already closed, just ingore errors */
1306 server
.stat_numconnections
++;
1309 /* ======================= Redis objects implementation ===================== */
1311 static robj
*createObject(int type
, void *ptr
) {
1314 if (listLength(server
.objfreelist
)) {
1315 listNode
*head
= listFirst(server
.objfreelist
);
1316 o
= listNodeValue(head
);
1317 listDelNode(server
.objfreelist
,head
);
1319 o
= zmalloc(sizeof(*o
));
1321 if (!o
) oom("createObject");
1328 static robj
*createStringObject(char *ptr
, size_t len
) {
1329 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
1332 static robj
*createListObject(void) {
1333 list
*l
= listCreate();
1335 if (!l
) oom("listCreate");
1336 listSetFreeMethod(l
,decrRefCount
);
1337 return createObject(REDIS_LIST
,l
);
1340 static robj
*createSetObject(void) {
1341 dict
*d
= dictCreate(&setDictType
,NULL
);
1342 if (!d
) oom("dictCreate");
1343 return createObject(REDIS_SET
,d
);
1347 static robj
*createHashObject(void) {
1348 dict
*d
= dictCreate(&hashDictType
,NULL
);
1349 if (!d
) oom("dictCreate");
1350 return createObject(REDIS_SET
,d
);
1354 static void freeStringObject(robj
*o
) {
1358 static void freeListObject(robj
*o
) {
1359 listRelease((list
*) o
->ptr
);
1362 static void freeSetObject(robj
*o
) {
1363 dictRelease((dict
*) o
->ptr
);
1366 static void freeHashObject(robj
*o
) {
1367 dictRelease((dict
*) o
->ptr
);
1370 static void incrRefCount(robj
*o
) {
1374 static void decrRefCount(void *obj
) {
1376 if (--(o
->refcount
) == 0) {
1378 case REDIS_STRING
: freeStringObject(o
); break;
1379 case REDIS_LIST
: freeListObject(o
); break;
1380 case REDIS_SET
: freeSetObject(o
); break;
1381 case REDIS_HASH
: freeHashObject(o
); break;
1382 default: assert(0 != 0); break;
1384 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
1385 !listAddNodeHead(server
.objfreelist
,o
))
1390 /*============================ DB saving/loading ============================ */
1392 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
1393 static int saveDb(char *filename
) {
1394 dictIterator
*di
= NULL
;
1402 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
1403 fp
= fopen(tmpfile
,"w");
1405 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
1408 if (fwrite("REDIS0000",9,1,fp
) == 0) goto werr
;
1409 for (j
= 0; j
< server
.dbnum
; j
++) {
1410 dict
*d
= server
.dict
[j
];
1411 if (dictGetHashTableUsed(d
) == 0) continue;
1412 di
= dictGetIterator(d
);
1418 /* Write the SELECT DB opcode */
1419 type
= REDIS_SELECTDB
;
1421 if (fwrite(&type
,1,1,fp
) == 0) goto werr
;
1422 if (fwrite(&len
,4,1,fp
) == 0) goto werr
;
1424 /* Iterate this DB writing every entry */
1425 while((de
= dictNext(di
)) != NULL
) {
1426 robj
*key
= dictGetEntryKey(de
);
1427 robj
*o
= dictGetEntryVal(de
);
1430 len
= htonl(sdslen(key
->ptr
));
1431 if (fwrite(&type
,1,1,fp
) == 0) goto werr
;
1432 if (fwrite(&len
,4,1,fp
) == 0) goto werr
;
1433 if (fwrite(key
->ptr
,sdslen(key
->ptr
),1,fp
) == 0) goto werr
;
1434 if (type
== REDIS_STRING
) {
1435 /* Save a string value */
1437 len
= htonl(sdslen(sval
));
1438 if (fwrite(&len
,4,1,fp
) == 0) goto werr
;
1440 fwrite(sval
,sdslen(sval
),1,fp
) == 0) goto werr
;
1441 } else if (type
== REDIS_LIST
) {
1442 /* Save a list value */
1443 list
*list
= o
->ptr
;
1444 listNode
*ln
= list
->head
;
1446 len
= htonl(listLength(list
));
1447 if (fwrite(&len
,4,1,fp
) == 0) goto werr
;
1449 robj
*eleobj
= listNodeValue(ln
);
1450 len
= htonl(sdslen(eleobj
->ptr
));
1451 if (fwrite(&len
,4,1,fp
) == 0) goto werr
;
1452 if (sdslen(eleobj
->ptr
) && fwrite(eleobj
->ptr
,sdslen(eleobj
->ptr
),1,fp
) == 0)
1456 } else if (type
== REDIS_SET
) {
1457 /* Save a set value */
1459 dictIterator
*di
= dictGetIterator(set
);
1462 if (!set
) oom("dictGetIteraotr");
1463 len
= htonl(dictGetHashTableUsed(set
));
1464 if (fwrite(&len
,4,1,fp
) == 0) goto werr
;
1465 while((de
= dictNext(di
)) != NULL
) {
1468 eleobj
= dictGetEntryKey(de
);
1469 len
= htonl(sdslen(eleobj
->ptr
));
1470 if (fwrite(&len
,4,1,fp
) == 0) goto werr
;
1471 if (sdslen(eleobj
->ptr
) && fwrite(eleobj
->ptr
,sdslen(eleobj
->ptr
),1,fp
) == 0)
1474 dictReleaseIterator(di
);
1479 dictReleaseIterator(di
);
1483 if (fwrite(&type
,1,1,fp
) == 0) goto werr
;
1488 /* Use RENAME to make sure the DB file is changed atomically only
1489 * if the generate DB file is ok. */
1490 if (rename(tmpfile
,filename
) == -1) {
1491 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destionation: %s", strerror(errno
));
1495 redisLog(REDIS_NOTICE
,"DB saved on disk");
1497 server
.lastsave
= time(NULL
);
1503 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
1504 if (di
) dictReleaseIterator(di
);
1508 static int saveDbBackground(char *filename
) {
1511 if (server
.bgsaveinprogress
) return REDIS_ERR
;
1512 if ((childpid
= fork()) == 0) {
1515 if (saveDb(filename
) == REDIS_OK
) {
1522 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
1523 server
.bgsaveinprogress
= 1;
1526 return REDIS_OK
; /* unreached */
1529 static int loadDb(char *filename
) {
1531 char buf
[REDIS_LOADBUF_LEN
]; /* Try to use this buffer instead of */
1532 char vbuf
[REDIS_LOADBUF_LEN
]; /* malloc() when the element is small */
1533 char *key
= NULL
, *val
= NULL
;
1534 uint32_t klen
,vlen
,dbid
;
1537 dict
*d
= server
.dict
[0];
1539 fp
= fopen(filename
,"r");
1540 if (!fp
) return REDIS_ERR
;
1541 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1542 if (memcmp(buf
,"REDIS0000",9) != 0) {
1544 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1551 if (fread(&type
,1,1,fp
) == 0) goto eoferr
;
1552 if (type
== REDIS_EOF
) break;
1553 /* Handle SELECT DB opcode as a special case */
1554 if (type
== REDIS_SELECTDB
) {
1555 if (fread(&dbid
,4,1,fp
) == 0) goto eoferr
;
1557 if (dbid
>= (unsigned)server
.dbnum
) {
1558 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server compiled to handle more than %d databases. Exiting\n", server
.dbnum
);
1561 d
= server
.dict
[dbid
];
1565 if (fread(&klen
,4,1,fp
) == 0) goto eoferr
;
1567 if (klen
<= REDIS_LOADBUF_LEN
) {
1570 key
= zmalloc(klen
);
1571 if (!key
) oom("Loading DB from file");
1573 if (fread(key
,klen
,1,fp
) == 0) goto eoferr
;
1575 if (type
== REDIS_STRING
) {
1576 /* Read string value */
1577 if (fread(&vlen
,4,1,fp
) == 0) goto eoferr
;
1579 if (vlen
<= REDIS_LOADBUF_LEN
) {
1582 val
= zmalloc(vlen
);
1583 if (!val
) oom("Loading DB from file");
1585 if (vlen
&& fread(val
,vlen
,1,fp
) == 0) goto eoferr
;
1586 o
= createObject(REDIS_STRING
,sdsnewlen(val
,vlen
));
1587 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
1588 /* Read list/set value */
1590 if (fread(&listlen
,4,1,fp
) == 0) goto eoferr
;
1591 listlen
= ntohl(listlen
);
1592 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
1593 /* Load every single element of the list/set */
1597 if (fread(&vlen
,4,1,fp
) == 0) goto eoferr
;
1599 if (vlen
<= REDIS_LOADBUF_LEN
) {
1602 val
= zmalloc(vlen
);
1603 if (!val
) oom("Loading DB from file");
1605 if (vlen
&& fread(val
,vlen
,1,fp
) == 0) goto eoferr
;
1606 ele
= createObject(REDIS_STRING
,sdsnewlen(val
,vlen
));
1607 if (type
== REDIS_LIST
) {
1608 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
1609 oom("listAddNodeTail");
1611 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
1614 /* free the temp buffer if needed */
1615 if (val
!= vbuf
) zfree(val
);
1621 /* Add the new object in the hash table */
1622 retval
= dictAdd(d
,createStringObject(key
,klen
),o
);
1623 if (retval
== DICT_ERR
) {
1624 redisLog(REDIS_WARNING
,"Loading DB, duplicated key found! Unrecoverable error, exiting now.");
1627 /* Iteration cleanup */
1628 if (key
!= buf
) zfree(key
);
1629 if (val
!= vbuf
) zfree(val
);
1635 eoferr
: /* unexpected end of file is handled here with a fatal exit */
1636 if (key
!= buf
) zfree(key
);
1637 if (val
!= vbuf
) zfree(val
);
1638 redisLog(REDIS_WARNING
,"Short read loading DB. Unrecoverable error, exiting now.");
1640 return REDIS_ERR
; /* Just to avoid warning */
1643 /*================================== Commands =============================== */
1645 static void pingCommand(redisClient
*c
) {
1646 addReply(c
,shared
.pong
);
1649 static void echoCommand(redisClient
*c
) {
1650 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",
1651 (int)sdslen(c
->argv
[1]->ptr
)));
1652 addReply(c
,c
->argv
[1]);
1653 addReply(c
,shared
.crlf
);
1656 /*=================================== Strings =============================== */
1658 static void setGenericCommand(redisClient
*c
, int nx
) {
1661 retval
= dictAdd(c
->dict
,c
->argv
[1],c
->argv
[2]);
1662 if (retval
== DICT_ERR
) {
1664 dictReplace(c
->dict
,c
->argv
[1],c
->argv
[2]);
1665 incrRefCount(c
->argv
[2]);
1667 addReply(c
,shared
.zero
);
1671 incrRefCount(c
->argv
[1]);
1672 incrRefCount(c
->argv
[2]);
1675 addReply(c
, nx
? shared
.one
: shared
.ok
);
1678 static void setCommand(redisClient
*c
) {
1679 return setGenericCommand(c
,0);
1682 static void setnxCommand(redisClient
*c
) {
1683 return setGenericCommand(c
,1);
1686 static void getCommand(redisClient
*c
) {
1689 de
= dictFind(c
->dict
,c
->argv
[1]);
1691 addReply(c
,shared
.nil
);
1693 robj
*o
= dictGetEntryVal(de
);
1695 if (o
->type
!= REDIS_STRING
) {
1696 addReply(c
,shared
.wrongtypeerrbulk
);
1698 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",(int)sdslen(o
->ptr
)));
1700 addReply(c
,shared
.crlf
);
1705 static void mgetCommand(redisClient
*c
) {
1709 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",c
->argc
-1));
1710 for (j
= 1; j
< c
->argc
; j
++) {
1711 de
= dictFind(c
->dict
,c
->argv
[j
]);
1713 addReply(c
,shared
.minus1
);
1715 robj
*o
= dictGetEntryVal(de
);
1717 if (o
->type
!= REDIS_STRING
) {
1718 addReply(c
,shared
.minus1
);
1720 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",(int)sdslen(o
->ptr
)));
1722 addReply(c
,shared
.crlf
);
1728 static void incrDecrCommand(redisClient
*c
, int incr
) {
1734 de
= dictFind(c
->dict
,c
->argv
[1]);
1738 robj
*o
= dictGetEntryVal(de
);
1740 if (o
->type
!= REDIS_STRING
) {
1745 value
= strtoll(o
->ptr
, &eptr
, 10);
1750 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
1751 retval
= dictAdd(c
->dict
,c
->argv
[1],o
);
1752 if (retval
== DICT_ERR
) {
1753 dictReplace(c
->dict
,c
->argv
[1],o
);
1755 incrRefCount(c
->argv
[1]);
1759 addReply(c
,shared
.crlf
);
1762 static void incrCommand(redisClient
*c
) {
1763 return incrDecrCommand(c
,1);
1766 static void decrCommand(redisClient
*c
) {
1767 return incrDecrCommand(c
,-1);
1770 static void incrbyCommand(redisClient
*c
) {
1771 int incr
= atoi(c
->argv
[2]->ptr
);
1772 return incrDecrCommand(c
,incr
);
1775 static void decrbyCommand(redisClient
*c
) {
1776 int incr
= atoi(c
->argv
[2]->ptr
);
1777 return incrDecrCommand(c
,-incr
);
1780 /* ========================= Type agnostic commands ========================= */
1782 static void delCommand(redisClient
*c
) {
1783 if (dictDelete(c
->dict
,c
->argv
[1]) == DICT_OK
) {
1785 addReply(c
,shared
.one
);
1787 addReply(c
,shared
.zero
);
1791 static void existsCommand(redisClient
*c
) {
1794 de
= dictFind(c
->dict
,c
->argv
[1]);
1796 addReply(c
,shared
.zero
);
1798 addReply(c
,shared
.one
);
1801 static void selectCommand(redisClient
*c
) {
1802 int id
= atoi(c
->argv
[1]->ptr
);
1804 if (selectDb(c
,id
) == REDIS_ERR
) {
1805 addReplySds(c
,"-ERR invalid DB index\r\n");
1807 addReply(c
,shared
.ok
);
1811 static void randomkeyCommand(redisClient
*c
) {
1814 de
= dictGetRandomKey(c
->dict
);
1816 addReply(c
,shared
.crlf
);
1818 addReply(c
,dictGetEntryKey(de
));
1819 addReply(c
,shared
.crlf
);
1823 static void keysCommand(redisClient
*c
) {
1826 sds pattern
= c
->argv
[1]->ptr
;
1827 int plen
= sdslen(pattern
);
1828 int numkeys
= 0, keyslen
= 0;
1829 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
1831 di
= dictGetIterator(c
->dict
);
1832 if (!di
) oom("dictGetIterator");
1834 decrRefCount(lenobj
);
1835 while((de
= dictNext(di
)) != NULL
) {
1836 robj
*keyobj
= dictGetEntryKey(de
);
1837 sds key
= keyobj
->ptr
;
1838 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
1839 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
1841 addReply(c
,shared
.space
);
1844 keyslen
+= sdslen(key
);
1847 dictReleaseIterator(di
);
1848 lenobj
->ptr
= sdscatprintf(sdsempty(),"%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
1849 addReply(c
,shared
.crlf
);
1852 static void dbsizeCommand(redisClient
*c
) {
1854 sdscatprintf(sdsempty(),"%lu\r\n",dictGetHashTableUsed(c
->dict
)));
1857 static void lastsaveCommand(redisClient
*c
) {
1859 sdscatprintf(sdsempty(),"%lu\r\n",server
.lastsave
));
1862 static void typeCommand(redisClient
*c
) {
1866 de
= dictFind(c
->dict
,c
->argv
[1]);
1870 robj
*o
= dictGetEntryVal(de
);
1873 case REDIS_STRING
: type
= "string"; break;
1874 case REDIS_LIST
: type
= "list"; break;
1875 case REDIS_SET
: type
= "set"; break;
1876 default: type
= "unknown"; break;
1879 addReplySds(c
,sdsnew(type
));
1880 addReply(c
,shared
.crlf
);
1883 static void saveCommand(redisClient
*c
) {
1884 if (saveDb(server
.dbfilename
) == REDIS_OK
) {
1885 addReply(c
,shared
.ok
);
1887 addReply(c
,shared
.err
);
1891 static void bgsaveCommand(redisClient
*c
) {
1892 if (server
.bgsaveinprogress
) {
1893 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
1896 if (saveDbBackground(server
.dbfilename
) == REDIS_OK
) {
1897 addReply(c
,shared
.ok
);
1899 addReply(c
,shared
.err
);
1903 static void shutdownCommand(redisClient
*c
) {
1904 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1905 if (saveDb(server
.dbfilename
) == REDIS_OK
) {
1906 if (server
.daemonize
) {
1907 unlink(server
.pidfile
);
1909 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1912 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1913 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
1917 static void renameGenericCommand(redisClient
*c
, int nx
) {
1921 /* To use the same key as src and dst is probably an error */
1922 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
1924 addReply(c
,shared
.minus3
);
1926 addReplySds(c
,sdsnew("-ERR src and dest key are the same\r\n"));
1930 de
= dictFind(c
->dict
,c
->argv
[1]);
1933 addReply(c
,shared
.minus1
);
1935 addReply(c
,shared
.nokeyerr
);
1938 o
= dictGetEntryVal(de
);
1940 if (dictAdd(c
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
1943 addReply(c
,shared
.zero
);
1946 dictReplace(c
->dict
,c
->argv
[2],o
);
1948 incrRefCount(c
->argv
[2]);
1950 dictDelete(c
->dict
,c
->argv
[1]);
1952 addReply(c
,nx
? shared
.one
: shared
.ok
);
1955 static void renameCommand(redisClient
*c
) {
1956 renameGenericCommand(c
,0);
1959 static void renamenxCommand(redisClient
*c
) {
1960 renameGenericCommand(c
,1);
1963 static void moveCommand(redisClient
*c
) {
1969 /* Obtain source and target DB pointers */
1972 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
1973 addReply(c
,shared
.minus4
);
1980 /* If the user is moving using as target the same
1981 * DB as the source DB it is probably an error. */
1983 addReply(c
,shared
.minus3
);
1987 /* Check if the element exists and get a reference */
1988 de
= dictFind(c
->dict
,c
->argv
[1]);
1990 addReply(c
,shared
.zero
);
1994 /* Try to add the element to the target DB */
1995 key
= dictGetEntryKey(de
);
1996 o
= dictGetEntryVal(de
);
1997 if (dictAdd(dst
,key
,o
) == DICT_ERR
) {
1998 addReply(c
,shared
.zero
);
2004 /* OK! key moved, free the entry in the source DB */
2005 dictDelete(src
,c
->argv
[1]);
2007 addReply(c
,shared
.one
);
2010 /* =================================== Lists ================================ */
2011 static void pushGenericCommand(redisClient
*c
, int where
) {
2016 de
= dictFind(c
->dict
,c
->argv
[1]);
2018 lobj
= createListObject();
2020 if (where
== REDIS_HEAD
) {
2021 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2023 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2025 dictAdd(c
->dict
,c
->argv
[1],lobj
);
2026 incrRefCount(c
->argv
[1]);
2027 incrRefCount(c
->argv
[2]);
2029 lobj
= dictGetEntryVal(de
);
2030 if (lobj
->type
!= REDIS_LIST
) {
2031 addReply(c
,shared
.wrongtypeerr
);
2035 if (where
== REDIS_HEAD
) {
2036 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2038 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2040 incrRefCount(c
->argv
[2]);
2043 addReply(c
,shared
.ok
);
2046 static void lpushCommand(redisClient
*c
) {
2047 pushGenericCommand(c
,REDIS_HEAD
);
2050 static void rpushCommand(redisClient
*c
) {
2051 pushGenericCommand(c
,REDIS_TAIL
);
2054 static void llenCommand(redisClient
*c
) {
2058 de
= dictFind(c
->dict
,c
->argv
[1]);
2060 addReply(c
,shared
.zero
);
2063 robj
*o
= dictGetEntryVal(de
);
2064 if (o
->type
!= REDIS_LIST
) {
2065 addReply(c
,shared
.minus2
);
2068 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",listLength(l
)));
2073 static void lindexCommand(redisClient
*c
) {
2075 int index
= atoi(c
->argv
[2]->ptr
);
2077 de
= dictFind(c
->dict
,c
->argv
[1]);
2079 addReply(c
,shared
.nil
);
2081 robj
*o
= dictGetEntryVal(de
);
2083 if (o
->type
!= REDIS_LIST
) {
2084 addReply(c
,shared
.wrongtypeerrbulk
);
2086 list
*list
= o
->ptr
;
2089 ln
= listIndex(list
, index
);
2091 addReply(c
,shared
.nil
);
2093 robj
*ele
= listNodeValue(ln
);
2094 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",(int)sdslen(ele
->ptr
)));
2096 addReply(c
,shared
.crlf
);
2102 static void lsetCommand(redisClient
*c
) {
2104 int index
= atoi(c
->argv
[2]->ptr
);
2106 de
= dictFind(c
->dict
,c
->argv
[1]);
2108 addReply(c
,shared
.nokeyerr
);
2110 robj
*o
= dictGetEntryVal(de
);
2112 if (o
->type
!= REDIS_LIST
) {
2113 addReply(c
,shared
.wrongtypeerr
);
2115 list
*list
= o
->ptr
;
2118 ln
= listIndex(list
, index
);
2120 addReplySds(c
,sdsnew("-ERR index out of range\r\n"));
2122 robj
*ele
= listNodeValue(ln
);
2125 listNodeValue(ln
) = c
->argv
[3];
2126 incrRefCount(c
->argv
[3]);
2127 addReply(c
,shared
.ok
);
2134 static void popGenericCommand(redisClient
*c
, int where
) {
2137 de
= dictFind(c
->dict
,c
->argv
[1]);
2139 addReply(c
,shared
.nil
);
2141 robj
*o
= dictGetEntryVal(de
);
2143 if (o
->type
!= REDIS_LIST
) {
2144 addReply(c
,shared
.wrongtypeerrbulk
);
2146 list
*list
= o
->ptr
;
2149 if (where
== REDIS_HEAD
)
2150 ln
= listFirst(list
);
2152 ln
= listLast(list
);
2155 addReply(c
,shared
.nil
);
2157 robj
*ele
= listNodeValue(ln
);
2158 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",(int)sdslen(ele
->ptr
)));
2160 addReply(c
,shared
.crlf
);
2161 listDelNode(list
,ln
);
2168 static void lpopCommand(redisClient
*c
) {
2169 popGenericCommand(c
,REDIS_HEAD
);
2172 static void rpopCommand(redisClient
*c
) {
2173 popGenericCommand(c
,REDIS_TAIL
);
2176 static void lrangeCommand(redisClient
*c
) {
2178 int start
= atoi(c
->argv
[2]->ptr
);
2179 int end
= atoi(c
->argv
[3]->ptr
);
2181 de
= dictFind(c
->dict
,c
->argv
[1]);
2183 addReply(c
,shared
.nil
);
2185 robj
*o
= dictGetEntryVal(de
);
2187 if (o
->type
!= REDIS_LIST
) {
2188 addReply(c
,shared
.wrongtypeerrbulk
);
2190 list
*list
= o
->ptr
;
2192 int llen
= listLength(list
);
2196 /* convert negative indexes */
2197 if (start
< 0) start
= llen
+start
;
2198 if (end
< 0) end
= llen
+end
;
2199 if (start
< 0) start
= 0;
2200 if (end
< 0) end
= 0;
2202 /* indexes sanity checks */
2203 if (start
> end
|| start
>= llen
) {
2204 /* Out of range start or start > end result in empty list */
2205 addReply(c
,shared
.zero
);
2208 if (end
>= llen
) end
= llen
-1;
2209 rangelen
= (end
-start
)+1;
2211 /* Return the result in form of a multi-bulk reply */
2212 ln
= listIndex(list
, start
);
2213 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",rangelen
));
2214 for (j
= 0; j
< rangelen
; j
++) {
2215 ele
= listNodeValue(ln
);
2216 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",(int)sdslen(ele
->ptr
)));
2218 addReply(c
,shared
.crlf
);
2225 static void ltrimCommand(redisClient
*c
) {
2227 int start
= atoi(c
->argv
[2]->ptr
);
2228 int end
= atoi(c
->argv
[3]->ptr
);
2230 de
= dictFind(c
->dict
,c
->argv
[1]);
2232 addReply(c
,shared
.nokeyerr
);
2234 robj
*o
= dictGetEntryVal(de
);
2236 if (o
->type
!= REDIS_LIST
) {
2237 addReply(c
,shared
.wrongtypeerr
);
2239 list
*list
= o
->ptr
;
2241 int llen
= listLength(list
);
2242 int j
, ltrim
, rtrim
;
2244 /* convert negative indexes */
2245 if (start
< 0) start
= llen
+start
;
2246 if (end
< 0) end
= llen
+end
;
2247 if (start
< 0) start
= 0;
2248 if (end
< 0) end
= 0;
2250 /* indexes sanity checks */
2251 if (start
> end
|| start
>= llen
) {
2252 /* Out of range start or start > end result in empty list */
2256 if (end
>= llen
) end
= llen
-1;
2261 /* Remove list elements to perform the trim */
2262 for (j
= 0; j
< ltrim
; j
++) {
2263 ln
= listFirst(list
);
2264 listDelNode(list
,ln
);
2266 for (j
= 0; j
< rtrim
; j
++) {
2267 ln
= listLast(list
);
2268 listDelNode(list
,ln
);
2270 addReply(c
,shared
.ok
);
2276 static void lremCommand(redisClient
*c
) {
2279 de
= dictFind(c
->dict
,c
->argv
[1]);
2281 addReply(c
,shared
.minus1
);
2283 robj
*o
= dictGetEntryVal(de
);
2285 if (o
->type
!= REDIS_LIST
) {
2286 addReply(c
,shared
.minus2
);
2288 list
*list
= o
->ptr
;
2289 listNode
*ln
, *next
;
2290 int toremove
= atoi(c
->argv
[2]->ptr
);
2295 toremove
= -toremove
;
2298 ln
= fromtail
? list
->tail
: list
->head
;
2300 next
= fromtail
? ln
->prev
: ln
->next
;
2301 robj
*ele
= listNodeValue(ln
);
2302 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2303 listDelNode(list
,ln
);
2306 if (toremove
&& removed
== toremove
) break;
2310 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",removed
));
2315 /* ==================================== Sets ================================ */
2317 static void saddCommand(redisClient
*c
) {
2321 de
= dictFind(c
->dict
,c
->argv
[1]);
2323 set
= createSetObject();
2324 dictAdd(c
->dict
,c
->argv
[1],set
);
2325 incrRefCount(c
->argv
[1]);
2327 set
= dictGetEntryVal(de
);
2328 if (set
->type
!= REDIS_SET
) {
2329 addReply(c
,shared
.minus2
);
2333 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2334 incrRefCount(c
->argv
[2]);
2336 addReply(c
,shared
.one
);
2338 addReply(c
,shared
.zero
);
2342 static void sremCommand(redisClient
*c
) {
2345 de
= dictFind(c
->dict
,c
->argv
[1]);
2347 addReply(c
,shared
.zero
);
2351 set
= dictGetEntryVal(de
);
2352 if (set
->type
!= REDIS_SET
) {
2353 addReply(c
,shared
.minus2
);
2356 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2358 addReply(c
,shared
.one
);
2360 addReply(c
,shared
.zero
);
2365 static void sismemberCommand(redisClient
*c
) {
2368 de
= dictFind(c
->dict
,c
->argv
[1]);
2370 addReply(c
,shared
.zero
);
2374 set
= dictGetEntryVal(de
);
2375 if (set
->type
!= REDIS_SET
) {
2376 addReply(c
,shared
.minus2
);
2379 if (dictFind(set
->ptr
,c
->argv
[2]))
2380 addReply(c
,shared
.one
);
2382 addReply(c
,shared
.zero
);
2386 static void scardCommand(redisClient
*c
) {
2390 de
= dictFind(c
->dict
,c
->argv
[1]);
2392 addReply(c
,shared
.zero
);
2395 robj
*o
= dictGetEntryVal(de
);
2396 if (o
->type
!= REDIS_SET
) {
2397 addReply(c
,shared
.minus2
);
2400 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",
2401 dictGetHashTableUsed(s
)));
2406 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2407 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2409 return dictGetHashTableUsed(*d1
)-dictGetHashTableUsed(*d2
);
2412 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2413 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2416 robj
*lenobj
= NULL
, *dstset
= NULL
;
2417 int j
, cardinality
= 0;
2419 if (!dv
) oom("sinterCommand");
2420 for (j
= 0; j
< setsnum
; j
++) {
2424 de
= dictFind(c
->dict
,setskeys
[j
]);
2427 addReply(c
,dstkey
? shared
.nokeyerr
: shared
.nil
);
2430 setobj
= dictGetEntryVal(de
);
2431 if (setobj
->type
!= REDIS_SET
) {
2433 addReply(c
,dstkey
? shared
.wrongtypeerr
: shared
.wrongtypeerrbulk
);
2436 dv
[j
] = setobj
->ptr
;
2438 /* Sort sets from the smallest to largest, this will improve our
2439 * algorithm's performace */
2440 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2442 /* The first thing we should output is the total number of elements...
2443 * since this is a multi-bulk write, but at this stage we don't know
2444 * the intersection set size, so we use a trick, append an empty object
2445 * to the output list and save the pointer to later modify it with the
2448 lenobj
= createObject(REDIS_STRING
,NULL
);
2450 decrRefCount(lenobj
);
2452 /* If we have a target key where to store the resulting set
2453 * create this key with an empty set inside */
2454 dstset
= createSetObject();
2455 dictDelete(c
->dict
,dstkey
);
2456 dictAdd(c
->dict
,dstkey
,dstset
);
2457 incrRefCount(dstkey
);
2460 /* Iterate all the elements of the first (smallest) set, and test
2461 * the element against all the other sets, if at least one set does
2462 * not include the element it is discarded */
2463 di
= dictGetIterator(dv
[0]);
2464 if (!di
) oom("dictGetIterator");
2466 while((de
= dictNext(di
)) != NULL
) {
2469 for (j
= 1; j
< setsnum
; j
++)
2470 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2472 continue; /* at least one set does not contain the member */
2473 ele
= dictGetEntryKey(de
);
2475 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",sdslen(ele
->ptr
)));
2477 addReply(c
,shared
.crlf
);
2480 dictAdd(dstset
->ptr
,ele
,NULL
);
2484 dictReleaseIterator(di
);
2487 lenobj
->ptr
= sdscatprintf(sdsempty(),"%d\r\n",cardinality
);
2489 addReply(c
,shared
.ok
);
2493 static void sinterCommand(redisClient
*c
) {
2494 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2497 static void sinterstoreCommand(redisClient
*c
) {
2498 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2501 static void flushdbCommand(redisClient
*c
) {
2503 addReply(c
,shared
.ok
);
2504 saveDb(server
.dbfilename
);
2507 static void flushallCommand(redisClient
*c
) {
2509 addReply(c
,shared
.ok
);
2510 saveDb(server
.dbfilename
);
2513 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2514 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2515 if (!so
) oom("createSortOperation");
2517 so
->pattern
= pattern
;
2521 /* Return the value associated to the key with a name obtained
2522 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2523 robj
*lookupKeyByPattern(dict
*dict
, robj
*pattern
, robj
*subst
) {
2527 int prefixlen
, sublen
, postfixlen
;
2529 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2533 char buf
[REDIS_SORTKEY_MAX
+1];
2537 spat
= pattern
->ptr
;
2539 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2540 p
= strchr(spat
,'*');
2541 if (!p
) return NULL
;
2544 sublen
= sdslen(ssub
);
2545 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2546 memcpy(keyname
.buf
,spat
,prefixlen
);
2547 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2548 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2549 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2550 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2552 keyobj
.refcount
= 1;
2553 keyobj
.type
= REDIS_STRING
;
2554 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2556 de
= dictFind(dict
,&keyobj
);
2557 // printf("lookup '%s' => %p\n", keyname.buf,de);
2558 if (!de
) return NULL
;
2559 return dictGetEntryVal(de
);
2562 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2563 * the additional parameter is not standard but a BSD-specific we have to
2564 * pass sorting parameters via the global 'server' structure */
2565 static int sortCompare(const void *s1
, const void *s2
) {
2566 const redisSortObject
*so1
= s1
, *so2
= s2
;
2569 if (!server
.sort_alpha
) {
2570 /* Numeric sorting. Here it's trivial as we precomputed scores */
2571 if (so1
->u
.score
> so2
->u
.score
) {
2573 } else if (so1
->u
.score
< so2
->u
.score
) {
2579 /* Alphanumeric sorting */
2580 if (server
.sort_bypattern
) {
2581 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2582 /* At least one compare object is NULL */
2583 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2585 else if (so1
->u
.cmpobj
== NULL
)
2590 /* We have both the objects, use strcoll */
2591 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2594 /* Compare elements directly */
2595 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
2598 return server
.sort_desc
? -cmp
: cmp
;
2601 /* The SORT command is the most complex command in Redis. Warning: this code
2602 * is optimized for speed and a bit less for readability */
2603 static void sortCommand(redisClient
*c
) {
2607 int desc
= 0, alpha
= 0;
2608 int limit_start
= 0, limit_count
= -1, start
, end
;
2609 int j
, dontsort
= 0, vectorlen
;
2610 int getop
= 0; /* GET operation counter */
2611 robj
*sortval
, *sortby
= NULL
;
2612 redisSortObject
*vector
; /* Resulting vector to sort */
2614 /* Lookup the key to sort. It must be of the right types */
2615 de
= dictFind(c
->dict
,c
->argv
[1]);
2617 addReply(c
,shared
.nokeyerrbulk
);
2620 sortval
= dictGetEntryVal(de
);
2621 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
2622 addReply(c
,shared
.wrongtypeerrbulk
);
2626 /* Create a list of operations to perform for every sorted element.
2627 * Operations can be GET/DEL/INCR/DECR */
2628 operations
= listCreate();
2629 listSetFreeMethod(operations
,zfree
);
2632 /* Now we need to protect sortval incrementing its count, in the future
2633 * SORT may have options able to overwrite/delete keys during the sorting
2634 * and the sorted key itself may get destroied */
2635 incrRefCount(sortval
);
2637 /* The SORT command has an SQL-alike syntax, parse it */
2638 while(j
< c
->argc
) {
2639 int leftargs
= c
->argc
-j
-1;
2640 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
2642 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
2644 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
2646 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
2647 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
2648 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
2650 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
2651 sortby
= c
->argv
[j
+1];
2652 /* If the BY pattern does not contain '*', i.e. it is constant,
2653 * we don't need to sort nor to lookup the weight keys. */
2654 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
2656 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2657 listAddNodeTail(operations
,createSortOperation(
2658 REDIS_SORT_GET
,c
->argv
[j
+1]));
2661 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
2662 listAddNodeTail(operations
,createSortOperation(
2663 REDIS_SORT_DEL
,c
->argv
[j
+1]));
2665 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
2666 listAddNodeTail(operations
,createSortOperation(
2667 REDIS_SORT_INCR
,c
->argv
[j
+1]));
2669 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2670 listAddNodeTail(operations
,createSortOperation(
2671 REDIS_SORT_DECR
,c
->argv
[j
+1]));
2674 decrRefCount(sortval
);
2675 listRelease(operations
);
2676 addReply(c
,shared
.syntaxerrbulk
);
2682 /* Load the sorting vector with all the objects to sort */
2683 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
2684 listLength((list
*)sortval
->ptr
) :
2685 dictGetHashTableUsed((dict
*)sortval
->ptr
);
2686 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
2687 if (!vector
) oom("allocating objects vector for SORT");
2689 if (sortval
->type
== REDIS_LIST
) {
2690 list
*list
= sortval
->ptr
;
2691 listNode
*ln
= list
->head
;
2693 robj
*ele
= ln
->value
;
2694 vector
[j
].obj
= ele
;
2695 vector
[j
].u
.score
= 0;
2696 vector
[j
].u
.cmpobj
= NULL
;
2701 dict
*set
= sortval
->ptr
;
2705 di
= dictGetIterator(set
);
2706 if (!di
) oom("dictGetIterator");
2707 while((setele
= dictNext(di
)) != NULL
) {
2708 vector
[j
].obj
= dictGetEntryKey(setele
);
2709 vector
[j
].u
.score
= 0;
2710 vector
[j
].u
.cmpobj
= NULL
;
2713 dictReleaseIterator(di
);
2715 assert(j
== vectorlen
);
2717 /* Now it's time to load the right scores in the sorting vector */
2718 if (dontsort
== 0) {
2719 for (j
= 0; j
< vectorlen
; j
++) {
2723 byval
= lookupKeyByPattern(c
->dict
,sortby
,vector
[j
].obj
);
2724 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
2726 vector
[j
].u
.cmpobj
= byval
;
2727 incrRefCount(byval
);
2729 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
2732 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
2737 /* We are ready to sort the vector... perform a bit of sanity check
2738 * on the LIMIT option too. We'll use a partial version of quicksort. */
2739 start
= (limit_start
< 0) ? 0 : limit_start
;
2740 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
2741 if (start
>= vectorlen
) {
2742 start
= vectorlen
-1;
2745 if (end
>= vectorlen
) end
= vectorlen
-1;
2747 if (dontsort
== 0) {
2748 server
.sort_desc
= desc
;
2749 server
.sort_alpha
= alpha
;
2750 server
.sort_bypattern
= sortby
? 1 : 0;
2751 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
2754 /* Send command output to the output buffer, performing the specified
2755 * GET/DEL/INCR/DECR operations if any. */
2756 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
2757 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",outputlen
));
2758 for (j
= start
; j
<= end
; j
++) {
2759 listNode
*ln
= operations
->head
;
2761 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",
2762 sdslen(vector
[j
].obj
->ptr
)));
2763 addReply(c
,vector
[j
].obj
);
2764 addReply(c
,shared
.crlf
);
2767 redisSortOperation
*sop
= ln
->value
;
2768 robj
*val
= lookupKeyByPattern(c
->dict
,sop
->pattern
,
2771 if (sop
->type
== REDIS_SORT_GET
) {
2772 if (!val
|| val
->type
!= REDIS_STRING
) {
2773 addReply(c
,shared
.minus1
);
2775 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",
2778 addReply(c
,shared
.crlf
);
2780 } else if (sop
->type
== REDIS_SORT_DEL
) {
2788 decrRefCount(sortval
);
2789 listRelease(operations
);
2790 for (j
= 0; j
< vectorlen
; j
++) {
2791 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
2792 decrRefCount(vector
[j
].u
.cmpobj
);
2797 static void infoCommand(redisClient
*c
) {
2799 time_t uptime
= time(NULL
)-server
.stat_starttime
;
2801 info
= sdscatprintf(sdsempty(),
2802 "redis_version:%s\r\n"
2803 "connected_clients:%d\r\n"
2804 "connected_slaves:%d\r\n"
2805 "used_memory:%d\r\n"
2806 "changes_since_last_save:%lld\r\n"
2807 "last_save_time:%d\r\n"
2808 "total_connections_received:%lld\r\n"
2809 "total_commands_processed:%lld\r\n"
2810 "uptime_in_seconds:%d\r\n"
2811 "uptime_in_days:%d\r\n"
2813 listLength(server
.clients
)-listLength(server
.slaves
),
2814 listLength(server
.slaves
),
2818 server
.stat_numconnections
,
2819 server
.stat_numcommands
,
2823 addReplySds(c
,sdscatprintf(sdsempty(),"%d\r\n",sdslen(info
)));
2824 addReplySds(c
,info
);
2825 addReply(c
,shared
.crlf
);
2828 /* =============================== Replication ============================= */
2830 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
2831 static int flushClientOutput(redisClient
*c
) {
2833 time_t start
= time(NULL
);
2835 while(listLength(c
->reply
)) {
2836 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
2837 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
2840 } else if (retval
& AE_WRITABLE
) {
2841 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
2847 static int syncWrite(int fd
, void *ptr
, ssize_t size
, int timeout
) {
2848 ssize_t nwritten
, ret
= size
;
2849 time_t start
= time(NULL
);
2853 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
2854 nwritten
= write(fd
,ptr
,size
);
2855 if (nwritten
== -1) return -1;
2859 if ((time(NULL
)-start
) > timeout
) {
2867 static int syncRead(int fd
, void *ptr
, ssize_t size
, int timeout
) {
2868 ssize_t nread
, totread
= 0;
2869 time_t start
= time(NULL
);
2873 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
2874 nread
= read(fd
,ptr
,size
);
2875 if (nread
== -1) return -1;
2880 if ((time(NULL
)-start
) > timeout
) {
2888 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
2895 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
2898 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
2909 static void syncCommand(redisClient
*c
) {
2912 time_t start
= time(NULL
);
2915 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
2916 if (flushClientOutput(c
) == REDIS_ERR
|| saveDb(server
.dbfilename
) != REDIS_OK
)
2919 fd
= open(server
.dbfilename
, O_RDONLY
);
2920 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
2923 snprintf(sizebuf
,32,"%d\r\n",len
);
2924 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
2929 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
2930 nread
= read(fd
,buf
,1024);
2931 if (nread
== -1) goto closeconn
;
2933 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
2935 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
2937 c
->flags
|= REDIS_SLAVE
;
2939 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
2940 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
2944 if (fd
!= -1) close(fd
);
2945 c
->flags
|= REDIS_CLOSE
;
2946 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
2950 static int syncWithMaster(void) {
2951 char buf
[1024], tmpfile
[256];
2953 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
2957 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
2961 /* Issue the SYNC command */
2962 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
2964 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
2968 /* Read the bulk write count */
2969 if (syncReadLine(fd
,buf
,1024,5) == -1) {
2971 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
2975 dumpsize
= atoi(buf
);
2976 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
2977 /* Read the bulk write data on a temp file */
2978 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
2979 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
2982 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
2986 int nread
, nwritten
;
2988 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
2990 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
2996 nwritten
= write(dfd
,buf
,nread
);
2997 if (nwritten
== -1) {
2998 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3006 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3007 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3013 if (loadDb(server
.dbfilename
) != REDIS_OK
) {
3014 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3018 server
.master
= createClient(fd
);
3019 server
.master
->flags
|= REDIS_MASTER
;
3020 server
.replstate
= REDIS_REPL_CONNECTED
;
3024 /* =================================== Main! ================================ */
3026 static void daemonize(void) {
3030 if (fork() != 0) exit(0); /* parent exits */
3031 setsid(); /* create a new session */
3033 /* Every output goes to /dev/null. If Redis is daemonized but
3034 * the 'logfile' is set to 'stdout' in the configuration file
3035 * it will not log at all. */
3036 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3037 dup2(fd
, STDIN_FILENO
);
3038 dup2(fd
, STDOUT_FILENO
);
3039 dup2(fd
, STDERR_FILENO
);
3040 if (fd
> STDERR_FILENO
) close(fd
);
3042 /* Try to write the pid file */
3043 fp
= fopen(server
.pidfile
,"w");
3045 fprintf(fp
,"%d\n",getpid());
3050 int main(int argc
, char **argv
) {
3053 ResetServerSaveParams();
3054 loadServerConfig(argv
[1]);
3055 } else if (argc
> 2) {
3056 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3060 if (server
.daemonize
) daemonize();
3061 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3062 if (loadDb(server
.dbfilename
) == REDIS_OK
)
3063 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3064 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3065 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3066 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3068 aeDeleteEventLoop(server
.el
);