2 * Copyright (c) 2009-2010, 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.
41 #include <arpa/inet.h>
45 #include <sys/resource.h>
50 #include <sys/resource.h>
51 #include <sys/utsname.h>
53 /* Our shared "common" objects */
55 struct sharedObjectsStruct shared
;
57 /* Global vars that are actually used as constants. The following double
58 * values are used for double on-disk serialization, and are initialized
59 * at runtime to avoid strange compiler optimizations. */
61 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
63 /*================================= Globals ================================= */
66 struct redisServer server
; /* server global state */
67 struct redisCommand
*commandTable
;
71 * Every entry is composed of the following fields:
73 * name: a string representing the command name.
74 * function: pointer to the C function implementing the command.
75 * arity: number of arguments, it is possible to use -N to say >= N
76 * sflags: command flags as string. See below for a table of flags.
77 * flags: flags as bitmask. Computed by Redis using the 'sflags' field.
78 * get_keys_proc: an optional function to get key arguments from a command.
79 * This is only used when the following three fields are not
80 * enough to specify what arguments are keys.
81 * first_key_index: first argument that is a key
82 * last_key_index: last argument that is a key
83 * key_step: step to get all the keys from first to last argument. For instance
84 * in MSET the step is two since arguments are key,val,key,val,...
85 * microseconds: microseconds of total execution time for this command.
86 * calls: total number of calls of this command.
88 * The flags, microseconds and calls fields are computed by Redis and should
89 * always be set to zero.
91 * Command flags are expressed using strings where every character represents
92 * a flag. Later the populateCommandTable() function will take care of
93 * populating the real 'flags' field using this characters.
95 * This is the meaning of the flags:
97 * w: write command (may modify the key space).
98 * r: read command (will never modify the key space).
99 * m: may increase memory usage once called. Don't allow if out of memory.
100 * a: admin command, like SAVE or SHUTDOWN.
101 * p: Pub/Sub related command.
102 * f: force replication of this command, regarless of server.dirty.
103 * s: command not allowed in scripts.
104 * R: random command. Command is not deterministic, that is, the same command
105 * with the same arguments, with the same key space, may have different
106 * results. For instance SPOP and RANDOMKEY are two random commands.
107 * S: Sort command output array if called from script, so that the output
110 struct redisCommand redisCommandTable
[] = {
111 {"get",getCommand
,2,"r",0,NULL
,1,1,1,0,0},
112 {"set",setCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
113 {"setnx",setnxCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
114 {"setex",setexCommand
,4,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
115 {"psetex",psetexCommand
,4,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
116 {"append",appendCommand
,3,"wm",0,NULL
,1,1,1,0,0},
117 {"strlen",strlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
118 {"del",delCommand
,-2,"w",0,noPreloadGetKeys
,1,-1,1,0,0},
119 {"exists",existsCommand
,2,"r",0,NULL
,1,1,1,0,0},
120 {"setbit",setbitCommand
,4,"wm",0,NULL
,1,1,1,0,0},
121 {"getbit",getbitCommand
,3,"r",0,NULL
,1,1,1,0,0},
122 {"setrange",setrangeCommand
,4,"wm",0,NULL
,1,1,1,0,0},
123 {"getrange",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
124 {"substr",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
125 {"incr",incrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
126 {"decr",decrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
127 {"mget",mgetCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
128 {"rpush",rpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
129 {"lpush",lpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
130 {"rpushx",rpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
131 {"lpushx",lpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
132 {"linsert",linsertCommand
,5,"wm",0,NULL
,1,1,1,0,0},
133 {"rpop",rpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
134 {"lpop",lpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
135 {"brpop",brpopCommand
,-3,"ws",0,NULL
,1,1,1,0,0},
136 {"brpoplpush",brpoplpushCommand
,4,"wms",0,NULL
,1,2,1,0,0},
137 {"blpop",blpopCommand
,-3,"ws",0,NULL
,1,-2,1,0,0},
138 {"llen",llenCommand
,2,"r",0,NULL
,1,1,1,0,0},
139 {"lindex",lindexCommand
,3,"r",0,NULL
,1,1,1,0,0},
140 {"lset",lsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
141 {"lrange",lrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
142 {"ltrim",ltrimCommand
,4,"w",0,NULL
,1,1,1,0,0},
143 {"lrem",lremCommand
,4,"w",0,NULL
,1,1,1,0,0},
144 {"rpoplpush",rpoplpushCommand
,3,"wm",0,NULL
,1,2,1,0,0},
145 {"sadd",saddCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
146 {"srem",sremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
147 {"smove",smoveCommand
,4,"w",0,NULL
,1,2,1,0,0},
148 {"sismember",sismemberCommand
,3,"r",0,NULL
,1,1,1,0,0},
149 {"scard",scardCommand
,2,"r",0,NULL
,1,1,1,0,0},
150 {"spop",spopCommand
,2,"wRs",0,NULL
,1,1,1,0,0},
151 {"srandmember",srandmemberCommand
,2,"rR",0,NULL
,1,1,1,0,0},
152 {"sinter",sinterCommand
,-2,"rS",0,NULL
,1,-1,1,0,0},
153 {"sinterstore",sinterstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0},
154 {"sunion",sunionCommand
,-2,"rS",0,NULL
,1,-1,1,0,0},
155 {"sunionstore",sunionstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0},
156 {"sdiff",sdiffCommand
,-2,"rS",0,NULL
,1,-1,1,0,0},
157 {"sdiffstore",sdiffstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0},
158 {"smembers",sinterCommand
,2,"rS",0,NULL
,1,1,1,0,0},
159 {"zadd",zaddCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
160 {"zincrby",zincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
161 {"zrem",zremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
162 {"zremrangebyscore",zremrangebyscoreCommand
,4,"w",0,NULL
,1,1,1,0,0},
163 {"zremrangebyrank",zremrangebyrankCommand
,4,"w",0,NULL
,1,1,1,0,0},
164 {"zunionstore",zunionstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
165 {"zinterstore",zinterstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
166 {"zrange",zrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
167 {"zrangebyscore",zrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
168 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
169 {"zcount",zcountCommand
,4,"r",0,NULL
,1,1,1,0,0},
170 {"zrevrange",zrevrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
171 {"zcard",zcardCommand
,2,"r",0,NULL
,1,1,1,0,0},
172 {"zscore",zscoreCommand
,3,"r",0,NULL
,1,1,1,0,0},
173 {"zrank",zrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
174 {"zrevrank",zrevrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
175 {"hset",hsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
176 {"hsetnx",hsetnxCommand
,4,"wm",0,NULL
,1,1,1,0,0},
177 {"hget",hgetCommand
,3,"r",0,NULL
,1,1,1,0,0},
178 {"hmset",hmsetCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
179 {"hmget",hmgetCommand
,-3,"r",0,NULL
,1,1,1,0,0},
180 {"hincrby",hincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
181 {"hincrbyfloat",hincrbyfloatCommand
,4,"wm",0,NULL
,1,1,1,0,0},
182 {"hdel",hdelCommand
,-3,"w",0,NULL
,1,1,1,0,0},
183 {"hlen",hlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
184 {"hkeys",hkeysCommand
,2,"rS",0,NULL
,1,1,1,0,0},
185 {"hvals",hvalsCommand
,2,"rS",0,NULL
,1,1,1,0,0},
186 {"hgetall",hgetallCommand
,2,"r",0,NULL
,1,1,1,0,0},
187 {"hexists",hexistsCommand
,3,"r",0,NULL
,1,1,1,0,0},
188 {"incrby",incrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
189 {"decrby",decrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
190 {"incrbyfloat",incrbyfloatCommand
,3,"wm",0,NULL
,1,1,1,0,0},
191 {"getset",getsetCommand
,3,"wm",0,NULL
,1,1,1,0,0},
192 {"mset",msetCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
193 {"msetnx",msetnxCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
194 {"randomkey",randomkeyCommand
,1,"rR",0,NULL
,0,0,0,0,0},
195 {"select",selectCommand
,2,"r",0,NULL
,0,0,0,0,0},
196 {"move",moveCommand
,3,"w",0,NULL
,1,1,1,0,0},
197 {"rename",renameCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
198 {"renamenx",renamenxCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
199 {"expire",expireCommand
,3,"w",0,NULL
,1,1,1,0,0},
200 {"expireat",expireatCommand
,3,"w",0,NULL
,1,1,1,0,0},
201 {"pexpire",pexpireCommand
,3,"w",0,NULL
,1,1,1,0,0},
202 {"pexpireat",pexpireatCommand
,3,"w",0,NULL
,1,1,1,0,0},
203 {"keys",keysCommand
,2,"rS",0,NULL
,0,0,0,0,0},
204 {"dbsize",dbsizeCommand
,1,"r",0,NULL
,0,0,0,0,0},
205 {"auth",authCommand
,2,"rs",0,NULL
,0,0,0,0,0},
206 {"ping",pingCommand
,1,"r",0,NULL
,0,0,0,0,0},
207 {"echo",echoCommand
,2,"r",0,NULL
,0,0,0,0,0},
208 {"save",saveCommand
,1,"ars",0,NULL
,0,0,0,0,0},
209 {"bgsave",bgsaveCommand
,1,"ar",0,NULL
,0,0,0,0,0},
210 {"bgrewriteaof",bgrewriteaofCommand
,1,"ar",0,NULL
,0,0,0,0,0},
211 {"shutdown",shutdownCommand
,-1,"ar",0,NULL
,0,0,0,0,0},
212 {"lastsave",lastsaveCommand
,1,"r",0,NULL
,0,0,0,0,0},
213 {"type",typeCommand
,2,"r",0,NULL
,1,1,1,0,0},
214 {"multi",multiCommand
,1,"rs",0,NULL
,0,0,0,0,0},
215 {"exec",execCommand
,1,"s",0,NULL
,0,0,0,0,0},
216 {"discard",discardCommand
,1,"rs",0,NULL
,0,0,0,0,0},
217 {"sync",syncCommand
,1,"ars",0,NULL
,0,0,0,0,0},
218 {"flushdb",flushdbCommand
,1,"w",0,NULL
,0,0,0,0,0},
219 {"flushall",flushallCommand
,1,"w",0,NULL
,0,0,0,0,0},
220 {"sort",sortCommand
,-2,"wmS",0,NULL
,1,1,1,0,0},
221 {"info",infoCommand
,-1,"r",0,NULL
,0,0,0,0,0},
222 {"monitor",monitorCommand
,1,"ars",0,NULL
,0,0,0,0,0},
223 {"ttl",ttlCommand
,2,"r",0,NULL
,1,1,1,0,0},
224 {"pttl",pttlCommand
,2,"r",0,NULL
,1,1,1,0,0},
225 {"persist",persistCommand
,2,"w",0,NULL
,1,1,1,0,0},
226 {"slaveof",slaveofCommand
,3,"as",0,NULL
,0,0,0,0,0},
227 {"debug",debugCommand
,-2,"as",0,NULL
,0,0,0,0,0},
228 {"config",configCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
229 {"subscribe",subscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
230 {"unsubscribe",unsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
231 {"psubscribe",psubscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
232 {"punsubscribe",punsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
233 {"publish",publishCommand
,3,"pf",0,NULL
,0,0,0,0,0},
234 {"watch",watchCommand
,-2,"rs",0,noPreloadGetKeys
,1,-1,1,0,0},
235 {"unwatch",unwatchCommand
,1,"rs",0,NULL
,0,0,0,0,0},
236 {"restore",restoreCommand
,4,"awm",0,NULL
,1,1,1,0,0},
237 {"migrate",migrateCommand
,6,"aw",0,NULL
,0,0,0,0,0},
238 {"dump",dumpCommand
,2,"ar",0,NULL
,1,1,1,0,0},
239 {"object",objectCommand
,-2,"r",0,NULL
,2,2,2,0,0},
240 {"client",clientCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
241 {"eval",evalCommand
,-3,"s",0,zunionInterGetKeys
,0,0,0,0,0},
242 {"evalsha",evalShaCommand
,-3,"s",0,zunionInterGetKeys
,0,0,0,0,0},
243 {"slowlog",slowlogCommand
,-2,"r",0,NULL
,0,0,0,0,0},
244 {"script",scriptCommand
,-2,"ras",0,NULL
,0,0,0,0,0},
245 {"time",timeCommand
,1,"rR",0,NULL
,0,0,0,0,0}
248 /*============================ Utility functions ============================ */
250 /* Low level logging. To use only for very big messages, otherwise
251 * redisLog() is to prefer. */
252 void redisLogRaw(int level
, const char *msg
) {
253 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
254 const char *c
= ".-*#";
257 int rawmode
= (level
& REDIS_LOG_RAW
);
259 level
&= 0xff; /* clear flags */
260 if (level
< server
.verbosity
) return;
262 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
266 fprintf(fp
,"%s",msg
);
271 gettimeofday(&tv
,NULL
);
272 off
= strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S.",localtime(&tv
.tv_sec
));
273 snprintf(buf
+off
,sizeof(buf
)-off
,"%03d",(int)tv
.tv_usec
/1000);
274 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
278 if (server
.logfile
) fclose(fp
);
280 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
283 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
284 * is used across the code. The raw version is only used in order to dump
285 * the INFO output on crash. */
286 void redisLog(int level
, const char *fmt
, ...) {
288 char msg
[REDIS_MAX_LOGMSG_LEN
];
290 if ((level
&0xff) < server
.verbosity
) return;
293 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
296 redisLogRaw(level
,msg
);
299 /* Log a fixed message without printf-alike capabilities, in a way that is
300 * safe to call from a signal handler.
302 * We actually use this only for signals that are not fatal from the point
303 * of view of Redis. Signals that are going to kill the server anyway and
304 * where we need printf-alike features are served by redisLog(). */
305 void redisLogFromHandler(int level
, const char *msg
) {
309 if ((level
&0xff) < server
.verbosity
||
310 (server
.logfile
== NULL
&& server
.daemonize
)) return;
311 fd
= server
.logfile
?
312 open(server
.logfile
, O_APPEND
|O_CREAT
|O_WRONLY
, 0644) :
314 if (fd
== -1) return;
315 ll2string(buf
,sizeof(buf
),getpid());
317 write(fd
,buf
,strlen(buf
));
318 write(fd
," | signal handler] (",20);
319 ll2string(buf
,sizeof(buf
),time(NULL
));
320 write(fd
,buf
,strlen(buf
));
322 write(fd
,msg
,strlen(msg
));
324 if (server
.logfile
) close(fd
);
327 /* Redis generally does not try to recover from out of memory conditions
328 * when allocating objects or strings, it is not clear if it will be possible
329 * to report this condition to the client since the networking layer itself
330 * is based on heap allocation for send buffers, so we simply abort.
331 * At least the code will be simpler to read... */
332 void oom(const char *msg
) {
333 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
338 /* Return the UNIX time in microseconds */
339 long long ustime(void) {
343 gettimeofday(&tv
, NULL
);
344 ust
= ((long long)tv
.tv_sec
)*1000000;
349 /* Return the UNIX time in milliseconds */
350 long long mstime(void) {
351 return ustime()/1000;
354 /*====================== Hash table type implementation ==================== */
356 /* This is an hash table type that uses the SDS dynamic strings libary as
357 * keys and radis objects as values (objects can hold SDS strings,
360 void dictVanillaFree(void *privdata
, void *val
)
362 DICT_NOTUSED(privdata
);
366 void dictListDestructor(void *privdata
, void *val
)
368 DICT_NOTUSED(privdata
);
369 listRelease((list
*)val
);
372 int dictSdsKeyCompare(void *privdata
, const void *key1
,
376 DICT_NOTUSED(privdata
);
378 l1
= sdslen((sds
)key1
);
379 l2
= sdslen((sds
)key2
);
380 if (l1
!= l2
) return 0;
381 return memcmp(key1
, key2
, l1
) == 0;
384 /* A case insensitive version used for the command lookup table. */
385 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
388 DICT_NOTUSED(privdata
);
390 return strcasecmp(key1
, key2
) == 0;
393 void dictRedisObjectDestructor(void *privdata
, void *val
)
395 DICT_NOTUSED(privdata
);
397 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
401 void dictSdsDestructor(void *privdata
, void *val
)
403 DICT_NOTUSED(privdata
);
408 int dictObjKeyCompare(void *privdata
, const void *key1
,
411 const robj
*o1
= key1
, *o2
= key2
;
412 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
415 unsigned int dictObjHash(const void *key
) {
417 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
420 unsigned int dictSdsHash(const void *key
) {
421 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
424 unsigned int dictSdsCaseHash(const void *key
) {
425 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
428 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
431 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
434 if (o1
->encoding
== REDIS_ENCODING_INT
&&
435 o2
->encoding
== REDIS_ENCODING_INT
)
436 return o1
->ptr
== o2
->ptr
;
438 o1
= getDecodedObject(o1
);
439 o2
= getDecodedObject(o2
);
440 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
446 unsigned int dictEncObjHash(const void *key
) {
447 robj
*o
= (robj
*) key
;
449 if (o
->encoding
== REDIS_ENCODING_RAW
) {
450 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
452 if (o
->encoding
== REDIS_ENCODING_INT
) {
456 len
= ll2string(buf
,32,(long)o
->ptr
);
457 return dictGenHashFunction((unsigned char*)buf
, len
);
461 o
= getDecodedObject(o
);
462 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
469 /* Sets type hash table */
470 dictType setDictType
= {
471 dictEncObjHash
, /* hash function */
474 dictEncObjKeyCompare
, /* key compare */
475 dictRedisObjectDestructor
, /* key destructor */
476 NULL
/* val destructor */
479 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
480 dictType zsetDictType
= {
481 dictEncObjHash
, /* hash function */
484 dictEncObjKeyCompare
, /* key compare */
485 dictRedisObjectDestructor
, /* key destructor */
486 NULL
/* val destructor */
489 /* Db->dict, keys are sds strings, vals are Redis objects. */
490 dictType dbDictType
= {
491 dictSdsHash
, /* hash function */
494 dictSdsKeyCompare
, /* key compare */
495 dictSdsDestructor
, /* key destructor */
496 dictRedisObjectDestructor
/* val destructor */
500 dictType keyptrDictType
= {
501 dictSdsHash
, /* hash function */
504 dictSdsKeyCompare
, /* key compare */
505 NULL
, /* key destructor */
506 NULL
/* val destructor */
509 /* Command table. sds string -> command struct pointer. */
510 dictType commandTableDictType
= {
511 dictSdsCaseHash
, /* hash function */
514 dictSdsKeyCaseCompare
, /* key compare */
515 dictSdsDestructor
, /* key destructor */
516 NULL
/* val destructor */
519 /* Hash type hash table (note that small hashes are represented with zimpaps) */
520 dictType hashDictType
= {
521 dictEncObjHash
, /* hash function */
524 dictEncObjKeyCompare
, /* key compare */
525 dictRedisObjectDestructor
, /* key destructor */
526 dictRedisObjectDestructor
/* val destructor */
529 /* Keylist hash table type has unencoded redis objects as keys and
530 * lists as values. It's used for blocking operations (BLPOP) and to
531 * map swapped keys to a list of clients waiting for this keys to be loaded. */
532 dictType keylistDictType
= {
533 dictObjHash
, /* hash function */
536 dictObjKeyCompare
, /* key compare */
537 dictRedisObjectDestructor
, /* key destructor */
538 dictListDestructor
/* val destructor */
541 int htNeedsResize(dict
*dict
) {
542 long long size
, used
;
544 size
= dictSlots(dict
);
545 used
= dictSize(dict
);
546 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
547 (used
*100/size
< REDIS_HT_MINFILL
));
550 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
551 * we resize the hash table to save memory */
552 void tryResizeHashTables(void) {
555 for (j
= 0; j
< server
.dbnum
; j
++) {
556 if (htNeedsResize(server
.db
[j
].dict
))
557 dictResize(server
.db
[j
].dict
);
558 if (htNeedsResize(server
.db
[j
].expires
))
559 dictResize(server
.db
[j
].expires
);
563 /* Our hash table implementation performs rehashing incrementally while
564 * we write/read from the hash table. Still if the server is idle, the hash
565 * table will use two tables for a long time. So we try to use 1 millisecond
566 * of CPU time at every serverCron() loop in order to rehash some key. */
567 void incrementallyRehash(void) {
570 for (j
= 0; j
< server
.dbnum
; j
++) {
571 if (dictIsRehashing(server
.db
[j
].dict
)) {
572 dictRehashMilliseconds(server
.db
[j
].dict
,1);
573 break; /* already used our millisecond for this loop... */
578 /* This function is called once a background process of some kind terminates,
579 * as we want to avoid resizing the hash tables when there is a child in order
580 * to play well with copy-on-write (otherwise when a resize happens lots of
581 * memory pages are copied). The goal of this function is to update the ability
582 * for dict.c to resize the hash tables accordingly to the fact we have o not
584 void updateDictResizePolicy(void) {
585 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1)
591 /* ======================= Cron: called every 100 ms ======================== */
593 /* Try to expire a few timed out keys. The algorithm used is adaptive and
594 * will use few CPU cycles if there are few expiring keys, otherwise
595 * it will get more aggressive to avoid that too much memory is used by
596 * keys that can be removed from the keyspace. */
597 void activeExpireCycle(void) {
600 for (j
= 0; j
< server
.dbnum
; j
++) {
602 redisDb
*db
= server
.db
+j
;
604 /* Continue to expire if at the end of the cycle more than 25%
605 * of the keys were expired. */
607 long num
= dictSize(db
->expires
);
608 long long now
= mstime();
611 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
612 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
617 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
618 t
= dictGetSignedIntegerVal(de
);
620 sds key
= dictGetKey(de
);
621 robj
*keyobj
= createStringObject(key
,sdslen(key
));
623 propagateExpire(db
,keyobj
);
625 decrRefCount(keyobj
);
627 server
.stat_expiredkeys
++;
630 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
634 void updateLRUClock(void) {
635 server
.lruclock
= (server
.unixtime
/REDIS_LRU_CLOCK_RESOLUTION
) &
640 /* Add a sample to the operations per second array of samples. */
641 void trackOperationsPerSecond(void) {
642 long long t
= mstime() - server
.ops_sec_last_sample_time
;
643 long long ops
= server
.stat_numcommands
- server
.ops_sec_last_sample_ops
;
646 ops_sec
= t
> 0 ? (ops
*1000/t
) : 0;
648 server
.ops_sec_samples
[server
.ops_sec_idx
] = ops_sec
;
649 server
.ops_sec_idx
= (server
.ops_sec_idx
+1) % REDIS_OPS_SEC_SAMPLES
;
650 server
.ops_sec_last_sample_time
= mstime();
651 server
.ops_sec_last_sample_ops
= server
.stat_numcommands
;
654 /* Return the mean of all the samples. */
655 long long getOperationsPerSecond(void) {
659 for (j
= 0; j
< REDIS_OPS_SEC_SAMPLES
; j
++)
660 sum
+= server
.ops_sec_samples
[j
];
661 return sum
/ REDIS_OPS_SEC_SAMPLES
;
664 /* Check for timeouts. Returns non-zero if the client was terminated */
665 int clientsCronHandleTimeout(redisClient
*c
) {
666 time_t now
= server
.unixtime
;
668 if (server
.maxidletime
&&
669 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
670 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
671 !(c
->flags
& REDIS_BLOCKED
) && /* no timeout for BLPOP */
672 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
673 listLength(c
->pubsub_patterns
) == 0 &&
674 (now
- c
->lastinteraction
> server
.maxidletime
))
676 redisLog(REDIS_VERBOSE
,"Closing idle client");
679 } else if (c
->flags
& REDIS_BLOCKED
) {
680 if (c
->bpop
.timeout
!= 0 && c
->bpop
.timeout
< now
) {
681 addReply(c
,shared
.nullmultibulk
);
682 unblockClientWaitingData(c
);
688 /* The client query buffer is an sds.c string that can end with a lot of
689 * free space not used, this function reclaims space if needed.
691 * The funciton always returns 0 as it never terminates the client. */
692 int clientsCronResizeQueryBuffer(redisClient
*c
) {
693 size_t querybuf_size
= sdsAllocSize(c
->querybuf
);
694 time_t idletime
= server
.unixtime
- c
->lastinteraction
;
696 /* There are two conditions to resize the query buffer:
697 * 1) Query buffer is > BIG_ARG and too big for latest peak.
698 * 2) Client is inactive and the buffer is bigger than 1k. */
699 if (((querybuf_size
> REDIS_MBULK_BIG_ARG
) &&
700 (querybuf_size
/(c
->querybuf_peak
+1)) > 2) ||
701 (querybuf_size
> 1024 && idletime
> 2))
703 /* Only resize the query buffer if it is actually wasting space. */
704 if (sdsavail(c
->querybuf
) > 1024) {
705 c
->querybuf
= sdsRemoveFreeSpace(c
->querybuf
);
708 /* Reset the peak again to capture the peak memory usage in the next
710 c
->querybuf_peak
= 0;
714 void clientsCron(void) {
715 /* Make sure to process at least 1/100 of clients per call.
716 * Since this function is called 10 times per second we are sure that
717 * in the worst case we process all the clients in 10 seconds.
718 * In normal conditions (a reasonable number of clients) we process
719 * all the clients in a shorter time. */
720 int numclients
= listLength(server
.clients
);
721 int iterations
= numclients
/100;
724 iterations
= (numclients
< 50) ? numclients
: 50;
725 while(listLength(server
.clients
) && iterations
--) {
729 /* Rotate the list, take the current head, process.
730 * This way if the client must be removed from the list it's the
731 * first element and we don't incur into O(N) computation. */
732 listRotate(server
.clients
);
733 head
= listFirst(server
.clients
);
734 c
= listNodeValue(head
);
735 /* The following functions do different service checks on the client.
736 * The protocol is that they return non-zero if the client was
738 if (clientsCronHandleTimeout(c
)) continue;
739 if (clientsCronResizeQueryBuffer(c
)) continue;
743 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
744 int j
, loops
= server
.cronloops
;
745 REDIS_NOTUSED(eventLoop
);
747 REDIS_NOTUSED(clientData
);
749 /* Software watchdog: deliver the SIGALRM that will reach the signal
750 * handler if we don't return here fast enough. */
751 if (server
.watchdog_period
) watchdogScheduleSignal(server
.watchdog_period
);
753 /* We take a cached value of the unix time in the global state because
754 * with virtual memory and aging there is to store the current time
755 * in objects at every object access, and accuracy is not needed.
756 * To access a global var is faster than calling time(NULL) */
757 server
.unixtime
= time(NULL
);
759 trackOperationsPerSecond();
761 /* We have just 22 bits per object for LRU information.
762 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
763 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
765 * Note that even if this will wrap after 1.5 years it's not a problem,
766 * everything will still work but just some object will appear younger
767 * to Redis. But for this to happen a given object should never be touched
770 * Note that you can change the resolution altering the
771 * REDIS_LRU_CLOCK_RESOLUTION define.
775 /* Record the max memory used since the server was started. */
776 if (zmalloc_used_memory() > server
.stat_peak_memory
)
777 server
.stat_peak_memory
= zmalloc_used_memory();
779 /* We received a SIGTERM, shutting down here in a safe way, as it is
780 * not ok doing so inside the signal handler. */
781 if (server
.shutdown_asap
) {
782 if (prepareForShutdown(0) == REDIS_OK
) exit(0);
783 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
786 /* Show some info about non-empty databases */
787 for (j
= 0; j
< server
.dbnum
; j
++) {
788 long long size
, used
, vkeys
;
790 size
= dictSlots(server
.db
[j
].dict
);
791 used
= dictSize(server
.db
[j
].dict
);
792 vkeys
= dictSize(server
.db
[j
].expires
);
793 if (!(loops
% 50) && (used
|| vkeys
)) {
794 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
795 /* dictPrintStats(server.dict); */
799 /* We don't want to resize the hash tables while a bacground saving
800 * is in progress: the saving child is created using fork() that is
801 * implemented with a copy-on-write semantic in most modern systems, so
802 * if we resize the HT while there is the saving child at work actually
803 * a lot of memory movements in the parent will cause a lot of pages
805 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1) {
806 if (!(loops
% 10)) tryResizeHashTables();
807 if (server
.activerehashing
) incrementallyRehash();
810 /* Show information about connected clients */
812 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
813 listLength(server
.clients
)-listLength(server
.slaves
),
814 listLength(server
.slaves
),
815 zmalloc_used_memory());
818 /* We need to do a few operations on clients asynchronously. */
821 /* Start a scheduled AOF rewrite if this was requested by the user while
822 * a BGSAVE was in progress. */
823 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1 &&
824 server
.aof_rewrite_scheduled
)
826 rewriteAppendOnlyFileBackground();
829 /* Check if a background saving or AOF rewrite in progress terminated. */
830 if (server
.rdb_child_pid
!= -1 || server
.aof_child_pid
!= -1) {
834 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
835 int exitcode
= WEXITSTATUS(statloc
);
838 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
840 if (pid
== server
.rdb_child_pid
) {
841 backgroundSaveDoneHandler(exitcode
,bysignal
);
843 backgroundRewriteDoneHandler(exitcode
,bysignal
);
845 updateDictResizePolicy();
848 /* If there is not a background saving/rewrite in progress check if
849 * we have to save/rewrite now */
850 for (j
= 0; j
< server
.saveparamslen
; j
++) {
851 struct saveparam
*sp
= server
.saveparams
+j
;
853 if (server
.dirty
>= sp
->changes
&&
854 server
.unixtime
-server
.lastsave
> sp
->seconds
) {
855 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
856 sp
->changes
, sp
->seconds
);
857 rdbSaveBackground(server
.rdb_filename
);
862 /* Trigger an AOF rewrite if needed */
863 if (server
.rdb_child_pid
== -1 &&
864 server
.aof_child_pid
== -1 &&
865 server
.aof_rewrite_perc
&&
866 server
.aof_current_size
> server
.aof_rewrite_min_size
)
868 long long base
= server
.aof_rewrite_base_size
?
869 server
.aof_rewrite_base_size
: 1;
870 long long growth
= (server
.aof_current_size
*100/base
) - 100;
871 if (growth
>= server
.aof_rewrite_perc
) {
872 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
873 rewriteAppendOnlyFileBackground();
879 /* If we postponed an AOF buffer flush, let's try to do it every time the
880 * cron function is called. */
881 if (server
.aof_flush_postponed_start
) flushAppendOnlyFile(0);
883 /* Expire a few keys per cycle, only if this is a master.
884 * On slaves we wait for DEL operations synthesized by the master
885 * in order to guarantee a strict consistency. */
886 if (server
.masterhost
== NULL
) activeExpireCycle();
888 /* Close clients that need to be closed asynchronous */
889 freeClientsInAsyncFreeQueue();
891 /* Replication cron function -- used to reconnect to master and
892 * to detect transfer failures. */
893 if (!(loops
% 10)) replicationCron();
899 /* This function gets called every time Redis is entering the
900 * main loop of the event driven library, that is, before to sleep
901 * for ready file descriptors. */
902 void beforeSleep(struct aeEventLoop
*eventLoop
) {
903 REDIS_NOTUSED(eventLoop
);
907 /* Try to process pending commands for clients that were just unblocked. */
908 while (listLength(server
.unblocked_clients
)) {
909 ln
= listFirst(server
.unblocked_clients
);
910 redisAssert(ln
!= NULL
);
912 listDelNode(server
.unblocked_clients
,ln
);
913 c
->flags
&= ~REDIS_UNBLOCKED
;
915 /* Process remaining data in the input buffer. */
916 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) {
917 server
.current_client
= c
;
918 processInputBuffer(c
);
919 server
.current_client
= NULL
;
923 /* Write the AOF buffer on disk */
924 flushAppendOnlyFile(0);
927 /* =========================== Server initialization ======================== */
929 void createSharedObjects(void) {
932 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
933 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
934 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
935 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
936 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
937 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
938 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
939 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
940 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
941 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
942 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
943 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
944 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
945 "-ERR Operation against a key holding the wrong kind of value\r\n"));
946 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
947 "-ERR no such key\r\n"));
948 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
949 "-ERR syntax error\r\n"));
950 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
951 "-ERR source and destination objects are the same\r\n"));
952 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
953 "-ERR index out of range\r\n"));
954 shared
.noscripterr
= createObject(REDIS_STRING
,sdsnew(
955 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
956 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
957 "-LOADING Redis is loading the dataset in memory\r\n"));
958 shared
.slowscripterr
= createObject(REDIS_STRING
,sdsnew(
959 "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n"));
960 shared
.bgsaveerr
= createObject(REDIS_STRING
,sdsnew(
961 "-MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.\r\n"));
962 shared
.roslaveerr
= createObject(REDIS_STRING
,sdsnew(
963 "-READONLY You can't write against a read only slave.\r\n"));
964 shared
.oomerr
= createObject(REDIS_STRING
,sdsnew(
965 "-OOM command not allowed when used memory > 'maxmemory'.\r\n"));
966 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
967 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
968 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
970 for (j
= 0; j
< REDIS_SHARED_SELECT_CMDS
; j
++) {
971 shared
.select
[j
] = createObject(REDIS_STRING
,
972 sdscatprintf(sdsempty(),"select %d\r\n", j
));
974 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
975 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
976 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
977 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
978 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
979 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
980 shared
.del
= createStringObject("DEL",3);
981 shared
.rpop
= createStringObject("RPOP",4);
982 shared
.lpop
= createStringObject("LPOP",4);
983 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
984 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
985 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
987 for (j
= 0; j
< REDIS_SHARED_BULKHDR_LEN
; j
++) {
988 shared
.mbulkhdr
[j
] = createObject(REDIS_STRING
,
989 sdscatprintf(sdsempty(),"*%d\r\n",j
));
990 shared
.bulkhdr
[j
] = createObject(REDIS_STRING
,
991 sdscatprintf(sdsempty(),"$%d\r\n",j
));
995 void initServerConfig() {
996 getRandomHexChars(server
.runid
,REDIS_RUN_ID_SIZE
);
997 server
.runid
[REDIS_RUN_ID_SIZE
] = '\0';
998 server
.arch_bits
= (sizeof(long) == 8) ? 64 : 32;
999 server
.port
= REDIS_SERVERPORT
;
1000 server
.bindaddr
= NULL
;
1001 server
.unixsocket
= NULL
;
1002 server
.unixsocketperm
= 0;
1005 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1006 server
.verbosity
= REDIS_NOTICE
;
1007 server
.maxidletime
= REDIS_MAXIDLETIME
;
1008 server
.client_max_querybuf_len
= REDIS_MAX_QUERYBUF_LEN
;
1009 server
.saveparams
= NULL
;
1011 server
.logfile
= NULL
; /* NULL = log on standard output */
1012 server
.syslog_enabled
= 0;
1013 server
.syslog_ident
= zstrdup("redis");
1014 server
.syslog_facility
= LOG_LOCAL0
;
1015 server
.daemonize
= 0;
1016 server
.aof_state
= REDIS_AOF_OFF
;
1017 server
.aof_fsync
= AOF_FSYNC_EVERYSEC
;
1018 server
.aof_no_fsync_on_rewrite
= 0;
1019 server
.aof_rewrite_perc
= REDIS_AOF_REWRITE_PERC
;
1020 server
.aof_rewrite_min_size
= REDIS_AOF_REWRITE_MIN_SIZE
;
1021 server
.aof_rewrite_base_size
= 0;
1022 server
.aof_rewrite_scheduled
= 0;
1023 server
.aof_last_fsync
= time(NULL
);
1024 server
.aof_delayed_fsync
= 0;
1026 server
.aof_selected_db
= -1; /* Make sure the first time will not match */
1027 server
.aof_flush_postponed_start
= 0;
1028 server
.pidfile
= zstrdup("/var/run/redis.pid");
1029 server
.rdb_filename
= zstrdup("dump.rdb");
1030 server
.aof_filename
= zstrdup("appendonly.aof");
1031 server
.requirepass
= NULL
;
1032 server
.rdb_compression
= 1;
1033 server
.activerehashing
= 1;
1034 server
.maxclients
= REDIS_MAX_CLIENTS
;
1035 server
.bpop_blocked_clients
= 0;
1036 server
.maxmemory
= 0;
1037 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
1038 server
.maxmemory_samples
= 3;
1039 server
.hash_max_ziplist_entries
= REDIS_HASH_MAX_ZIPLIST_ENTRIES
;
1040 server
.hash_max_ziplist_value
= REDIS_HASH_MAX_ZIPLIST_VALUE
;
1041 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
1042 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
1043 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
1044 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
1045 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
1046 server
.shutdown_asap
= 0;
1047 server
.repl_ping_slave_period
= REDIS_REPL_PING_SLAVE_PERIOD
;
1048 server
.repl_timeout
= REDIS_REPL_TIMEOUT
;
1049 server
.lua_caller
= NULL
;
1050 server
.lua_time_limit
= REDIS_LUA_TIME_LIMIT
;
1051 server
.lua_client
= NULL
;
1052 server
.lua_timedout
= 0;
1055 resetServerSaveParams();
1057 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1058 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1059 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1060 /* Replication related */
1061 server
.masterauth
= NULL
;
1062 server
.masterhost
= NULL
;
1063 server
.masterport
= 6379;
1064 server
.master
= NULL
;
1065 server
.repl_state
= REDIS_REPL_NONE
;
1066 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
1067 server
.repl_serve_stale_data
= 1;
1068 server
.repl_slave_ro
= 1;
1069 server
.repl_down_since
= time(NULL
);
1071 /* Client output buffer limits */
1072 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_NORMAL
].hard_limit_bytes
= 0;
1073 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_NORMAL
].soft_limit_bytes
= 0;
1074 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_NORMAL
].soft_limit_seconds
= 0;
1075 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_SLAVE
].hard_limit_bytes
= 1024*1024*256;
1076 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_SLAVE
].soft_limit_bytes
= 1024*1024*64;
1077 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_SLAVE
].soft_limit_seconds
= 60;
1078 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_PUBSUB
].hard_limit_bytes
= 1024*1024*32;
1079 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_PUBSUB
].soft_limit_bytes
= 1024*1024*8;
1080 server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_PUBSUB
].soft_limit_seconds
= 60;
1082 /* Double constants initialization */
1084 R_PosInf
= 1.0/R_Zero
;
1085 R_NegInf
= -1.0/R_Zero
;
1086 R_Nan
= R_Zero
/R_Zero
;
1088 /* Command table -- we intiialize it here as it is part of the
1089 * initial configuration, since command names may be changed via
1090 * redis.conf using the rename-command directive. */
1091 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
1092 populateCommandTable();
1093 server
.delCommand
= lookupCommandByCString("del");
1094 server
.multiCommand
= lookupCommandByCString("multi");
1095 server
.lpushCommand
= lookupCommandByCString("lpush");
1098 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
1099 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
1102 server
.assert_failed
= "<no assertion failed>";
1103 server
.assert_file
= "<no file>";
1104 server
.assert_line
= 0;
1105 server
.bug_report_start
= 0;
1106 server
.watchdog_period
= 0;
1109 /* This function will try to raise the max number of open files accordingly to
1110 * the configured max number of clients. It will also account for 32 additional
1111 * file descriptors as we need a few more for persistence, listening
1112 * sockets, log files and so forth.
1114 * If it will not be possible to set the limit accordingly to the configured
1115 * max number of clients, the function will do the reverse setting
1116 * server.maxclients to the value that we can actually handle. */
1117 void adjustOpenFilesLimit(void) {
1118 rlim_t maxfiles
= server
.maxclients
+32;
1119 struct rlimit limit
;
1121 if (maxfiles
< 1024) maxfiles
= 1024;
1122 if (getrlimit(RLIMIT_NOFILE
,&limit
) == -1) {
1123 redisLog(REDIS_WARNING
,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.",
1125 server
.maxclients
= 1024-32;
1127 rlim_t oldlimit
= limit
.rlim_cur
;
1129 /* Set the max number of files if the current limit is not enough
1131 if (oldlimit
< maxfiles
) {
1135 while(f
> oldlimit
) {
1138 if (setrlimit(RLIMIT_NOFILE
,&limit
) != -1) break;
1141 if (f
< oldlimit
) f
= oldlimit
;
1142 if (f
!= maxfiles
) {
1143 server
.maxclients
= f
-32;
1144 redisLog(REDIS_WARNING
,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.",
1145 (int) maxfiles
, strerror(errno
), (int) server
.maxclients
);
1147 redisLog(REDIS_NOTICE
,"Max number of open files set to %d",
1157 signal(SIGHUP
, SIG_IGN
);
1158 signal(SIGPIPE
, SIG_IGN
);
1159 setupSignalHandlers();
1161 if (server
.syslog_enabled
) {
1162 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
1163 server
.syslog_facility
);
1166 server
.current_client
= NULL
;
1167 server
.clients
= listCreate();
1168 server
.clients_to_close
= listCreate();
1169 server
.slaves
= listCreate();
1170 server
.monitors
= listCreate();
1171 server
.unblocked_clients
= listCreate();
1173 createSharedObjects();
1174 adjustOpenFilesLimit();
1175 server
.el
= aeCreateEventLoop(server
.maxclients
+1024);
1176 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1178 if (server
.port
!= 0) {
1179 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
1180 if (server
.ipfd
== ANET_ERR
) {
1181 redisLog(REDIS_WARNING
, "Opening port %d: %s",
1182 server
.port
, server
.neterr
);
1186 if (server
.unixsocket
!= NULL
) {
1187 unlink(server
.unixsocket
); /* don't care if this fails */
1188 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
,server
.unixsocketperm
);
1189 if (server
.sofd
== ANET_ERR
) {
1190 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
1194 if (server
.ipfd
< 0 && server
.sofd
< 0) {
1195 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
1198 for (j
= 0; j
< server
.dbnum
; j
++) {
1199 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1200 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1201 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
1202 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
1203 server
.db
[j
].id
= j
;
1205 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
1206 server
.pubsub_patterns
= listCreate();
1207 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
1208 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
1209 server
.cronloops
= 0;
1210 server
.rdb_child_pid
= -1;
1211 server
.aof_child_pid
= -1;
1212 server
.aof_rewrite_buf
= sdsempty();
1213 server
.aof_buf
= sdsempty();
1214 server
.lastsave
= time(NULL
);
1216 server
.stat_numcommands
= 0;
1217 server
.stat_numconnections
= 0;
1218 server
.stat_expiredkeys
= 0;
1219 server
.stat_evictedkeys
= 0;
1220 server
.stat_starttime
= time(NULL
);
1221 server
.stat_keyspace_misses
= 0;
1222 server
.stat_keyspace_hits
= 0;
1223 server
.stat_peak_memory
= 0;
1224 server
.stat_fork_time
= 0;
1225 server
.stat_rejected_conn
= 0;
1226 memset(server
.ops_sec_samples
,0,sizeof(server
.ops_sec_samples
));
1227 server
.ops_sec_idx
= 0;
1228 server
.ops_sec_last_sample_time
= mstime();
1229 server
.ops_sec_last_sample_ops
= 0;
1230 server
.unixtime
= time(NULL
);
1231 server
.lastbgsave_status
= REDIS_OK
;
1232 server
.stop_writes_on_bgsave_err
= 1;
1233 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1234 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
1235 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
1236 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
1237 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
1239 if (server
.aof_state
== REDIS_AOF_ON
) {
1240 server
.aof_fd
= open(server
.aof_filename
,
1241 O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1242 if (server
.aof_fd
== -1) {
1243 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1249 /* 32 bit instances are limited to 4GB of address space, so if there is
1250 * no explicit limit in the user provided configuration we set a limit
1251 * at 3.5GB using maxmemory with 'noeviction' policy'. This saves
1252 * useless crashes of the Redis instance. */
1253 if (server
.arch_bits
== 32 && server
.maxmemory
== 0) {
1254 redisLog(REDIS_WARNING
,"Warning: 32 bit instance detected but no memory limit set. Setting 3.5 GB maxmemory limit with 'noeviction' policy now.");
1255 server
.maxmemory
= 3584LL*(1024*1024); /* 3584 MB = 3.5 GB */
1256 server
.maxmemory_policy
= REDIS_MAXMEMORY_NO_EVICTION
;
1264 /* Populates the Redis Command Table starting from the hard coded list
1265 * we have on top of redis.c file. */
1266 void populateCommandTable(void) {
1268 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1270 for (j
= 0; j
< numcommands
; j
++) {
1271 struct redisCommand
*c
= redisCommandTable
+j
;
1272 char *f
= c
->sflags
;
1277 case 'w': c
->flags
|= REDIS_CMD_WRITE
; break;
1278 case 'r': c
->flags
|= REDIS_CMD_READONLY
; break;
1279 case 'm': c
->flags
|= REDIS_CMD_DENYOOM
; break;
1280 case 'a': c
->flags
|= REDIS_CMD_ADMIN
; break;
1281 case 'p': c
->flags
|= REDIS_CMD_PUBSUB
; break;
1282 case 'f': c
->flags
|= REDIS_CMD_FORCE_REPLICATION
; break;
1283 case 's': c
->flags
|= REDIS_CMD_NOSCRIPT
; break;
1284 case 'R': c
->flags
|= REDIS_CMD_RANDOM
; break;
1285 case 'S': c
->flags
|= REDIS_CMD_SORT_FOR_SCRIPT
; break;
1286 default: redisPanic("Unsupported command flag"); break;
1291 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
1292 assert(retval
== DICT_OK
);
1296 void resetCommandTableStats(void) {
1297 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1300 for (j
= 0; j
< numcommands
; j
++) {
1301 struct redisCommand
*c
= redisCommandTable
+j
;
1303 c
->microseconds
= 0;
1308 /* ========================== Redis OP Array API ============================ */
1310 void redisOpArrayInit(redisOpArray
*oa
) {
1315 int redisOpArrayAppend(redisOpArray
*oa
, struct redisCommand
*cmd
, int dbid
,
1316 robj
**argv
, int argc
, int target
)
1320 oa
->ops
= zrealloc(oa
->ops
,sizeof(redisOp
)*(oa
->numops
+1));
1321 op
= oa
->ops
+oa
->numops
;
1326 op
->target
= target
;
1331 void redisOpArrayFree(redisOpArray
*oa
) {
1337 op
= oa
->ops
+oa
->numops
;
1338 for (j
= 0; j
< op
->argc
; j
++)
1339 decrRefCount(op
->argv
[j
]);
1345 /* ====================== Commands lookup and execution ===================== */
1347 struct redisCommand
*lookupCommand(sds name
) {
1348 return dictFetchValue(server
.commands
, name
);
1351 struct redisCommand
*lookupCommandByCString(char *s
) {
1352 struct redisCommand
*cmd
;
1353 sds name
= sdsnew(s
);
1355 cmd
= dictFetchValue(server
.commands
, name
);
1360 /* Propagate the specified command (in the context of the specified database id)
1361 * to AOF, Slaves and Monitors.
1363 * flags are an xor between:
1364 * + REDIS_PROPAGATE_NONE (no propagation of command at all)
1365 * + REDIS_PROPAGATE_AOF (propagate into the AOF file if is enabled)
1366 * + REDIS_PROPAGATE_REPL (propagate into the replication link)
1368 void propagate(struct redisCommand
*cmd
, int dbid
, robj
**argv
, int argc
,
1371 if (server
.aof_state
!= REDIS_AOF_OFF
&& flags
& REDIS_PROPAGATE_AOF
)
1372 feedAppendOnlyFile(cmd
,dbid
,argv
,argc
);
1373 if (flags
& REDIS_PROPAGATE_REPL
&& listLength(server
.slaves
))
1374 replicationFeedSlaves(server
.slaves
,dbid
,argv
,argc
);
1377 /* Used inside commands to schedule the propagation of additional commands
1378 * after the current command is propagated to AOF / Replication. */
1379 void alsoPropagate(struct redisCommand
*cmd
, int dbid
, robj
**argv
, int argc
,
1382 redisOpArrayAppend(&server
.also_propagate
,cmd
,dbid
,argv
,argc
,target
);
1385 /* Call() is the core of Redis execution of a command */
1386 void call(redisClient
*c
, int flags
) {
1387 long long dirty
, start
= ustime(), duration
;
1389 /* Sent the command to clients in MONITOR mode, only if the commands are
1390 * not geneated from reading an AOF. */
1391 if (listLength(server
.monitors
) && !server
.loading
)
1392 replicationFeedMonitors(c
,server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1394 /* Call the command. */
1395 redisOpArrayInit(&server
.also_propagate
);
1396 dirty
= server
.dirty
;
1398 dirty
= server
.dirty
-dirty
;
1399 duration
= ustime()-start
;
1401 /* When EVAL is called loading the AOF we don't want commands called
1402 * from Lua to go into the slowlog or to populate statistics. */
1403 if (server
.loading
&& c
->flags
& REDIS_LUA_CLIENT
)
1404 flags
&= ~(REDIS_CALL_SLOWLOG
| REDIS_CALL_STATS
);
1406 /* Log the command into the Slow log if needed, and populate the
1407 * per-command statistics that we show in INFO commandstats. */
1408 if (flags
& REDIS_CALL_SLOWLOG
)
1409 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1410 if (flags
& REDIS_CALL_STATS
) {
1411 c
->cmd
->microseconds
+= duration
;
1415 /* Propagate the command into the AOF and replication link */
1416 if (flags
& REDIS_CALL_PROPAGATE
) {
1417 int flags
= REDIS_PROPAGATE_NONE
;
1419 if (c
->cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
)
1420 flags
|= REDIS_PROPAGATE_REPL
;
1422 flags
|= (REDIS_PROPAGATE_REPL
| REDIS_PROPAGATE_AOF
);
1423 if (flags
!= REDIS_PROPAGATE_NONE
)
1424 propagate(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
,flags
);
1426 /* Commands such as LPUSH or BRPOPLPUSH may propagate an additional
1428 if (server
.also_propagate
.numops
) {
1432 for (j
= 0; j
< server
.also_propagate
.numops
; j
++) {
1433 rop
= &server
.also_propagate
.ops
[j
];
1434 propagate(rop
->cmd
, rop
->dbid
, rop
->argv
, rop
->argc
, rop
->target
);
1436 redisOpArrayFree(&server
.also_propagate
);
1438 server
.stat_numcommands
++;
1441 /* If this function gets called we already read a whole
1442 * command, argments are in the client argv/argc fields.
1443 * processCommand() execute the command or prepare the
1444 * server for a bulk read from the client.
1446 * If 1 is returned the client is still alive and valid and
1447 * and other operations can be performed by the caller. Otherwise
1448 * if 0 is returned the client was destroied (i.e. after QUIT). */
1449 int processCommand(redisClient
*c
) {
1450 /* The QUIT command is handled separately. Normal command procs will
1451 * go through checking for replication and QUIT will cause trouble
1452 * when FORCE_REPLICATION is enabled and would be implemented in
1453 * a regular command proc. */
1454 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1455 addReply(c
,shared
.ok
);
1456 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1460 /* Now lookup the command and check ASAP about trivial error conditions
1461 * such as wrong arity, bad command name and so forth. */
1462 c
->cmd
= c
->lastcmd
= lookupCommand(c
->argv
[0]->ptr
);
1464 addReplyErrorFormat(c
,"unknown command '%s'",
1465 (char*)c
->argv
[0]->ptr
);
1467 } else if ((c
->cmd
->arity
> 0 && c
->cmd
->arity
!= c
->argc
) ||
1468 (c
->argc
< -c
->cmd
->arity
)) {
1469 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1474 /* Check if the user is authenticated */
1475 if (server
.requirepass
&& !c
->authenticated
&& c
->cmd
->proc
!= authCommand
)
1477 addReplyError(c
,"operation not permitted");
1481 /* Handle the maxmemory directive.
1483 * First we try to free some memory if possible (if there are volatile
1484 * keys in the dataset). If there are not the only thing we can do
1485 * is returning an error. */
1486 if (server
.maxmemory
) {
1487 int retval
= freeMemoryIfNeeded();
1488 if ((c
->cmd
->flags
& REDIS_CMD_DENYOOM
) && retval
== REDIS_ERR
) {
1489 addReply(c
, shared
.oomerr
);
1494 /* Don't accept write commands if there are problems persisting on disk. */
1495 if (server
.stop_writes_on_bgsave_err
&&
1496 server
.saveparamslen
> 0
1497 && server
.lastbgsave_status
== REDIS_ERR
&&
1498 c
->cmd
->flags
& REDIS_CMD_WRITE
)
1500 addReply(c
, shared
.bgsaveerr
);
1504 /* Don't accept wirte commands if this is a read only slave. But
1505 * accept write commands if this is our master. */
1506 if (server
.masterhost
&& server
.repl_slave_ro
&&
1507 !(c
->flags
& REDIS_MASTER
) &&
1508 c
->cmd
->flags
& REDIS_CMD_WRITE
)
1510 addReply(c
, shared
.roslaveerr
);
1514 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1515 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1517 c
->cmd
->proc
!= subscribeCommand
&&
1518 c
->cmd
->proc
!= unsubscribeCommand
&&
1519 c
->cmd
->proc
!= psubscribeCommand
&&
1520 c
->cmd
->proc
!= punsubscribeCommand
) {
1521 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1525 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1526 * we are a slave with a broken link with master. */
1527 if (server
.masterhost
&& server
.repl_state
!= REDIS_REPL_CONNECTED
&&
1528 server
.repl_serve_stale_data
== 0 &&
1529 c
->cmd
->proc
!= infoCommand
&& c
->cmd
->proc
!= slaveofCommand
)
1532 "link with MASTER is down and slave-serve-stale-data is set to no");
1536 /* Loading DB? Return an error if the command is not INFO */
1537 if (server
.loading
&& c
->cmd
->proc
!= infoCommand
) {
1538 addReply(c
, shared
.loadingerr
);
1542 /* Lua script too slow? Only allow SHUTDOWN NOSAVE and SCRIPT KILL. */
1543 if (server
.lua_timedout
&&
1544 !(c
->cmd
->proc
!= shutdownCommand
&&
1546 tolower(((char*)c
->argv
[1]->ptr
)[0]) == 'n') &&
1547 !(c
->cmd
->proc
== scriptCommand
&&
1549 tolower(((char*)c
->argv
[1]->ptr
)[0]) == 'k'))
1551 addReply(c
, shared
.slowscripterr
);
1555 /* Exec the command */
1556 if (c
->flags
& REDIS_MULTI
&&
1557 c
->cmd
->proc
!= execCommand
&& c
->cmd
->proc
!= discardCommand
&&
1558 c
->cmd
->proc
!= multiCommand
&& c
->cmd
->proc
!= watchCommand
)
1560 queueMultiCommand(c
);
1561 addReply(c
,shared
.queued
);
1563 call(c
,REDIS_CALL_FULL
);
1568 /*================================== Shutdown =============================== */
1570 int prepareForShutdown(int flags
) {
1571 int save
= flags
& REDIS_SHUTDOWN_SAVE
;
1572 int nosave
= flags
& REDIS_SHUTDOWN_NOSAVE
;
1574 redisLog(REDIS_WARNING
,"User requested shutdown...");
1575 /* Kill the saving child if there is a background saving in progress.
1576 We want to avoid race conditions, for instance our saving child may
1577 overwrite the synchronous saving did by SHUTDOWN. */
1578 if (server
.rdb_child_pid
!= -1) {
1579 redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!");
1580 kill(server
.rdb_child_pid
,SIGKILL
);
1581 rdbRemoveTempFile(server
.rdb_child_pid
);
1583 if (server
.aof_state
!= REDIS_AOF_OFF
) {
1584 /* Kill the AOF saving child as the AOF we already have may be longer
1585 * but contains the full dataset anyway. */
1586 if (server
.aof_child_pid
!= -1) {
1587 redisLog(REDIS_WARNING
,
1588 "There is a child rewriting the AOF. Killing it!");
1589 kill(server
.aof_child_pid
,SIGKILL
);
1591 /* Append only file: fsync() the AOF and exit */
1592 redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file.");
1593 aof_fsync(server
.aof_fd
);
1595 if ((server
.saveparamslen
> 0 && !nosave
) || save
) {
1596 redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting.");
1597 /* Snapshotting. Perform a SYNC SAVE and exit */
1598 if (rdbSave(server
.rdb_filename
) != REDIS_OK
) {
1599 /* Ooops.. error saving! The best we can do is to continue
1600 * operating. Note that if there was a background saving process,
1601 * in the next cron() Redis will be notified that the background
1602 * saving aborted, handling special stuff like slaves pending for
1603 * synchronization... */
1604 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit.");
1608 if (server
.daemonize
) {
1609 redisLog(REDIS_NOTICE
,"Removing the pid file.");
1610 unlink(server
.pidfile
);
1612 /* Close the listening sockets. Apparently this allows faster restarts. */
1613 if (server
.ipfd
!= -1) close(server
.ipfd
);
1614 if (server
.sofd
!= -1) close(server
.sofd
);
1615 if (server
.unixsocket
) {
1616 redisLog(REDIS_NOTICE
,"Removing the unix socket file.");
1617 unlink(server
.unixsocket
); /* don't care if this fails */
1620 redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye...");
1624 /*================================== Commands =============================== */
1626 void authCommand(redisClient
*c
) {
1627 if (!server
.requirepass
) {
1628 addReplyError(c
,"Client sent AUTH, but no password is set");
1629 } else if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1630 c
->authenticated
= 1;
1631 addReply(c
,shared
.ok
);
1633 c
->authenticated
= 0;
1634 addReplyError(c
,"invalid password");
1638 void pingCommand(redisClient
*c
) {
1639 addReply(c
,shared
.pong
);
1642 void echoCommand(redisClient
*c
) {
1643 addReplyBulk(c
,c
->argv
[1]);
1646 void timeCommand(redisClient
*c
) {
1649 /* gettimeofday() can only fail if &tv is a bad addresss so we
1650 * don't check for errors. */
1651 gettimeofday(&tv
,NULL
);
1652 addReplyMultiBulkLen(c
,2);
1653 addReplyBulkLongLong(c
,tv
.tv_sec
);
1654 addReplyBulkLongLong(c
,tv
.tv_usec
);
1657 /* Convert an amount of bytes into a human readable string in the form
1658 * of 100B, 2G, 100M, 4K, and so forth. */
1659 void bytesToHuman(char *s
, unsigned long long n
) {
1664 sprintf(s
,"%lluB",n
);
1666 } else if (n
< (1024*1024)) {
1667 d
= (double)n
/(1024);
1668 sprintf(s
,"%.2fK",d
);
1669 } else if (n
< (1024LL*1024*1024)) {
1670 d
= (double)n
/(1024*1024);
1671 sprintf(s
,"%.2fM",d
);
1672 } else if (n
< (1024LL*1024*1024*1024)) {
1673 d
= (double)n
/(1024LL*1024*1024);
1674 sprintf(s
,"%.2fG",d
);
1678 /* Create the string returned by the INFO command. This is decoupled
1679 * by the INFO command itself as we need to report the same information
1680 * on memory corruption problems. */
1681 sds
genRedisInfoString(char *section
) {
1682 sds info
= sdsempty();
1683 time_t uptime
= server
.unixtime
-server
.stat_starttime
;
1685 struct rusage self_ru
, c_ru
;
1686 unsigned long lol
, bib
;
1687 int allsections
= 0, defsections
= 0;
1691 allsections
= strcasecmp(section
,"all") == 0;
1692 defsections
= strcasecmp(section
,"default") == 0;
1695 getrusage(RUSAGE_SELF
, &self_ru
);
1696 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1697 getClientsMaxBuffers(&lol
,&bib
);
1700 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1701 struct utsname name
;
1703 if (sections
++) info
= sdscat(info
,"\r\n");
1705 info
= sdscatprintf(info
,
1707 "redis_version:%s\r\n"
1708 "redis_git_sha1:%s\r\n"
1709 "redis_git_dirty:%d\r\n"
1712 "multiplexing_api:%s\r\n"
1713 "gcc_version:%d.%d.%d\r\n"
1714 "process_id:%ld\r\n"
1717 "uptime_in_seconds:%ld\r\n"
1718 "uptime_in_days:%ld\r\n"
1719 "lru_clock:%ld\r\n",
1722 strtol(redisGitDirty(),NULL
,10) > 0,
1723 name
.sysname
, name
.release
, name
.machine
,
1727 __GNUC__
,__GNUC_MINOR__
,__GNUC_PATCHLEVEL__
,
1736 (unsigned long) server
.lruclock
);
1740 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1741 if (sections
++) info
= sdscat(info
,"\r\n");
1742 info
= sdscatprintf(info
,
1744 "connected_clients:%lu\r\n"
1745 "client_longest_output_list:%lu\r\n"
1746 "client_biggest_input_buf:%lu\r\n"
1747 "blocked_clients:%d\r\n",
1748 listLength(server
.clients
)-listLength(server
.slaves
),
1750 server
.bpop_blocked_clients
);
1754 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1758 bytesToHuman(hmem
,zmalloc_used_memory());
1759 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1760 if (sections
++) info
= sdscat(info
,"\r\n");
1761 info
= sdscatprintf(info
,
1763 "used_memory:%zu\r\n"
1764 "used_memory_human:%s\r\n"
1765 "used_memory_rss:%zu\r\n"
1766 "used_memory_peak:%zu\r\n"
1767 "used_memory_peak_human:%s\r\n"
1768 "used_memory_lua:%lld\r\n"
1769 "mem_fragmentation_ratio:%.2f\r\n"
1770 "mem_allocator:%s\r\n",
1771 zmalloc_used_memory(),
1774 server
.stat_peak_memory
,
1776 ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL,
1777 zmalloc_get_fragmentation_ratio(),
1783 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1784 if (sections
++) info
= sdscat(info
,"\r\n");
1785 info
= sdscatprintf(info
,
1788 "aof_enabled:%d\r\n"
1789 "changes_since_last_save:%lld\r\n"
1790 "bgsave_in_progress:%d\r\n"
1791 "last_save_time:%ld\r\n"
1792 "last_bgsave_status:%s\r\n"
1793 "bgrewriteaof_in_progress:%d\r\n",
1795 server
.aof_state
!= REDIS_AOF_OFF
,
1797 server
.rdb_child_pid
!= -1,
1799 server
.lastbgsave_status
== REDIS_OK
? "ok" : "err",
1800 server
.aof_child_pid
!= -1);
1802 if (server
.aof_state
!= REDIS_AOF_OFF
) {
1803 info
= sdscatprintf(info
,
1804 "aof_current_size:%lld\r\n"
1805 "aof_base_size:%lld\r\n"
1806 "aof_pending_rewrite:%d\r\n"
1807 "aof_buffer_length:%zu\r\n"
1808 "aof_pending_bio_fsync:%llu\r\n"
1809 "aof_delayed_fsync:%lu\r\n",
1810 (long long) server
.aof_current_size
,
1811 (long long) server
.aof_rewrite_base_size
,
1812 server
.aof_rewrite_scheduled
,
1813 sdslen(server
.aof_buf
),
1814 bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
),
1815 server
.aof_delayed_fsync
);
1818 if (server
.loading
) {
1820 time_t eta
, elapsed
;
1821 off_t remaining_bytes
= server
.loading_total_bytes
-
1822 server
.loading_loaded_bytes
;
1824 perc
= ((double)server
.loading_loaded_bytes
/
1825 server
.loading_total_bytes
) * 100;
1827 elapsed
= server
.unixtime
-server
.loading_start_time
;
1829 eta
= 1; /* A fake 1 second figure if we don't have
1832 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1835 info
= sdscatprintf(info
,
1836 "loading_start_time:%ld\r\n"
1837 "loading_total_bytes:%llu\r\n"
1838 "loading_loaded_bytes:%llu\r\n"
1839 "loading_loaded_perc:%.2f\r\n"
1840 "loading_eta_seconds:%ld\r\n"
1841 ,(unsigned long) server
.loading_start_time
,
1842 (unsigned long long) server
.loading_total_bytes
,
1843 (unsigned long long) server
.loading_loaded_bytes
,
1851 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1852 if (sections
++) info
= sdscat(info
,"\r\n");
1853 info
= sdscatprintf(info
,
1855 "total_connections_received:%lld\r\n"
1856 "total_commands_processed:%lld\r\n"
1857 "instantaneous_ops_per_sec:%lld\r\n"
1858 "rejected_connections:%lld\r\n"
1859 "expired_keys:%lld\r\n"
1860 "evicted_keys:%lld\r\n"
1861 "keyspace_hits:%lld\r\n"
1862 "keyspace_misses:%lld\r\n"
1863 "pubsub_channels:%ld\r\n"
1864 "pubsub_patterns:%lu\r\n"
1865 "latest_fork_usec:%lld\r\n",
1866 server
.stat_numconnections
,
1867 server
.stat_numcommands
,
1868 getOperationsPerSecond(),
1869 server
.stat_rejected_conn
,
1870 server
.stat_expiredkeys
,
1871 server
.stat_evictedkeys
,
1872 server
.stat_keyspace_hits
,
1873 server
.stat_keyspace_misses
,
1874 dictSize(server
.pubsub_channels
),
1875 listLength(server
.pubsub_patterns
),
1876 server
.stat_fork_time
);
1880 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1881 if (sections
++) info
= sdscat(info
,"\r\n");
1882 info
= sdscatprintf(info
,
1885 server
.masterhost
== NULL
? "master" : "slave");
1886 if (server
.masterhost
) {
1887 info
= sdscatprintf(info
,
1888 "master_host:%s\r\n"
1889 "master_port:%d\r\n"
1890 "master_link_status:%s\r\n"
1891 "master_last_io_seconds_ago:%d\r\n"
1892 "master_sync_in_progress:%d\r\n"
1895 (server
.repl_state
== REDIS_REPL_CONNECTED
) ?
1898 ((int)(server
.unixtime
-server
.master
->lastinteraction
)) : -1,
1899 server
.repl_state
== REDIS_REPL_TRANSFER
1902 if (server
.repl_state
== REDIS_REPL_TRANSFER
) {
1903 info
= sdscatprintf(info
,
1904 "master_sync_left_bytes:%ld\r\n"
1905 "master_sync_last_io_seconds_ago:%d\r\n"
1906 ,(long)server
.repl_transfer_left
,
1907 (int)(server
.unixtime
-server
.repl_transfer_lastio
)
1911 if (server
.repl_state
!= REDIS_REPL_CONNECTED
) {
1912 info
= sdscatprintf(info
,
1913 "master_link_down_since_seconds:%ld\r\n",
1914 (long)server
.unixtime
-server
.repl_down_since
);
1917 info
= sdscatprintf(info
,
1918 "connected_slaves:%lu\r\n",
1919 listLength(server
.slaves
));
1920 if (listLength(server
.slaves
)) {
1925 listRewind(server
.slaves
,&li
);
1926 while((ln
= listNext(&li
))) {
1927 redisClient
*slave
= listNodeValue(ln
);
1932 if (anetPeerToString(slave
->fd
,ip
,&port
) == -1) continue;
1933 switch(slave
->replstate
) {
1934 case REDIS_REPL_WAIT_BGSAVE_START
:
1935 case REDIS_REPL_WAIT_BGSAVE_END
:
1936 state
= "wait_bgsave";
1938 case REDIS_REPL_SEND_BULK
:
1939 state
= "send_bulk";
1941 case REDIS_REPL_ONLINE
:
1945 if (state
== NULL
) continue;
1946 info
= sdscatprintf(info
,"slave%d:%s,%d,%s\r\n",
1947 slaveid
,ip
,port
,state
);
1954 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1955 if (sections
++) info
= sdscat(info
,"\r\n");
1956 info
= sdscatprintf(info
,
1958 "used_cpu_sys:%.2f\r\n"
1959 "used_cpu_user:%.2f\r\n"
1960 "used_cpu_sys_children:%.2f\r\n"
1961 "used_cpu_user_children:%.2f\r\n",
1962 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1963 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1964 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1965 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000);
1969 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1970 if (sections
++) info
= sdscat(info
,"\r\n");
1971 info
= sdscatprintf(info
, "# Commandstats\r\n");
1972 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1973 for (j
= 0; j
< numcommands
; j
++) {
1974 struct redisCommand
*c
= redisCommandTable
+j
;
1976 if (!c
->calls
) continue;
1977 info
= sdscatprintf(info
,
1978 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1979 c
->name
, c
->calls
, c
->microseconds
,
1980 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1985 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1986 if (sections
++) info
= sdscat(info
,"\r\n");
1987 info
= sdscatprintf(info
, "# Keyspace\r\n");
1988 for (j
= 0; j
< server
.dbnum
; j
++) {
1989 long long keys
, vkeys
;
1991 keys
= dictSize(server
.db
[j
].dict
);
1992 vkeys
= dictSize(server
.db
[j
].expires
);
1993 if (keys
|| vkeys
) {
1994 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
2002 void infoCommand(redisClient
*c
) {
2003 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
2006 addReply(c
,shared
.syntaxerr
);
2009 sds info
= genRedisInfoString(section
);
2010 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
2011 (unsigned long)sdslen(info
)));
2012 addReplySds(c
,info
);
2013 addReply(c
,shared
.crlf
);
2016 void monitorCommand(redisClient
*c
) {
2017 /* ignore MONITOR if aleady slave or in monitor mode */
2018 if (c
->flags
& REDIS_SLAVE
) return;
2020 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
2022 listAddNodeTail(server
.monitors
,c
);
2023 addReply(c
,shared
.ok
);
2026 /* ============================ Maxmemory directive ======================== */
2028 /* This function gets called when 'maxmemory' is set on the config file to limit
2029 * the max memory used by the server, before processing a command.
2031 * The goal of the function is to free enough memory to keep Redis under the
2032 * configured memory limit.
2034 * The function starts calculating how many bytes should be freed to keep
2035 * Redis under the limit, and enters a loop selecting the best keys to
2036 * evict accordingly to the configured policy.
2038 * If all the bytes needed to return back under the limit were freed the
2039 * function returns REDIS_OK, otherwise REDIS_ERR is returned, and the caller
2040 * should block the execution of commands that will result in more memory
2041 * used by the server.
2043 int freeMemoryIfNeeded(void) {
2044 size_t mem_used
, mem_tofree
, mem_freed
;
2045 int slaves
= listLength(server
.slaves
);
2047 /* Remove the size of slaves output buffers and AOF buffer from the
2048 * count of used memory. */
2049 mem_used
= zmalloc_used_memory();
2054 listRewind(server
.slaves
,&li
);
2055 while((ln
= listNext(&li
))) {
2056 redisClient
*slave
= listNodeValue(ln
);
2057 unsigned long obuf_bytes
= getClientOutputBufferMemoryUsage(slave
);
2058 if (obuf_bytes
> mem_used
)
2061 mem_used
-= obuf_bytes
;
2064 if (server
.aof_state
!= REDIS_AOF_OFF
) {
2065 mem_used
-= sdslen(server
.aof_buf
);
2066 mem_used
-= sdslen(server
.aof_rewrite_buf
);
2069 /* Check if we are over the memory limit. */
2070 if (mem_used
<= server
.maxmemory
) return REDIS_OK
;
2072 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
)
2073 return REDIS_ERR
; /* We need to free memory, but policy forbids. */
2075 /* Compute how much memory we need to free. */
2076 mem_tofree
= mem_used
- server
.maxmemory
;
2078 while (mem_freed
< mem_tofree
) {
2079 int j
, k
, keys_freed
= 0;
2081 for (j
= 0; j
< server
.dbnum
; j
++) {
2082 long bestval
= 0; /* just to prevent warning */
2084 struct dictEntry
*de
;
2085 redisDb
*db
= server
.db
+j
;
2088 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
2089 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
2091 dict
= server
.db
[j
].dict
;
2093 dict
= server
.db
[j
].expires
;
2095 if (dictSize(dict
) == 0) continue;
2097 /* volatile-random and allkeys-random policy */
2098 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
2099 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
2101 de
= dictGetRandomKey(dict
);
2102 bestkey
= dictGetKey(de
);
2105 /* volatile-lru and allkeys-lru policy */
2106 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
2107 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
2109 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
2114 de
= dictGetRandomKey(dict
);
2115 thiskey
= dictGetKey(de
);
2116 /* When policy is volatile-lru we need an additonal lookup
2117 * to locate the real key, as dict is set to db->expires. */
2118 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
2119 de
= dictFind(db
->dict
, thiskey
);
2121 thisval
= estimateObjectIdleTime(o
);
2123 /* Higher idle time is better candidate for deletion */
2124 if (bestkey
== NULL
|| thisval
> bestval
) {
2132 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
2133 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
2137 de
= dictGetRandomKey(dict
);
2138 thiskey
= dictGetKey(de
);
2139 thisval
= (long) dictGetVal(de
);
2141 /* Expire sooner (minor expire unix timestamp) is better
2142 * candidate for deletion */
2143 if (bestkey
== NULL
|| thisval
< bestval
) {
2150 /* Finally remove the selected key. */
2154 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
2155 propagateExpire(db
,keyobj
);
2156 /* We compute the amount of memory freed by dbDelete() alone.
2157 * It is possible that actually the memory needed to propagate
2158 * the DEL in AOF and replication link is greater than the one
2159 * we are freeing removing the key, but we can't account for
2160 * that otherwise we would never exit the loop.
2162 * AOF and Output buffer memory will be freed eventually so
2163 * we only care about memory used by the key space. */
2164 delta
= (long long) zmalloc_used_memory();
2165 dbDelete(db
,keyobj
);
2166 delta
-= (long long) zmalloc_used_memory();
2168 server
.stat_evictedkeys
++;
2169 decrRefCount(keyobj
);
2172 /* When the memory to free starts to be big enough, we may
2173 * start spending so much time here that is impossible to
2174 * deliver data to the slaves fast enough, so we force the
2175 * transmission here inside the loop. */
2176 if (slaves
) flushSlavesOutputBuffers();
2179 if (!keys_freed
) return REDIS_ERR
; /* nothing to free... */
2184 /* =================================== Main! ================================ */
2187 int linuxOvercommitMemoryValue(void) {
2188 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
2192 if (fgets(buf
,64,fp
) == NULL
) {
2201 void linuxOvercommitMemoryWarning(void) {
2202 if (linuxOvercommitMemoryValue() == 0) {
2203 redisLog(REDIS_WARNING
,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
2206 #endif /* __linux__ */
2208 void createPidFile(void) {
2209 /* Try to write the pid file in a best-effort way. */
2210 FILE *fp
= fopen(server
.pidfile
,"w");
2212 fprintf(fp
,"%d\n",(int)getpid());
2217 void daemonize(void) {
2220 if (fork() != 0) exit(0); /* parent exits */
2221 setsid(); /* create a new session */
2223 /* Every output goes to /dev/null. If Redis is daemonized but
2224 * the 'logfile' is set to 'stdout' in the configuration file
2225 * it will not log at all. */
2226 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
2227 dup2(fd
, STDIN_FILENO
);
2228 dup2(fd
, STDOUT_FILENO
);
2229 dup2(fd
, STDERR_FILENO
);
2230 if (fd
> STDERR_FILENO
) close(fd
);
2235 printf("Redis server v=%s sha=%s:%d malloc=%s\n", REDIS_VERSION
,
2236 redisGitSHA1(), atoi(redisGitDirty()) > 0, ZMALLOC_LIB
);
2241 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf] [options]\n");
2242 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
2243 fprintf(stderr
," ./redis-server -v or --version\n");
2244 fprintf(stderr
," ./redis-server -h or --help\n");
2245 fprintf(stderr
," ./redis-server --test-memory <megabytes>\n\n");
2246 fprintf(stderr
,"Examples:\n");
2247 fprintf(stderr
," ./redis-server (run the server with default conf)\n");
2248 fprintf(stderr
," ./redis-server /etc/redis/6379.conf\n");
2249 fprintf(stderr
," ./redis-server --port 7777\n");
2250 fprintf(stderr
," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n");
2251 fprintf(stderr
," ./redis-server /etc/myredis.conf --loglevel verbose\n");
2255 void redisAsciiArt(void) {
2256 #include "asciilogo.h"
2257 char *buf
= zmalloc(1024*16);
2259 snprintf(buf
,1024*16,ascii_logo
,
2262 strtol(redisGitDirty(),NULL
,10) > 0,
2263 (sizeof(long) == 8) ? "64" : "32",
2268 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
2272 static void sigtermHandler(int sig
) {
2275 redisLogFromHandler(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
2276 server
.shutdown_asap
= 1;
2279 void setupSignalHandlers(void) {
2280 struct sigaction act
;
2282 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
2283 * Otherwise, sa_handler is used. */
2284 sigemptyset(&act
.sa_mask
);
2285 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
2286 act
.sa_handler
= sigtermHandler
;
2287 sigaction(SIGTERM
, &act
, NULL
);
2289 #ifdef HAVE_BACKTRACE
2290 sigemptyset(&act
.sa_mask
);
2291 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
2292 act
.sa_sigaction
= sigsegvHandler
;
2293 sigaction(SIGSEGV
, &act
, NULL
);
2294 sigaction(SIGBUS
, &act
, NULL
);
2295 sigaction(SIGFPE
, &act
, NULL
);
2296 sigaction(SIGILL
, &act
, NULL
);
2301 void memtest(size_t megabytes
, int passes
);
2303 int main(int argc
, char **argv
) {
2307 /* We need to initialize our libraries, and the server configuration. */
2308 zmalloc_enable_thread_safeness();
2309 srand(time(NULL
)^getpid());
2310 gettimeofday(&tv
,NULL
);
2311 dictSetHashFunctionSeed(tv
.tv_sec
^tv
.tv_usec
^getpid());
2315 int j
= 1; /* First option to parse in argv[] */
2316 sds options
= sdsempty();
2317 char *configfile
= NULL
;
2319 /* Handle special options --help and --version */
2320 if (strcmp(argv
[1], "-v") == 0 ||
2321 strcmp(argv
[1], "--version") == 0) version();
2322 if (strcmp(argv
[1], "--help") == 0 ||
2323 strcmp(argv
[1], "-h") == 0) usage();
2324 if (strcmp(argv
[1], "--test-memory") == 0) {
2326 memtest(atoi(argv
[2]),50);
2329 fprintf(stderr
,"Please specify the amount of memory to test in megabytes.\n");
2330 fprintf(stderr
,"Example: ./redis-server --test-memory 4096\n\n");
2335 /* First argument is the config file name? */
2336 if (argv
[j
][0] != '-' || argv
[j
][1] != '-')
2337 configfile
= argv
[j
++];
2338 /* All the other options are parsed and conceptually appended to the
2339 * configuration file. For instance --port 6380 will generate the
2340 * string "port 6380\n" to be parsed after the actual file name
2341 * is parsed, if any. */
2343 if (argv
[j
][0] == '-' && argv
[j
][1] == '-') {
2345 if (sdslen(options
)) options
= sdscat(options
,"\n");
2346 options
= sdscat(options
,argv
[j
]+2);
2347 options
= sdscat(options
," ");
2349 /* Option argument */
2350 options
= sdscatrepr(options
,argv
[j
],strlen(argv
[j
]));
2351 options
= sdscat(options
," ");
2355 resetServerSaveParams();
2356 loadServerConfig(configfile
,options
);
2359 redisLog(REDIS_WARNING
,"Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'");
2361 if (server
.daemonize
) daemonize();
2363 if (server
.daemonize
) createPidFile();
2365 redisLog(REDIS_WARNING
,"Server started, Redis version " REDIS_VERSION
);
2367 linuxOvercommitMemoryWarning();
2370 if (server
.aof_state
== REDIS_AOF_ON
) {
2371 if (loadAppendOnlyFile(server
.aof_filename
) == REDIS_OK
)
2372 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
2374 if (rdbLoad(server
.rdb_filename
) == REDIS_OK
) {
2375 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",
2376 (float)(ustime()-start
)/1000000);
2377 } else if (errno
!= ENOENT
) {
2378 redisLog(REDIS_WARNING
,"Fatal error loading the DB. Exiting.");
2382 if (server
.ipfd
> 0)
2383 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
2384 if (server
.sofd
> 0)
2385 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
2386 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
2388 aeDeleteEventLoop(server
.el
);