]>
Commit | Line | Data |
---|---|---|
e2641e09 | 1 | /* |
2 | * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> | |
3 | * All rights reserved. | |
4 | * | |
5 | * Redistribution and use in source and binary forms, with or without | |
6 | * modification, are permitted provided that the following conditions are met: | |
7 | * | |
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. | |
16 | * | |
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. | |
28 | */ | |
29 | ||
30 | #include "redis.h" | |
daa70b17 | 31 | #include "slowlog.h" |
8f61a72f | 32 | #include "bio.h" |
e2641e09 | 33 | |
34 | #ifdef HAVE_BACKTRACE | |
35 | #include <execinfo.h> | |
36 | #include <ucontext.h> | |
37 | #endif /* HAVE_BACKTRACE */ | |
38 | ||
39 | #include <time.h> | |
40 | #include <signal.h> | |
41 | #include <sys/wait.h> | |
42 | #include <errno.h> | |
43 | #include <assert.h> | |
44 | #include <ctype.h> | |
45 | #include <stdarg.h> | |
e2641e09 | 46 | #include <arpa/inet.h> |
47 | #include <sys/stat.h> | |
48 | #include <fcntl.h> | |
49 | #include <sys/time.h> | |
50 | #include <sys/resource.h> | |
51 | #include <sys/uio.h> | |
52 | #include <limits.h> | |
53 | #include <float.h> | |
54 | #include <math.h> | |
2b00385d | 55 | #include <sys/resource.h> |
e2641e09 | 56 | |
57 | /* Our shared "common" objects */ | |
58 | ||
59 | struct sharedObjectsStruct shared; | |
60 | ||
c74b7c77 | 61 | /* Global vars that are actually used as constants. The following double |
e2641e09 | 62 | * values are used for double on-disk serialization, and are initialized |
63 | * at runtime to avoid strange compiler optimizations. */ | |
64 | ||
65 | double R_Zero, R_PosInf, R_NegInf, R_Nan; | |
66 | ||
67 | /*================================= Globals ================================= */ | |
68 | ||
69 | /* Global vars */ | |
70 | struct redisServer server; /* server global state */ | |
71 | struct redisCommand *commandTable; | |
5d02b00f | 72 | |
73 | /* Our command table. Command flags are expressed using strings where every | |
74 | * character represents a flag. Later the populateCommandTable() function will | |
75 | * take care of populating the real 'flags' field using this characters. | |
76 | * | |
77 | * This is the meaning of the flags: | |
78 | * | |
79 | * w: write command (may modify the key space). | |
80 | * r: read command (will never modify the key space). | |
81 | * m: may increase memory usage once called. Don't allow if out of memory. | |
82 | * a: admin command, like SAVE or SHUTDOWN. | |
83 | * p: Pub/Sub related command. | |
b60ed6e8 | 84 | * f: force replication of this command, regarless of server.dirty. |
85 | * s: command not allowed in scripts. | |
86 | * r: random command. Command is not deterministic, that is, the same command | |
87 | * with the same arguments, with the same key space, may have different | |
88 | * results. For instance SPOP and RANDOMKEY are two random commands. */ | |
d7ed7fd2 | 89 | struct redisCommand redisCommandTable[] = { |
5d02b00f | 90 | {"get",getCommand,2,"r",0,NULL,1,1,1,0,0}, |
91 | {"set",setCommand,3,"wm",0,noPreloadGetKeys,1,1,1,0,0}, | |
92 | {"setnx",setnxCommand,3,"wm",0,noPreloadGetKeys,1,1,1,0,0}, | |
93 | {"setex",setexCommand,4,"wm",0,noPreloadGetKeys,2,2,1,0,0}, | |
94 | {"append",appendCommand,3,"wm",0,NULL,1,1,1,0,0}, | |
95 | {"strlen",strlenCommand,2,"r",0,NULL,1,1,1,0,0}, | |
96 | {"del",delCommand,-2,"w",0,noPreloadGetKeys,1,-1,1,0,0}, | |
97 | {"exists",existsCommand,2,"r",0,NULL,1,1,1,0,0}, | |
98 | {"setbit",setbitCommand,4,"wm",0,NULL,1,1,1,0,0}, | |
99 | {"getbit",getbitCommand,3,"r",0,NULL,1,1,1,0,0}, | |
100 | {"setrange",setrangeCommand,4,"wm",0,NULL,1,1,1,0,0}, | |
101 | {"getrange",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, | |
102 | {"substr",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, | |
103 | {"incr",incrCommand,2,"wm",0,NULL,1,1,1,0,0}, | |
104 | {"decr",decrCommand,2,"wm",0,NULL,1,1,1,0,0}, | |
105 | {"mget",mgetCommand,-2,"r",0,NULL,1,-1,1,0,0}, | |
106 | {"rpush",rpushCommand,-3,"wm",0,NULL,1,1,1,0,0}, | |
107 | {"lpush",lpushCommand,-3,"wm",0,NULL,1,1,1,0,0}, | |
108 | {"rpushx",rpushxCommand,3,"wm",0,NULL,1,1,1,0,0}, | |
109 | {"lpushx",lpushxCommand,3,"wm",0,NULL,1,1,1,0,0}, | |
110 | {"linsert",linsertCommand,5,"wm",0,NULL,1,1,1,0,0}, | |
111 | {"rpop",rpopCommand,2,"w",0,NULL,1,1,1,0,0}, | |
112 | {"lpop",lpopCommand,2,"w",0,NULL,1,1,1,0,0}, | |
113 | {"brpop",brpopCommand,-3,"w",0,NULL,1,1,1,0,0}, | |
114 | {"brpoplpush",brpoplpushCommand,4,"wm",0,NULL,1,2,1,0,0}, | |
115 | {"blpop",blpopCommand,-3,"w",0,NULL,1,-2,1,0,0}, | |
116 | {"llen",llenCommand,2,"r",0,NULL,1,1,1,0,0}, | |
117 | {"lindex",lindexCommand,3,"r",0,NULL,1,1,1,0,0}, | |
118 | {"lset",lsetCommand,4,"wm",0,NULL,1,1,1,0,0}, | |
119 | {"lrange",lrangeCommand,4,"r",0,NULL,1,1,1,0,0}, | |
120 | {"ltrim",ltrimCommand,4,"w",0,NULL,1,1,1,0,0}, | |
121 | {"lrem",lremCommand,4,"w",0,NULL,1,1,1,0,0}, | |
122 | {"rpoplpush",rpoplpushCommand,3,"wm",0,NULL,1,2,1,0,0}, | |
123 | {"sadd",saddCommand,-3,"wm",0,NULL,1,1,1,0,0}, | |
124 | {"srem",sremCommand,-3,"w",0,NULL,1,1,1,0,0}, | |
125 | {"smove",smoveCommand,4,"w",0,NULL,1,2,1,0,0}, | |
126 | {"sismember",sismemberCommand,3,"r",0,NULL,1,1,1,0,0}, | |
127 | {"scard",scardCommand,2,"r",0,NULL,1,1,1,0,0}, | |
15ef6053 | 128 | {"spop",spopCommand,2,"wRs",0,NULL,1,1,1,0,0}, |
b60ed6e8 | 129 | {"srandmember",srandmemberCommand,2,"rR",0,NULL,1,1,1,0,0}, |
5d02b00f | 130 | {"sinter",sinterCommand,-2,"r",0,NULL,1,-1,1,0,0}, |
131 | {"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,2,-1,1,0,0}, | |
132 | {"sunion",sunionCommand,-2,"r",0,NULL,1,-1,1,0,0}, | |
133 | {"sunionstore",sunionstoreCommand,-3,"wm",0,NULL,2,-1,1,0,0}, | |
134 | {"sdiff",sdiffCommand,-2,"r",0,NULL,1,-1,1,0,0}, | |
135 | {"sdiffstore",sdiffstoreCommand,-3,"wm",0,NULL,2,-1,1,0,0}, | |
136 | {"smembers",sinterCommand,2,"r",0,NULL,1,1,1,0,0}, | |
137 | {"zadd",zaddCommand,-4,"wm",0,NULL,1,1,1,0,0}, | |
138 | {"zincrby",zincrbyCommand,4,"wm",0,NULL,1,1,1,0,0}, | |
139 | {"zrem",zremCommand,-3,"w",0,NULL,1,1,1,0,0}, | |
140 | {"zremrangebyscore",zremrangebyscoreCommand,4,"w",0,NULL,1,1,1,0,0}, | |
141 | {"zremrangebyrank",zremrangebyrankCommand,4,"w",0,NULL,1,1,1,0,0}, | |
142 | {"zunionstore",zunionstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, | |
143 | {"zinterstore",zinterstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, | |
144 | {"zrange",zrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, | |
145 | {"zrangebyscore",zrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, | |
146 | {"zrevrangebyscore",zrevrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, | |
147 | {"zcount",zcountCommand,4,"r",0,NULL,1,1,1,0,0}, | |
148 | {"zrevrange",zrevrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, | |
149 | {"zcard",zcardCommand,2,"r",0,NULL,1,1,1,0,0}, | |
150 | {"zscore",zscoreCommand,3,"r",0,NULL,1,1,1,0,0}, | |
151 | {"zrank",zrankCommand,3,"r",0,NULL,1,1,1,0,0}, | |
152 | {"zrevrank",zrevrankCommand,3,"r",0,NULL,1,1,1,0,0}, | |
153 | {"hset",hsetCommand,4,"wm",0,NULL,1,1,1,0,0}, | |
154 | {"hsetnx",hsetnxCommand,4,"wm",0,NULL,1,1,1,0,0}, | |
155 | {"hget",hgetCommand,3,"r",0,NULL,1,1,1,0,0}, | |
156 | {"hmset",hmsetCommand,-4,"wm",0,NULL,1,1,1,0,0}, | |
157 | {"hmget",hmgetCommand,-3,"r",0,NULL,1,1,1,0,0}, | |
158 | {"hincrby",hincrbyCommand,4,"wm",0,NULL,1,1,1,0,0}, | |
159 | {"hdel",hdelCommand,-3,"w",0,NULL,1,1,1,0,0}, | |
160 | {"hlen",hlenCommand,2,"r",0,NULL,1,1,1,0,0}, | |
161 | {"hkeys",hkeysCommand,2,"r",0,NULL,1,1,1,0,0}, | |
162 | {"hvals",hvalsCommand,2,"r",0,NULL,1,1,1,0,0}, | |
163 | {"hgetall",hgetallCommand,2,"r",0,NULL,1,1,1,0,0}, | |
164 | {"hexists",hexistsCommand,3,"r",0,NULL,1,1,1,0,0}, | |
165 | {"incrby",incrbyCommand,3,"wm",0,NULL,1,1,1,0,0}, | |
166 | {"decrby",decrbyCommand,3,"wm",0,NULL,1,1,1,0,0}, | |
167 | {"getset",getsetCommand,3,"wm",0,NULL,1,1,1,0,0}, | |
168 | {"mset",msetCommand,-3,"wm",0,NULL,1,-1,2,0,0}, | |
169 | {"msetnx",msetnxCommand,-3,"wm",0,NULL,1,-1,2,0,0}, | |
b60ed6e8 | 170 | {"randomkey",randomkeyCommand,1,"rR",0,NULL,0,0,0,0,0}, |
5d02b00f | 171 | {"select",selectCommand,2,"r",0,NULL,0,0,0,0,0}, |
172 | {"move",moveCommand,3,"w",0,NULL,1,1,1,0,0}, | |
173 | {"rename",renameCommand,3,"w",0,renameGetKeys,1,2,1,0,0}, | |
174 | {"renamenx",renamenxCommand,3,"w",0,renameGetKeys,1,2,1,0,0}, | |
175 | {"expire",expireCommand,3,"w",0,NULL,1,1,1,0,0}, | |
176 | {"expireat",expireatCommand,3,"w",0,NULL,1,1,1,0,0}, | |
177 | {"keys",keysCommand,2,"r",0,NULL,0,0,0,0,0}, | |
178 | {"dbsize",dbsizeCommand,1,"r",0,NULL,0,0,0,0,0}, | |
179 | {"auth",authCommand,2,"r",0,NULL,0,0,0,0,0}, | |
180 | {"ping",pingCommand,1,"r",0,NULL,0,0,0,0,0}, | |
181 | {"echo",echoCommand,2,"r",0,NULL,0,0,0,0,0}, | |
182 | {"save",saveCommand,1,"ar",0,NULL,0,0,0,0,0}, | |
183 | {"bgsave",bgsaveCommand,1,"ar",0,NULL,0,0,0,0,0}, | |
184 | {"bgrewriteaof",bgrewriteaofCommand,1,"ar",0,NULL,0,0,0,0,0}, | |
185 | {"shutdown",shutdownCommand,1,"ar",0,NULL,0,0,0,0,0}, | |
186 | {"lastsave",lastsaveCommand,1,"r",0,NULL,0,0,0,0,0}, | |
187 | {"type",typeCommand,2,"r",0,NULL,1,1,1,0,0}, | |
b60ed6e8 | 188 | {"multi",multiCommand,1,"rs",0,NULL,0,0,0,0,0}, |
189 | {"exec",execCommand,1,"wms",0,NULL,0,0,0,0,0}, | |
190 | {"discard",discardCommand,1,"rs",0,NULL,0,0,0,0,0}, | |
191 | {"sync",syncCommand,1,"ars",0,NULL,0,0,0,0,0}, | |
5d02b00f | 192 | {"flushdb",flushdbCommand,1,"w",0,NULL,0,0,0,0,0}, |
193 | {"flushall",flushallCommand,1,"w",0,NULL,0,0,0,0,0}, | |
194 | {"sort",sortCommand,-2,"wm",0,NULL,1,1,1,0,0}, | |
195 | {"info",infoCommand,-1,"r",0,NULL,0,0,0,0,0}, | |
b60ed6e8 | 196 | {"monitor",monitorCommand,1,"ars",0,NULL,0,0,0,0,0}, |
5d02b00f | 197 | {"ttl",ttlCommand,2,"r",0,NULL,1,1,1,0,0}, |
198 | {"persist",persistCommand,2,"w",0,NULL,1,1,1,0,0}, | |
b60ed6e8 | 199 | {"slaveof",slaveofCommand,3,"aws",0,NULL,0,0,0,0,0}, |
5d02b00f | 200 | {"debug",debugCommand,-2,"aw",0,NULL,0,0,0,0,0}, |
201 | {"config",configCommand,-2,"ar",0,NULL,0,0,0,0,0}, | |
b60ed6e8 | 202 | {"subscribe",subscribeCommand,-2,"rps",0,NULL,0,0,0,0,0}, |
203 | {"unsubscribe",unsubscribeCommand,-1,"rps",0,NULL,0,0,0,0,0}, | |
204 | {"psubscribe",psubscribeCommand,-2,"rps",0,NULL,0,0,0,0,0}, | |
205 | {"punsubscribe",punsubscribeCommand,-1,"rps",0,NULL,0,0,0,0,0}, | |
5d02b00f | 206 | {"publish",publishCommand,3,"rpf",0,NULL,0,0,0,0,0}, |
b60ed6e8 | 207 | {"watch",watchCommand,-2,"rs",0,noPreloadGetKeys,1,-1,1,0,0}, |
208 | {"unwatch",unwatchCommand,1,"rs",0,NULL,0,0,0,0,0}, | |
5d02b00f | 209 | {"cluster",clusterCommand,-2,"ar",0,NULL,0,0,0,0,0}, |
7afc3a96 | 210 | {"restore",restoreCommand,4,"awm",0,NULL,1,1,1,0,0}, |
5d02b00f | 211 | {"migrate",migrateCommand,6,"aw",0,NULL,0,0,0,0,0}, |
6856c7b4 | 212 | {"asking",askingCommand,1,"r",0,NULL,0,0,0,0,0}, |
5d02b00f | 213 | {"dump",dumpCommand,2,"ar",0,NULL,0,0,0,0,0}, |
214 | {"object",objectCommand,-2,"r",0,NULL,0,0,0,0,0}, | |
215 | {"client",clientCommand,-2,"ar",0,NULL,0,0,0,0,0}, | |
b60ed6e8 | 216 | {"eval",evalCommand,-3,"wms",0,zunionInterGetKeys,0,0,0,0,0}, |
217 | {"evalsha",evalShaCommand,-3,"wms",0,zunionInterGetKeys,0,0,0,0,0}, | |
5d02b00f | 218 | {"slowlog",slowlogCommand,-2,"r",0,NULL,0,0,0,0,0} |
e2641e09 | 219 | }; |
220 | ||
221 | /*============================ Utility functions ============================ */ | |
222 | ||
9c104c68 | 223 | /* Low level logging. To use only for very big messages, otherwise |
224 | * redisLog() is to prefer. */ | |
225 | void redisLogRaw(int level, const char *msg) { | |
e1a586ee JH |
226 | const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING }; |
227 | const char *c = ".-*#"; | |
228 | time_t now = time(NULL); | |
e2641e09 | 229 | FILE *fp; |
23072961 | 230 | char buf[64]; |
996d503d | 231 | int rawmode = (level & REDIS_LOG_RAW); |
23072961 | 232 | |
996d503d | 233 | level &= 0xff; /* clear flags */ |
23072961 | 234 | if (level < server.verbosity) return; |
e2641e09 | 235 | |
236 | fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a"); | |
237 | if (!fp) return; | |
238 | ||
996d503d | 239 | if (rawmode) { |
240 | fprintf(fp,"%s",msg); | |
241 | } else { | |
242 | strftime(buf,sizeof(buf),"%d %b %H:%M:%S",localtime(&now)); | |
243 | fprintf(fp,"[%d] %s %c %s\n",(int)getpid(),buf,c[level],msg); | |
244 | } | |
e1a586ee JH |
245 | fflush(fp); |
246 | ||
e2641e09 | 247 | if (server.logfile) fclose(fp); |
e1a586ee JH |
248 | |
249 | if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg); | |
e2641e09 | 250 | } |
251 | ||
9c104c68 | 252 | /* Like redisLogRaw() but with printf-alike support. This is the funciton that |
253 | * is used across the code. The raw version is only used in order to dump | |
254 | * the INFO output on crash. */ | |
255 | void redisLog(int level, const char *fmt, ...) { | |
256 | va_list ap; | |
257 | char msg[REDIS_MAX_LOGMSG_LEN]; | |
258 | ||
996d503d | 259 | if ((level&0xff) < server.verbosity) return; |
9c104c68 | 260 | |
261 | va_start(ap, fmt); | |
262 | vsnprintf(msg, sizeof(msg), fmt, ap); | |
263 | va_end(ap); | |
264 | ||
265 | redisLogRaw(level,msg); | |
266 | } | |
267 | ||
e2641e09 | 268 | /* Redis generally does not try to recover from out of memory conditions |
269 | * when allocating objects or strings, it is not clear if it will be possible | |
270 | * to report this condition to the client since the networking layer itself | |
271 | * is based on heap allocation for send buffers, so we simply abort. | |
272 | * At least the code will be simpler to read... */ | |
273 | void oom(const char *msg) { | |
274 | redisLog(REDIS_WARNING, "%s: Out of memory\n",msg); | |
275 | sleep(1); | |
276 | abort(); | |
277 | } | |
278 | ||
d9cb288c | 279 | /* Return the UNIX time in microseconds */ |
280 | long long ustime(void) { | |
281 | struct timeval tv; | |
282 | long long ust; | |
283 | ||
284 | gettimeofday(&tv, NULL); | |
285 | ust = ((long long)tv.tv_sec)*1000000; | |
286 | ust += tv.tv_usec; | |
287 | return ust; | |
288 | } | |
289 | ||
e2641e09 | 290 | /*====================== Hash table type implementation ==================== */ |
291 | ||
292 | /* This is an hash table type that uses the SDS dynamic strings libary as | |
293 | * keys and radis objects as values (objects can hold SDS strings, | |
294 | * lists, sets). */ | |
295 | ||
296 | void dictVanillaFree(void *privdata, void *val) | |
297 | { | |
298 | DICT_NOTUSED(privdata); | |
299 | zfree(val); | |
300 | } | |
301 | ||
302 | void dictListDestructor(void *privdata, void *val) | |
303 | { | |
304 | DICT_NOTUSED(privdata); | |
305 | listRelease((list*)val); | |
306 | } | |
307 | ||
308 | int dictSdsKeyCompare(void *privdata, const void *key1, | |
309 | const void *key2) | |
310 | { | |
311 | int l1,l2; | |
312 | DICT_NOTUSED(privdata); | |
313 | ||
314 | l1 = sdslen((sds)key1); | |
315 | l2 = sdslen((sds)key2); | |
316 | if (l1 != l2) return 0; | |
317 | return memcmp(key1, key2, l1) == 0; | |
318 | } | |
319 | ||
1b1f47c9 | 320 | /* A case insensitive version used for the command lookup table. */ |
321 | int dictSdsKeyCaseCompare(void *privdata, const void *key1, | |
322 | const void *key2) | |
323 | { | |
324 | DICT_NOTUSED(privdata); | |
325 | ||
326 | return strcasecmp(key1, key2) == 0; | |
327 | } | |
328 | ||
e2641e09 | 329 | void dictRedisObjectDestructor(void *privdata, void *val) |
330 | { | |
331 | DICT_NOTUSED(privdata); | |
332 | ||
333 | if (val == NULL) return; /* Values of swapped out keys as set to NULL */ | |
334 | decrRefCount(val); | |
335 | } | |
336 | ||
337 | void dictSdsDestructor(void *privdata, void *val) | |
338 | { | |
339 | DICT_NOTUSED(privdata); | |
340 | ||
341 | sdsfree(val); | |
342 | } | |
343 | ||
344 | int dictObjKeyCompare(void *privdata, const void *key1, | |
345 | const void *key2) | |
346 | { | |
347 | const robj *o1 = key1, *o2 = key2; | |
348 | return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); | |
349 | } | |
350 | ||
351 | unsigned int dictObjHash(const void *key) { | |
352 | const robj *o = key; | |
353 | return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
354 | } | |
355 | ||
356 | unsigned int dictSdsHash(const void *key) { | |
357 | return dictGenHashFunction((unsigned char*)key, sdslen((char*)key)); | |
358 | } | |
359 | ||
1b1f47c9 | 360 | unsigned int dictSdsCaseHash(const void *key) { |
361 | return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key)); | |
362 | } | |
363 | ||
e2641e09 | 364 | int dictEncObjKeyCompare(void *privdata, const void *key1, |
365 | const void *key2) | |
366 | { | |
367 | robj *o1 = (robj*) key1, *o2 = (robj*) key2; | |
368 | int cmp; | |
369 | ||
370 | if (o1->encoding == REDIS_ENCODING_INT && | |
371 | o2->encoding == REDIS_ENCODING_INT) | |
372 | return o1->ptr == o2->ptr; | |
373 | ||
374 | o1 = getDecodedObject(o1); | |
375 | o2 = getDecodedObject(o2); | |
376 | cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); | |
377 | decrRefCount(o1); | |
378 | decrRefCount(o2); | |
379 | return cmp; | |
380 | } | |
381 | ||
382 | unsigned int dictEncObjHash(const void *key) { | |
383 | robj *o = (robj*) key; | |
384 | ||
385 | if (o->encoding == REDIS_ENCODING_RAW) { | |
386 | return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
387 | } else { | |
388 | if (o->encoding == REDIS_ENCODING_INT) { | |
389 | char buf[32]; | |
390 | int len; | |
391 | ||
392 | len = ll2string(buf,32,(long)o->ptr); | |
393 | return dictGenHashFunction((unsigned char*)buf, len); | |
394 | } else { | |
395 | unsigned int hash; | |
396 | ||
397 | o = getDecodedObject(o); | |
398 | hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
399 | decrRefCount(o); | |
400 | return hash; | |
401 | } | |
402 | } | |
403 | } | |
404 | ||
4dd444bb | 405 | /* Sets type hash table */ |
e2641e09 | 406 | dictType setDictType = { |
407 | dictEncObjHash, /* hash function */ | |
408 | NULL, /* key dup */ | |
409 | NULL, /* val dup */ | |
410 | dictEncObjKeyCompare, /* key compare */ | |
411 | dictRedisObjectDestructor, /* key destructor */ | |
412 | NULL /* val destructor */ | |
413 | }; | |
414 | ||
415 | /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ | |
416 | dictType zsetDictType = { | |
417 | dictEncObjHash, /* hash function */ | |
418 | NULL, /* key dup */ | |
419 | NULL, /* val dup */ | |
420 | dictEncObjKeyCompare, /* key compare */ | |
421 | dictRedisObjectDestructor, /* key destructor */ | |
69ef89f2 | 422 | NULL /* val destructor */ |
e2641e09 | 423 | }; |
424 | ||
425 | /* Db->dict, keys are sds strings, vals are Redis objects. */ | |
426 | dictType dbDictType = { | |
427 | dictSdsHash, /* hash function */ | |
428 | NULL, /* key dup */ | |
429 | NULL, /* val dup */ | |
430 | dictSdsKeyCompare, /* key compare */ | |
431 | dictSdsDestructor, /* key destructor */ | |
432 | dictRedisObjectDestructor /* val destructor */ | |
433 | }; | |
434 | ||
435 | /* Db->expires */ | |
436 | dictType keyptrDictType = { | |
437 | dictSdsHash, /* hash function */ | |
438 | NULL, /* key dup */ | |
439 | NULL, /* val dup */ | |
440 | dictSdsKeyCompare, /* key compare */ | |
441 | NULL, /* key destructor */ | |
442 | NULL /* val destructor */ | |
443 | }; | |
444 | ||
1b1f47c9 | 445 | /* Command table. sds string -> command struct pointer. */ |
446 | dictType commandTableDictType = { | |
447 | dictSdsCaseHash, /* hash function */ | |
448 | NULL, /* key dup */ | |
449 | NULL, /* val dup */ | |
450 | dictSdsKeyCaseCompare, /* key compare */ | |
451 | dictSdsDestructor, /* key destructor */ | |
452 | NULL /* val destructor */ | |
453 | }; | |
454 | ||
e2641e09 | 455 | /* Hash type hash table (note that small hashes are represented with zimpaps) */ |
456 | dictType hashDictType = { | |
457 | dictEncObjHash, /* hash function */ | |
458 | NULL, /* key dup */ | |
459 | NULL, /* val dup */ | |
460 | dictEncObjKeyCompare, /* key compare */ | |
461 | dictRedisObjectDestructor, /* key destructor */ | |
462 | dictRedisObjectDestructor /* val destructor */ | |
463 | }; | |
464 | ||
465 | /* Keylist hash table type has unencoded redis objects as keys and | |
466 | * lists as values. It's used for blocking operations (BLPOP) and to | |
467 | * map swapped keys to a list of clients waiting for this keys to be loaded. */ | |
468 | dictType keylistDictType = { | |
469 | dictObjHash, /* hash function */ | |
470 | NULL, /* key dup */ | |
471 | NULL, /* val dup */ | |
472 | dictObjKeyCompare, /* key compare */ | |
473 | dictRedisObjectDestructor, /* key destructor */ | |
474 | dictListDestructor /* val destructor */ | |
475 | }; | |
476 | ||
ecc91094 | 477 | /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to |
478 | * clusterNode structures. */ | |
479 | dictType clusterNodesDictType = { | |
480 | dictSdsHash, /* hash function */ | |
481 | NULL, /* key dup */ | |
482 | NULL, /* val dup */ | |
483 | dictSdsKeyCompare, /* key compare */ | |
484 | dictSdsDestructor, /* key destructor */ | |
485 | NULL /* val destructor */ | |
486 | }; | |
487 | ||
e2641e09 | 488 | int htNeedsResize(dict *dict) { |
489 | long long size, used; | |
490 | ||
491 | size = dictSlots(dict); | |
492 | used = dictSize(dict); | |
493 | return (size && used && size > DICT_HT_INITIAL_SIZE && | |
494 | (used*100/size < REDIS_HT_MINFILL)); | |
495 | } | |
496 | ||
497 | /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL | |
498 | * we resize the hash table to save memory */ | |
499 | void tryResizeHashTables(void) { | |
500 | int j; | |
501 | ||
502 | for (j = 0; j < server.dbnum; j++) { | |
503 | if (htNeedsResize(server.db[j].dict)) | |
504 | dictResize(server.db[j].dict); | |
505 | if (htNeedsResize(server.db[j].expires)) | |
506 | dictResize(server.db[j].expires); | |
507 | } | |
508 | } | |
509 | ||
510 | /* Our hash table implementation performs rehashing incrementally while | |
511 | * we write/read from the hash table. Still if the server is idle, the hash | |
512 | * table will use two tables for a long time. So we try to use 1 millisecond | |
513 | * of CPU time at every serverCron() loop in order to rehash some key. */ | |
514 | void incrementallyRehash(void) { | |
515 | int j; | |
516 | ||
517 | for (j = 0; j < server.dbnum; j++) { | |
518 | if (dictIsRehashing(server.db[j].dict)) { | |
519 | dictRehashMilliseconds(server.db[j].dict,1); | |
520 | break; /* already used our millisecond for this loop... */ | |
521 | } | |
522 | } | |
523 | } | |
524 | ||
525 | /* This function is called once a background process of some kind terminates, | |
526 | * as we want to avoid resizing the hash tables when there is a child in order | |
527 | * to play well with copy-on-write (otherwise when a resize happens lots of | |
528 | * memory pages are copied). The goal of this function is to update the ability | |
529 | * for dict.c to resize the hash tables accordingly to the fact we have o not | |
530 | * running childs. */ | |
531 | void updateDictResizePolicy(void) { | |
532 | if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) | |
533 | dictEnableResize(); | |
534 | else | |
535 | dictDisableResize(); | |
536 | } | |
537 | ||
538 | /* ======================= Cron: called every 100 ms ======================== */ | |
539 | ||
bcf2995c | 540 | /* Try to expire a few timed out keys. The algorithm used is adaptive and |
541 | * will use few CPU cycles if there are few expiring keys, otherwise | |
542 | * it will get more aggressive to avoid that too much memory is used by | |
543 | * keys that can be removed from the keyspace. */ | |
544 | void activeExpireCycle(void) { | |
545 | int j; | |
546 | ||
547 | for (j = 0; j < server.dbnum; j++) { | |
548 | int expired; | |
549 | redisDb *db = server.db+j; | |
550 | ||
551 | /* Continue to expire if at the end of the cycle more than 25% | |
552 | * of the keys were expired. */ | |
553 | do { | |
554 | long num = dictSize(db->expires); | |
555 | time_t now = time(NULL); | |
556 | ||
557 | expired = 0; | |
558 | if (num > REDIS_EXPIRELOOKUPS_PER_CRON) | |
559 | num = REDIS_EXPIRELOOKUPS_PER_CRON; | |
560 | while (num--) { | |
561 | dictEntry *de; | |
562 | time_t t; | |
563 | ||
564 | if ((de = dictGetRandomKey(db->expires)) == NULL) break; | |
565 | t = (time_t) dictGetEntryVal(de); | |
566 | if (now > t) { | |
567 | sds key = dictGetEntryKey(de); | |
568 | robj *keyobj = createStringObject(key,sdslen(key)); | |
569 | ||
570 | propagateExpire(db,keyobj); | |
571 | dbDelete(db,keyobj); | |
572 | decrRefCount(keyobj); | |
573 | expired++; | |
574 | server.stat_expiredkeys++; | |
575 | } | |
576 | } | |
577 | } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4); | |
578 | } | |
579 | } | |
580 | ||
165346ca | 581 | void updateLRUClock(void) { |
582 | server.lruclock = (time(NULL)/REDIS_LRU_CLOCK_RESOLUTION) & | |
583 | REDIS_LRU_CLOCK_MAX; | |
584 | } | |
bcf2995c | 585 | |
e2641e09 | 586 | int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { |
89a1433e | 587 | int j, loops = server.cronloops; |
e2641e09 | 588 | REDIS_NOTUSED(eventLoop); |
589 | REDIS_NOTUSED(id); | |
590 | REDIS_NOTUSED(clientData); | |
591 | ||
592 | /* We take a cached value of the unix time in the global state because | |
593 | * with virtual memory and aging there is to store the current time | |
594 | * in objects at every object access, and accuracy is not needed. | |
595 | * To access a global var is faster than calling time(NULL) */ | |
596 | server.unixtime = time(NULL); | |
4f06867a | 597 | |
ef59a8bc | 598 | /* We have just 22 bits per object for LRU information. |
165346ca | 599 | * So we use an (eventually wrapping) LRU clock with 10 seconds resolution. |
600 | * 2^22 bits with 10 seconds resoluton is more or less 1.5 years. | |
e2641e09 | 601 | * |
165346ca | 602 | * Note that even if this will wrap after 1.5 years it's not a problem, |
ef59a8bc | 603 | * everything will still work but just some object will appear younger |
165346ca | 604 | * to Redis. But for this to happen a given object should never be touched |
605 | * for 1.5 years. | |
606 | * | |
607 | * Note that you can change the resolution altering the | |
608 | * REDIS_LRU_CLOCK_RESOLUTION define. | |
e2641e09 | 609 | */ |
165346ca | 610 | updateLRUClock(); |
e2641e09 | 611 | |
17b24ff3 | 612 | /* Record the max memory used since the server was started. */ |
613 | if (zmalloc_used_memory() > server.stat_peak_memory) | |
614 | server.stat_peak_memory = zmalloc_used_memory(); | |
615 | ||
e2641e09 | 616 | /* We received a SIGTERM, shutting down here in a safe way, as it is |
617 | * not ok doing so inside the signal handler. */ | |
618 | if (server.shutdown_asap) { | |
619 | if (prepareForShutdown() == REDIS_OK) exit(0); | |
620 | redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); | |
621 | } | |
622 | ||
623 | /* Show some info about non-empty databases */ | |
624 | for (j = 0; j < server.dbnum; j++) { | |
625 | long long size, used, vkeys; | |
626 | ||
627 | size = dictSlots(server.db[j].dict); | |
628 | used = dictSize(server.db[j].dict); | |
629 | vkeys = dictSize(server.db[j].expires); | |
630 | if (!(loops % 50) && (used || vkeys)) { | |
631 | redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); | |
632 | /* dictPrintStats(server.dict); */ | |
633 | } | |
634 | } | |
635 | ||
636 | /* We don't want to resize the hash tables while a bacground saving | |
637 | * is in progress: the saving child is created using fork() that is | |
638 | * implemented with a copy-on-write semantic in most modern systems, so | |
639 | * if we resize the HT while there is the saving child at work actually | |
640 | * a lot of memory movements in the parent will cause a lot of pages | |
641 | * copied. */ | |
642 | if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) { | |
643 | if (!(loops % 10)) tryResizeHashTables(); | |
644 | if (server.activerehashing) incrementallyRehash(); | |
645 | } | |
646 | ||
647 | /* Show information about connected clients */ | |
648 | if (!(loops % 50)) { | |
649 | redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use", | |
650 | listLength(server.clients)-listLength(server.slaves), | |
651 | listLength(server.slaves), | |
ca734d17 | 652 | zmalloc_used_memory()); |
e2641e09 | 653 | } |
654 | ||
655 | /* Close connections of timedout clients */ | |
5fa95ad7 | 656 | if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients) |
e2641e09 | 657 | closeTimedoutClients(); |
658 | ||
b333e239 | 659 | /* Start a scheduled AOF rewrite if this was requested by the user while |
660 | * a BGSAVE was in progress. */ | |
661 | if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1 && | |
662 | server.aofrewrite_scheduled) | |
663 | { | |
664 | rewriteAppendOnlyFileBackground(); | |
665 | } | |
666 | ||
f03fe802 | 667 | /* Check if a background saving or AOF rewrite in progress terminated. */ |
e2641e09 | 668 | if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) { |
669 | int statloc; | |
670 | pid_t pid; | |
671 | ||
672 | if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { | |
36c17a53 | 673 | int exitcode = WEXITSTATUS(statloc); |
674 | int bysignal = 0; | |
675 | ||
676 | if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc); | |
677 | ||
e2641e09 | 678 | if (pid == server.bgsavechildpid) { |
36c17a53 | 679 | backgroundSaveDoneHandler(exitcode,bysignal); |
e2641e09 | 680 | } else { |
36c17a53 | 681 | backgroundRewriteDoneHandler(exitcode,bysignal); |
e2641e09 | 682 | } |
683 | updateDictResizePolicy(); | |
684 | } | |
c9d0c362 | 685 | } else { |
e2641e09 | 686 | time_t now = time(NULL); |
b333e239 | 687 | |
688 | /* If there is not a background saving/rewrite in progress check if | |
689 | * we have to save/rewrite now */ | |
e2641e09 | 690 | for (j = 0; j < server.saveparamslen; j++) { |
691 | struct saveparam *sp = server.saveparams+j; | |
692 | ||
693 | if (server.dirty >= sp->changes && | |
694 | now-server.lastsave > sp->seconds) { | |
695 | redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...", | |
696 | sp->changes, sp->seconds); | |
697 | rdbSaveBackground(server.dbfilename); | |
698 | break; | |
699 | } | |
700 | } | |
b333e239 | 701 | |
702 | /* Trigger an AOF rewrite if needed */ | |
19b46c9a | 703 | if (server.bgsavechildpid == -1 && |
704 | server.bgrewritechildpid == -1 && | |
705 | server.auto_aofrewrite_perc && | |
b333e239 | 706 | server.appendonly_current_size > server.auto_aofrewrite_min_size) |
707 | { | |
11aaf523 | 708 | long long base = server.auto_aofrewrite_base_size ? |
e3d27a72 | 709 | server.auto_aofrewrite_base_size : 1; |
0b17517c | 710 | long long growth = (server.appendonly_current_size*100/base) - 100; |
b333e239 | 711 | if (growth >= server.auto_aofrewrite_perc) { |
19b46c9a | 712 | redisLog(REDIS_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth); |
b333e239 | 713 | rewriteAppendOnlyFileBackground(); |
714 | } | |
715 | } | |
e2641e09 | 716 | } |
717 | ||
db3c2a4f | 718 | |
719 | /* If we postponed an AOF buffer flush, let's try to do it every time the | |
720 | * cron function is called. */ | |
721 | if (server.aof_flush_postponed_start) flushAppendOnlyFile(0); | |
722 | ||
bcf2995c | 723 | /* Expire a few keys per cycle, only if this is a master. |
724 | * On slaves we wait for DEL operations synthesized by the master | |
725 | * in order to guarantee a strict consistency. */ | |
726 | if (server.masterhost == NULL) activeExpireCycle(); | |
e2641e09 | 727 | |
f4aa600b | 728 | /* Replication cron function -- used to reconnect to master and |
729 | * to detect transfer failures. */ | |
62ec599c | 730 | if (!(loops % 10)) replicationCron(); |
f4aa600b | 731 | |
ecc91094 | 732 | /* Run other sub-systems specific cron jobs */ |
733 | if (server.cluster_enabled && !(loops % 10)) clusterCron(); | |
734 | ||
89a1433e | 735 | server.cronloops++; |
e2641e09 | 736 | return 100; |
737 | } | |
738 | ||
739 | /* This function gets called every time Redis is entering the | |
740 | * main loop of the event driven library, that is, before to sleep | |
741 | * for ready file descriptors. */ | |
742 | void beforeSleep(struct aeEventLoop *eventLoop) { | |
743 | REDIS_NOTUSED(eventLoop); | |
a4ce7581 PN |
744 | listNode *ln; |
745 | redisClient *c; | |
e2641e09 | 746 | |
a4ce7581 PN |
747 | /* Try to process pending commands for clients that were just unblocked. */ |
748 | while (listLength(server.unblocked_clients)) { | |
749 | ln = listFirst(server.unblocked_clients); | |
750 | redisAssert(ln != NULL); | |
751 | c = ln->value; | |
752 | listDelNode(server.unblocked_clients,ln); | |
3bcffcbe | 753 | c->flags &= ~REDIS_UNBLOCKED; |
a4ce7581 PN |
754 | |
755 | /* Process remaining data in the input buffer. */ | |
756 | if (c->querybuf && sdslen(c->querybuf) > 0) | |
757 | processInputBuffer(c); | |
758 | } | |
759 | ||
e2641e09 | 760 | /* Write the AOF buffer on disk */ |
db3c2a4f | 761 | flushAppendOnlyFile(0); |
e2641e09 | 762 | } |
763 | ||
764 | /* =========================== Server initialization ======================== */ | |
765 | ||
766 | void createSharedObjects(void) { | |
767 | int j; | |
768 | ||
769 | shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n")); | |
770 | shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n")); | |
771 | shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n")); | |
772 | shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n")); | |
773 | shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n")); | |
774 | shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n")); | |
775 | shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n")); | |
776 | shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n")); | |
777 | shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n")); | |
778 | shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n")); | |
779 | shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n")); | |
780 | shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n")); | |
781 | shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew( | |
782 | "-ERR Operation against a key holding the wrong kind of value\r\n")); | |
783 | shared.nokeyerr = createObject(REDIS_STRING,sdsnew( | |
784 | "-ERR no such key\r\n")); | |
785 | shared.syntaxerr = createObject(REDIS_STRING,sdsnew( | |
786 | "-ERR syntax error\r\n")); | |
787 | shared.sameobjecterr = createObject(REDIS_STRING,sdsnew( | |
788 | "-ERR source and destination objects are the same\r\n")); | |
789 | shared.outofrangeerr = createObject(REDIS_STRING,sdsnew( | |
790 | "-ERR index out of range\r\n")); | |
7229d60d | 791 | shared.noscripterr = createObject(REDIS_STRING,sdsnew( |
792 | "-NOSCRIPT No matching script. Please use EVAL.\r\n")); | |
97e7f8ae | 793 | shared.loadingerr = createObject(REDIS_STRING,sdsnew( |
794 | "-LOADING Redis is loading the dataset in memory\r\n")); | |
e2641e09 | 795 | shared.space = createObject(REDIS_STRING,sdsnew(" ")); |
796 | shared.colon = createObject(REDIS_STRING,sdsnew(":")); | |
797 | shared.plus = createObject(REDIS_STRING,sdsnew("+")); | |
798 | shared.select0 = createStringObject("select 0\r\n",10); | |
799 | shared.select1 = createStringObject("select 1\r\n",10); | |
800 | shared.select2 = createStringObject("select 2\r\n",10); | |
801 | shared.select3 = createStringObject("select 3\r\n",10); | |
802 | shared.select4 = createStringObject("select 4\r\n",10); | |
803 | shared.select5 = createStringObject("select 5\r\n",10); | |
804 | shared.select6 = createStringObject("select 6\r\n",10); | |
805 | shared.select7 = createStringObject("select 7\r\n",10); | |
806 | shared.select8 = createStringObject("select 8\r\n",10); | |
807 | shared.select9 = createStringObject("select 9\r\n",10); | |
808 | shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); | |
809 | shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); | |
810 | shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); | |
811 | shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); | |
812 | shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); | |
813 | shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); | |
814 | shared.mbulk3 = createStringObject("*3\r\n",4); | |
815 | shared.mbulk4 = createStringObject("*4\r\n",4); | |
816 | for (j = 0; j < REDIS_SHARED_INTEGERS; j++) { | |
817 | shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j); | |
818 | shared.integers[j]->encoding = REDIS_ENCODING_INT; | |
819 | } | |
820 | } | |
821 | ||
822 | void initServerConfig() { | |
e2641e09 | 823 | server.port = REDIS_SERVERPORT; |
a5639e7d | 824 | server.bindaddr = NULL; |
5d10923f | 825 | server.unixsocket = NULL; |
85238765 | 826 | server.unixsocketperm = 0; |
a5639e7d PN |
827 | server.ipfd = -1; |
828 | server.sofd = -1; | |
829 | server.dbnum = REDIS_DEFAULT_DBNUM; | |
e2641e09 | 830 | server.verbosity = REDIS_VERBOSE; |
831 | server.maxidletime = REDIS_MAXIDLETIME; | |
832 | server.saveparams = NULL; | |
97e7f8ae | 833 | server.loading = 0; |
e2641e09 | 834 | server.logfile = NULL; /* NULL = log on standard output */ |
e1a586ee JH |
835 | server.syslog_enabled = 0; |
836 | server.syslog_ident = zstrdup("redis"); | |
837 | server.syslog_facility = LOG_LOCAL0; | |
e2641e09 | 838 | server.daemonize = 0; |
839 | server.appendonly = 0; | |
840 | server.appendfsync = APPENDFSYNC_EVERYSEC; | |
841 | server.no_appendfsync_on_rewrite = 0; | |
b333e239 | 842 | server.auto_aofrewrite_perc = REDIS_AUTO_AOFREWRITE_PERC; |
843 | server.auto_aofrewrite_min_size = REDIS_AUTO_AOFREWRITE_MIN_SIZE; | |
844 | server.auto_aofrewrite_base_size = 0; | |
845 | server.aofrewrite_scheduled = 0; | |
e2641e09 | 846 | server.lastfsync = time(NULL); |
847 | server.appendfd = -1; | |
848 | server.appendseldb = -1; /* Make sure the first time will not match */ | |
db3c2a4f | 849 | server.aof_flush_postponed_start = 0; |
e2641e09 | 850 | server.pidfile = zstrdup("/var/run/redis.pid"); |
851 | server.dbfilename = zstrdup("dump.rdb"); | |
852 | server.appendfilename = zstrdup("appendonly.aof"); | |
853 | server.requirepass = NULL; | |
854 | server.rdbcompression = 1; | |
855 | server.activerehashing = 1; | |
856 | server.maxclients = 0; | |
5fa95ad7 | 857 | server.bpop_blocked_clients = 0; |
e2641e09 | 858 | server.maxmemory = 0; |
165346ca | 859 | server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU; |
860 | server.maxmemory_samples = 3; | |
e2641e09 | 861 | server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES; |
862 | server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE; | |
863 | server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES; | |
864 | server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE; | |
96ffb2fe | 865 | server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES; |
3ea204e1 PN |
866 | server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES; |
867 | server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE; | |
e2641e09 | 868 | server.shutdown_asap = 0; |
ecc91094 | 869 | server.cluster_enabled = 0; |
ef21ab96 | 870 | server.cluster.configfile = zstrdup("nodes.conf"); |
eeffcf38 | 871 | server.lua_time_limit = REDIS_LUA_TIME_LIMIT; |
e2641e09 | 872 | |
95506e46 | 873 | updateLRUClock(); |
e2641e09 | 874 | resetServerSaveParams(); |
875 | ||
876 | appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ | |
877 | appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ | |
878 | appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ | |
879 | /* Replication related */ | |
880 | server.isslave = 0; | |
881 | server.masterauth = NULL; | |
882 | server.masterhost = NULL; | |
883 | server.masterport = 6379; | |
884 | server.master = NULL; | |
885 | server.replstate = REDIS_REPL_NONE; | |
890a2ed9 | 886 | server.repl_syncio_timeout = REDIS_REPL_SYNCIO_TIMEOUT; |
4ebfc455 | 887 | server.repl_serve_stale_data = 1; |
07486df6 | 888 | server.repl_down_since = -1; |
e2641e09 | 889 | |
890 | /* Double constants initialization */ | |
891 | R_Zero = 0.0; | |
892 | R_PosInf = 1.0/R_Zero; | |
893 | R_NegInf = -1.0/R_Zero; | |
894 | R_Nan = R_Zero/R_Zero; | |
8d3e063a | 895 | |
896 | /* Command table -- we intiialize it here as it is part of the | |
897 | * initial configuration, since command names may be changed via | |
898 | * redis.conf using the rename-command directive. */ | |
899 | server.commands = dictCreate(&commandTableDictType,NULL); | |
900 | populateCommandTable(); | |
901 | server.delCommand = lookupCommandByCString("del"); | |
902 | server.multiCommand = lookupCommandByCString("multi"); | |
daa70b17 | 903 | |
904 | /* Slow log */ | |
905 | server.slowlog_log_slower_than = REDIS_SLOWLOG_LOG_SLOWER_THAN; | |
906 | server.slowlog_max_len = REDIS_SLOWLOG_MAX_LEN; | |
e2641e09 | 907 | } |
908 | ||
909 | void initServer() { | |
910 | int j; | |
911 | ||
912 | signal(SIGHUP, SIG_IGN); | |
913 | signal(SIGPIPE, SIG_IGN); | |
633a9410 | 914 | setupSignalHandlers(); |
e2641e09 | 915 | |
e1a586ee JH |
916 | if (server.syslog_enabled) { |
917 | openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, | |
918 | server.syslog_facility); | |
919 | } | |
920 | ||
e2641e09 | 921 | server.clients = listCreate(); |
922 | server.slaves = listCreate(); | |
923 | server.monitors = listCreate(); | |
a4ce7581 | 924 | server.unblocked_clients = listCreate(); |
cea8c5cd | 925 | |
e2641e09 | 926 | createSharedObjects(); |
927 | server.el = aeCreateEventLoop(); | |
928 | server.db = zmalloc(sizeof(redisDb)*server.dbnum); | |
68d6345d | 929 | |
a53b4c24 | 930 | if (server.port != 0) { |
68d6345d | 931 | server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr); |
a53b4c24 | 932 | if (server.ipfd == ANET_ERR) { |
eef17490 | 933 | redisLog(REDIS_WARNING, "Opening port %d: %s", |
934 | server.port, server.neterr); | |
a53b4c24 | 935 | exit(1); |
936 | } | |
a5639e7d | 937 | } |
5d10923f PN |
938 | if (server.unixsocket != NULL) { |
939 | unlink(server.unixsocket); /* don't care if this fails */ | |
85238765 | 940 | server.sofd = anetUnixServer(server.neterr,server.unixsocket,server.unixsocketperm); |
a5639e7d PN |
941 | if (server.sofd == ANET_ERR) { |
942 | redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr); | |
943 | exit(1); | |
944 | } | |
c61e6925 | 945 | } |
a5639e7d PN |
946 | if (server.ipfd < 0 && server.sofd < 0) { |
947 | redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting."); | |
e2641e09 | 948 | exit(1); |
949 | } | |
950 | for (j = 0; j < server.dbnum; j++) { | |
951 | server.db[j].dict = dictCreate(&dbDictType,NULL); | |
952 | server.db[j].expires = dictCreate(&keyptrDictType,NULL); | |
953 | server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); | |
954 | server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); | |
e2641e09 | 955 | server.db[j].id = j; |
956 | } | |
957 | server.pubsub_channels = dictCreate(&keylistDictType,NULL); | |
958 | server.pubsub_patterns = listCreate(); | |
959 | listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); | |
960 | listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); | |
961 | server.cronloops = 0; | |
962 | server.bgsavechildpid = -1; | |
963 | server.bgrewritechildpid = -1; | |
964 | server.bgrewritebuf = sdsempty(); | |
965 | server.aofbuf = sdsempty(); | |
966 | server.lastsave = time(NULL); | |
967 | server.dirty = 0; | |
968 | server.stat_numcommands = 0; | |
969 | server.stat_numconnections = 0; | |
970 | server.stat_expiredkeys = 0; | |
f21779ff | 971 | server.stat_evictedkeys = 0; |
e2641e09 | 972 | server.stat_starttime = time(NULL); |
53eeeaff | 973 | server.stat_keyspace_misses = 0; |
974 | server.stat_keyspace_hits = 0; | |
17b24ff3 | 975 | server.stat_peak_memory = 0; |
615e414c | 976 | server.stat_fork_time = 0; |
e2641e09 | 977 | server.unixtime = time(NULL); |
978 | aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL); | |
a5639e7d | 979 | if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE, |
ab17b909 | 980 | acceptTcpHandler,NULL) == AE_ERR) oom("creating file event"); |
a5639e7d | 981 | if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE, |
ab17b909 | 982 | acceptUnixHandler,NULL) == AE_ERR) oom("creating file event"); |
e2641e09 | 983 | |
984 | if (server.appendonly) { | |
985 | server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644); | |
986 | if (server.appendfd == -1) { | |
987 | redisLog(REDIS_WARNING, "Can't open the append-only file: %s", | |
988 | strerror(errno)); | |
989 | exit(1); | |
990 | } | |
991 | } | |
992 | ||
ecc91094 | 993 | if (server.cluster_enabled) clusterInit(); |
7585836e | 994 | scriptingInit(); |
daa70b17 | 995 | slowlogInit(); |
8f61a72f | 996 | bioInit(); |
29920dce | 997 | srand(time(NULL)^getpid()); |
e2641e09 | 998 | } |
999 | ||
1b1f47c9 | 1000 | /* Populates the Redis Command Table starting from the hard coded list |
1001 | * we have on top of redis.c file. */ | |
1002 | void populateCommandTable(void) { | |
1003 | int j; | |
d7ed7fd2 | 1004 | int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); |
1b1f47c9 | 1005 | |
1006 | for (j = 0; j < numcommands; j++) { | |
d7ed7fd2 | 1007 | struct redisCommand *c = redisCommandTable+j; |
5d02b00f | 1008 | char *f = c->sflags; |
1b1f47c9 | 1009 | int retval; |
e2641e09 | 1010 | |
5d02b00f | 1011 | while(*f != '\0') { |
1012 | switch(*f) { | |
1013 | case 'w': c->flags |= REDIS_CMD_WRITE; break; | |
1014 | case 'r': c->flags |= REDIS_CMD_READONLY; break; | |
1015 | case 'm': c->flags |= REDIS_CMD_DENYOOM; break; | |
1016 | case 'a': c->flags |= REDIS_CMD_ADMIN; break; | |
1017 | case 'p': c->flags |= REDIS_CMD_PUBSUB; break; | |
1018 | case 'f': c->flags |= REDIS_CMD_FORCE_REPLICATION; break; | |
b60ed6e8 | 1019 | case 's': c->flags |= REDIS_CMD_NOSCRIPT; break; |
1020 | case 'R': c->flags |= REDIS_CMD_RANDOM; break; | |
5d02b00f | 1021 | default: redisPanic("Unsupported command flag"); break; |
1022 | } | |
1023 | f++; | |
1024 | } | |
1025 | ||
1b1f47c9 | 1026 | retval = dictAdd(server.commands, sdsnew(c->name), c); |
1027 | assert(retval == DICT_OK); | |
1028 | } | |
e2641e09 | 1029 | } |
1030 | ||
d7ed7fd2 | 1031 | void resetCommandTableStats(void) { |
1032 | int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); | |
1033 | int j; | |
1034 | ||
1035 | for (j = 0; j < numcommands; j++) { | |
1036 | struct redisCommand *c = redisCommandTable+j; | |
1037 | ||
1038 | c->microseconds = 0; | |
1039 | c->calls = 0; | |
1040 | } | |
1041 | } | |
1042 | ||
e2641e09 | 1043 | /* ====================== Commands lookup and execution ===================== */ |
1044 | ||
1b1f47c9 | 1045 | struct redisCommand *lookupCommand(sds name) { |
1046 | return dictFetchValue(server.commands, name); | |
1047 | } | |
1048 | ||
1049 | struct redisCommand *lookupCommandByCString(char *s) { | |
1050 | struct redisCommand *cmd; | |
1051 | sds name = sdsnew(s); | |
1052 | ||
1053 | cmd = dictFetchValue(server.commands, name); | |
1054 | sdsfree(name); | |
1055 | return cmd; | |
e2641e09 | 1056 | } |
1057 | ||
1058 | /* Call() is the core of Redis execution of a command */ | |
09e2d9ee | 1059 | void call(redisClient *c) { |
daa70b17 | 1060 | long long dirty, start = ustime(), duration; |
e2641e09 | 1061 | |
1062 | dirty = server.dirty; | |
09e2d9ee | 1063 | c->cmd->proc(c); |
e2641e09 | 1064 | dirty = server.dirty-dirty; |
daa70b17 | 1065 | duration = ustime()-start; |
09e2d9ee | 1066 | c->cmd->microseconds += duration; |
daa70b17 | 1067 | slowlogPushEntryIfNeeded(c->argv,c->argc,duration); |
09e2d9ee | 1068 | c->cmd->calls++; |
e2641e09 | 1069 | |
6468a6fa | 1070 | if (server.appendonly && dirty > 0) |
09e2d9ee | 1071 | feedAppendOnlyFile(c->cmd,c->db->id,c->argv,c->argc); |
6468a6fa | 1072 | if ((dirty > 0 || c->cmd->flags & REDIS_CMD_FORCE_REPLICATION) && |
e2641e09 | 1073 | listLength(server.slaves)) |
1074 | replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc); | |
1075 | if (listLength(server.monitors)) | |
1076 | replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc); | |
1077 | server.stat_numcommands++; | |
1078 | } | |
1079 | ||
1080 | /* If this function gets called we already read a whole | |
1081 | * command, argments are in the client argv/argc fields. | |
1082 | * processCommand() execute the command or prepare the | |
1083 | * server for a bulk read from the client. | |
1084 | * | |
1085 | * If 1 is returned the client is still alive and valid and | |
1086 | * and other operations can be performed by the caller. Otherwise | |
1087 | * if 0 is returned the client was destroied (i.e. after QUIT). */ | |
1088 | int processCommand(redisClient *c) { | |
941c9fa2 PN |
1089 | /* The QUIT command is handled separately. Normal command procs will |
1090 | * go through checking for replication and QUIT will cause trouble | |
1091 | * when FORCE_REPLICATION is enabled and would be implemented in | |
1092 | * a regular command proc. */ | |
e2641e09 | 1093 | if (!strcasecmp(c->argv[0]->ptr,"quit")) { |
941c9fa2 | 1094 | addReply(c,shared.ok); |
5e78edb3 | 1095 | c->flags |= REDIS_CLOSE_AFTER_REPLY; |
cd8788f2 | 1096 | return REDIS_ERR; |
e2641e09 | 1097 | } |
1098 | ||
1099 | /* Now lookup the command and check ASAP about trivial error conditions | |
09e2d9ee | 1100 | * such as wrong arity, bad command name and so forth. */ |
1101 | c->cmd = lookupCommand(c->argv[0]->ptr); | |
1102 | if (!c->cmd) { | |
3ab20376 PN |
1103 | addReplyErrorFormat(c,"unknown command '%s'", |
1104 | (char*)c->argv[0]->ptr); | |
cd8788f2 | 1105 | return REDIS_OK; |
09e2d9ee | 1106 | } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) || |
1107 | (c->argc < -c->cmd->arity)) { | |
3ab20376 | 1108 | addReplyErrorFormat(c,"wrong number of arguments for '%s' command", |
09e2d9ee | 1109 | c->cmd->name); |
cd8788f2 | 1110 | return REDIS_OK; |
e2641e09 | 1111 | } |
e2641e09 | 1112 | |
1113 | /* Check if the user is authenticated */ | |
09e2d9ee | 1114 | if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand) |
1115 | { | |
3ab20376 | 1116 | addReplyError(c,"operation not permitted"); |
cd8788f2 | 1117 | return REDIS_OK; |
e2641e09 | 1118 | } |
1119 | ||
ecc91094 | 1120 | /* If cluster is enabled, redirect here */ |
1121 | if (server.cluster_enabled && | |
09e2d9ee | 1122 | !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0)) { |
ecc91094 | 1123 | int hashslot; |
1124 | ||
1125 | if (server.cluster.state != REDIS_CLUSTER_OK) { | |
1126 | addReplyError(c,"The cluster is down. Check with CLUSTER INFO for more information"); | |
1127 | return REDIS_OK; | |
1128 | } else { | |
eda827f8 | 1129 | int ask; |
09e2d9ee | 1130 | clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,&hashslot,&ask); |
ecc91094 | 1131 | if (n == NULL) { |
eda827f8 | 1132 | addReplyError(c,"Multi keys request invalid in cluster"); |
ecc91094 | 1133 | return REDIS_OK; |
1134 | } else if (n != server.cluster.myself) { | |
1135 | addReplySds(c,sdscatprintf(sdsempty(), | |
eda827f8 | 1136 | "-%s %d %s:%d\r\n", ask ? "ASK" : "MOVED", |
1137 | hashslot,n->ip,n->port)); | |
ecc91094 | 1138 | return REDIS_OK; |
1139 | } | |
1140 | } | |
1141 | } | |
1142 | ||
1dd10ca2 | 1143 | /* Handle the maxmemory directive. |
1144 | * | |
1145 | * First we try to free some memory if possible (if there are volatile | |
1146 | * keys in the dataset). If there are not the only thing we can do | |
1147 | * is returning an error. */ | |
1148 | if (server.maxmemory) freeMemoryIfNeeded(); | |
09e2d9ee | 1149 | if (server.maxmemory && (c->cmd->flags & REDIS_CMD_DENYOOM) && |
ca734d17 | 1150 | zmalloc_used_memory() > server.maxmemory) |
e2641e09 | 1151 | { |
3ab20376 | 1152 | addReplyError(c,"command not allowed when used memory > 'maxmemory'"); |
cd8788f2 | 1153 | return REDIS_OK; |
e2641e09 | 1154 | } |
1155 | ||
1156 | /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ | |
1157 | if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0) | |
1158 | && | |
09e2d9ee | 1159 | c->cmd->proc != subscribeCommand && |
1160 | c->cmd->proc != unsubscribeCommand && | |
1161 | c->cmd->proc != psubscribeCommand && | |
1162 | c->cmd->proc != punsubscribeCommand) { | |
3ab20376 | 1163 | addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context"); |
cd8788f2 | 1164 | return REDIS_OK; |
e2641e09 | 1165 | } |
1166 | ||
4ebfc455 | 1167 | /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and |
1168 | * we are a slave with a broken link with master. */ | |
1169 | if (server.masterhost && server.replstate != REDIS_REPL_CONNECTED && | |
1170 | server.repl_serve_stale_data == 0 && | |
09e2d9ee | 1171 | c->cmd->proc != infoCommand && c->cmd->proc != slaveofCommand) |
4ebfc455 | 1172 | { |
1173 | addReplyError(c, | |
1174 | "link with MASTER is down and slave-serve-stale-data is set to no"); | |
1175 | return REDIS_OK; | |
1176 | } | |
1177 | ||
97e7f8ae | 1178 | /* Loading DB? Return an error if the command is not INFO */ |
09e2d9ee | 1179 | if (server.loading && c->cmd->proc != infoCommand) { |
97e7f8ae | 1180 | addReply(c, shared.loadingerr); |
1181 | return REDIS_OK; | |
1182 | } | |
1183 | ||
e2641e09 | 1184 | /* Exec the command */ |
1185 | if (c->flags & REDIS_MULTI && | |
09e2d9ee | 1186 | c->cmd->proc != execCommand && c->cmd->proc != discardCommand && |
1187 | c->cmd->proc != multiCommand && c->cmd->proc != watchCommand) | |
e2641e09 | 1188 | { |
09e2d9ee | 1189 | queueMultiCommand(c); |
e2641e09 | 1190 | addReply(c,shared.queued); |
1191 | } else { | |
09e2d9ee | 1192 | call(c); |
e2641e09 | 1193 | } |
cd8788f2 | 1194 | return REDIS_OK; |
e2641e09 | 1195 | } |
1196 | ||
1197 | /*================================== Shutdown =============================== */ | |
1198 | ||
1199 | int prepareForShutdown() { | |
adae85cd | 1200 | redisLog(REDIS_WARNING,"User requested shutdown..."); |
e2641e09 | 1201 | /* Kill the saving child if there is a background saving in progress. |
1202 | We want to avoid race conditions, for instance our saving child may | |
1203 | overwrite the synchronous saving did by SHUTDOWN. */ | |
1204 | if (server.bgsavechildpid != -1) { | |
adae85cd | 1205 | redisLog(REDIS_WARNING,"There is a child saving an .rdb. Killing it!"); |
e2641e09 | 1206 | kill(server.bgsavechildpid,SIGKILL); |
1207 | rdbRemoveTempFile(server.bgsavechildpid); | |
1208 | } | |
c9d0c362 | 1209 | if (server.appendonly) { |
adae85cd | 1210 | /* Kill the AOF saving child as the AOF we already have may be longer |
1211 | * but contains the full dataset anyway. */ | |
1212 | if (server.bgrewritechildpid != -1) { | |
1213 | redisLog(REDIS_WARNING, | |
1214 | "There is a child rewriting the AOF. Killing it!"); | |
1215 | kill(server.bgrewritechildpid,SIGKILL); | |
1216 | } | |
e2641e09 | 1217 | /* Append only file: fsync() the AOF and exit */ |
adae85cd | 1218 | redisLog(REDIS_NOTICE,"Calling fsync() on the AOF file."); |
e2641e09 | 1219 | aof_fsync(server.appendfd); |
adae85cd | 1220 | } |
1221 | if (server.saveparamslen > 0) { | |
1222 | redisLog(REDIS_NOTICE,"Saving the final RDB snapshot before exiting."); | |
e2641e09 | 1223 | /* Snapshotting. Perform a SYNC SAVE and exit */ |
695fe874 | 1224 | if (rdbSave(server.dbfilename) != REDIS_OK) { |
e2641e09 | 1225 | /* Ooops.. error saving! The best we can do is to continue |
1226 | * operating. Note that if there was a background saving process, | |
1227 | * in the next cron() Redis will be notified that the background | |
1228 | * saving aborted, handling special stuff like slaves pending for | |
1229 | * synchronization... */ | |
adae85cd | 1230 | redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit."); |
e2641e09 | 1231 | return REDIS_ERR; |
1232 | } | |
1233 | } | |
adae85cd | 1234 | if (server.daemonize) { |
1235 | redisLog(REDIS_NOTICE,"Removing the pid file."); | |
1236 | unlink(server.pidfile); | |
1237 | } | |
80e87a46 | 1238 | /* Close the listening sockets. Apparently this allows faster restarts. */ |
1239 | if (server.ipfd != -1) close(server.ipfd); | |
1240 | if (server.sofd != -1) close(server.sofd); | |
56209f72 NF |
1241 | if (server.unixsocket) { |
1242 | redisLog(REDIS_NOTICE,"Removing the unix socket file."); | |
1243 | unlink(server.unixsocket); /* don't care if this fails */ | |
1244 | } | |
80e87a46 | 1245 | |
adae85cd | 1246 | redisLog(REDIS_WARNING,"Redis is now ready to exit, bye bye..."); |
e2641e09 | 1247 | return REDIS_OK; |
1248 | } | |
1249 | ||
1250 | /*================================== Commands =============================== */ | |
1251 | ||
1252 | void authCommand(redisClient *c) { | |
ab52d1f4 | 1253 | if (!server.requirepass) { |
1254 | addReplyError(c,"Client sent AUTH, but no password is set"); | |
1255 | } else if (!strcmp(c->argv[1]->ptr, server.requirepass)) { | |
e2641e09 | 1256 | c->authenticated = 1; |
1257 | addReply(c,shared.ok); | |
1258 | } else { | |
1259 | c->authenticated = 0; | |
3ab20376 | 1260 | addReplyError(c,"invalid password"); |
e2641e09 | 1261 | } |
1262 | } | |
1263 | ||
1264 | void pingCommand(redisClient *c) { | |
1265 | addReply(c,shared.pong); | |
1266 | } | |
1267 | ||
1268 | void echoCommand(redisClient *c) { | |
1269 | addReplyBulk(c,c->argv[1]); | |
1270 | } | |
1271 | ||
1272 | /* Convert an amount of bytes into a human readable string in the form | |
1273 | * of 100B, 2G, 100M, 4K, and so forth. */ | |
1274 | void bytesToHuman(char *s, unsigned long long n) { | |
1275 | double d; | |
1276 | ||
1277 | if (n < 1024) { | |
1278 | /* Bytes */ | |
1279 | sprintf(s,"%lluB",n); | |
1280 | return; | |
1281 | } else if (n < (1024*1024)) { | |
1282 | d = (double)n/(1024); | |
1283 | sprintf(s,"%.2fK",d); | |
1284 | } else if (n < (1024LL*1024*1024)) { | |
1285 | d = (double)n/(1024*1024); | |
1286 | sprintf(s,"%.2fM",d); | |
1287 | } else if (n < (1024LL*1024*1024*1024)) { | |
1288 | d = (double)n/(1024LL*1024*1024); | |
1289 | sprintf(s,"%.2fG",d); | |
1290 | } | |
1291 | } | |
1292 | ||
1293 | /* Create the string returned by the INFO command. This is decoupled | |
1294 | * by the INFO command itself as we need to report the same information | |
1295 | * on memory corruption problems. */ | |
1b085c9f | 1296 | sds genRedisInfoString(char *section) { |
1297 | sds info = sdsempty(); | |
e2641e09 | 1298 | time_t uptime = time(NULL)-server.stat_starttime; |
d9cb288c | 1299 | int j, numcommands; |
2b00385d | 1300 | struct rusage self_ru, c_ru; |
7a1fd61e | 1301 | unsigned long lol, bib; |
1b085c9f | 1302 | int allsections = 0, defsections = 0; |
1303 | int sections = 0; | |
1304 | ||
1305 | if (section) { | |
1306 | allsections = strcasecmp(section,"all") == 0; | |
0d808ef2 | 1307 | defsections = strcasecmp(section,"default") == 0; |
1b085c9f | 1308 | } |
2b00385d | 1309 | |
1310 | getrusage(RUSAGE_SELF, &self_ru); | |
1311 | getrusage(RUSAGE_CHILDREN, &c_ru); | |
7a1fd61e | 1312 | getClientsMaxBuffers(&lol,&bib); |
1b085c9f | 1313 | |
1314 | /* Server */ | |
1315 | if (allsections || defsections || !strcasecmp(section,"server")) { | |
1316 | if (sections++) info = sdscat(info,"\r\n"); | |
e2641e09 | 1317 | info = sdscatprintf(info, |
1b085c9f | 1318 | "# Server\r\n" |
1319 | "redis_version:%s\r\n" | |
1320 | "redis_git_sha1:%s\r\n" | |
1321 | "redis_git_dirty:%d\r\n" | |
1322 | "arch_bits:%s\r\n" | |
1323 | "multiplexing_api:%s\r\n" | |
1324 | "process_id:%ld\r\n" | |
1325 | "tcp_port:%d\r\n" | |
1326 | "uptime_in_seconds:%ld\r\n" | |
1327 | "uptime_in_days:%ld\r\n" | |
1328 | "lru_clock:%ld\r\n", | |
1329 | REDIS_VERSION, | |
1330 | redisGitSHA1(), | |
1331 | strtol(redisGitDirty(),NULL,10) > 0, | |
1332 | (sizeof(long) == 8) ? "64" : "32", | |
1333 | aeGetApiName(), | |
1334 | (long) getpid(), | |
1335 | server.port, | |
1336 | uptime, | |
1337 | uptime/(3600*24), | |
1338 | (unsigned long) server.lruclock); | |
1339 | } | |
1340 | ||
1341 | /* Clients */ | |
1342 | if (allsections || defsections || !strcasecmp(section,"clients")) { | |
1343 | if (sections++) info = sdscat(info,"\r\n"); | |
1344 | info = sdscatprintf(info, | |
1345 | "# Clients\r\n" | |
1346 | "connected_clients:%d\r\n" | |
1347 | "client_longest_output_list:%lu\r\n" | |
1348 | "client_biggest_input_buf:%lu\r\n" | |
1349 | "blocked_clients:%d\r\n", | |
1350 | listLength(server.clients)-listLength(server.slaves), | |
1351 | lol, bib, | |
1352 | server.bpop_blocked_clients); | |
1353 | } | |
1354 | ||
1355 | /* Memory */ | |
1356 | if (allsections || defsections || !strcasecmp(section,"memory")) { | |
17b24ff3 | 1357 | char hmem[64]; |
1358 | char peak_hmem[64]; | |
1359 | ||
1360 | bytesToHuman(hmem,zmalloc_used_memory()); | |
1361 | bytesToHuman(peak_hmem,server.stat_peak_memory); | |
1b085c9f | 1362 | if (sections++) info = sdscat(info,"\r\n"); |
1363 | info = sdscatprintf(info, | |
1364 | "# Memory\r\n" | |
1365 | "used_memory:%zu\r\n" | |
1366 | "used_memory_human:%s\r\n" | |
1367 | "used_memory_rss:%zu\r\n" | |
17b24ff3 | 1368 | "used_memory_peak:%zu\r\n" |
1369 | "used_memory_peak_human:%s\r\n" | |
8c3402df | 1370 | "used_memory_lua:%lld\r\n" |
1b085c9f | 1371 | "mem_fragmentation_ratio:%.2f\r\n" |
32f99c51 | 1372 | "mem_allocator:%s\r\n", |
1b085c9f | 1373 | zmalloc_used_memory(), |
1374 | hmem, | |
1375 | zmalloc_get_rss(), | |
17b24ff3 | 1376 | server.stat_peak_memory, |
1377 | peak_hmem, | |
8c3402df | 1378 | ((long long)lua_gc(server.lua,LUA_GCCOUNT,0))*1024LL, |
1b085c9f | 1379 | zmalloc_get_fragmentation_ratio(), |
fec5a664 | 1380 | ZMALLOC_LIB |
12ebe2ac | 1381 | ); |
0d808ef2 | 1382 | } |
1383 | ||
1b085c9f | 1384 | /* Persistence */ |
1385 | if (allsections || defsections || !strcasecmp(section,"persistence")) { | |
1386 | if (sections++) info = sdscat(info,"\r\n"); | |
e2641e09 | 1387 | info = sdscatprintf(info, |
1b085c9f | 1388 | "# Persistence\r\n" |
1389 | "loading:%d\r\n" | |
1390 | "aof_enabled:%d\r\n" | |
1391 | "changes_since_last_save:%lld\r\n" | |
1392 | "bgsave_in_progress:%d\r\n" | |
1393 | "last_save_time:%ld\r\n" | |
1394 | "bgrewriteaof_in_progress:%d\r\n", | |
1395 | server.loading, | |
1396 | server.appendonly, | |
1397 | server.dirty, | |
c9d0c362 | 1398 | server.bgsavechildpid != -1, |
1b085c9f | 1399 | server.lastsave, |
1400 | server.bgrewritechildpid != -1); | |
1401 | ||
d630abcd | 1402 | if (server.appendonly) { |
1403 | info = sdscatprintf(info, | |
1404 | "aof_current_size:%lld\r\n" | |
1405 | "aof_base_size:%lld\r\n" | |
1406 | "aof_pending_rewrite:%d\r\n", | |
1407 | (long long) server.appendonly_current_size, | |
1408 | (long long) server.auto_aofrewrite_base_size, | |
1409 | server.aofrewrite_scheduled); | |
1410 | } | |
1411 | ||
1b085c9f | 1412 | if (server.loading) { |
1413 | double perc; | |
1414 | time_t eta, elapsed; | |
1415 | off_t remaining_bytes = server.loading_total_bytes- | |
1416 | server.loading_loaded_bytes; | |
1417 | ||
1418 | perc = ((double)server.loading_loaded_bytes / | |
1419 | server.loading_total_bytes) * 100; | |
1420 | ||
1421 | elapsed = time(NULL)-server.loading_start_time; | |
1422 | if (elapsed == 0) { | |
1423 | eta = 1; /* A fake 1 second figure if we don't have | |
1424 | enough info */ | |
1425 | } else { | |
1426 | eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes; | |
1427 | } | |
1428 | ||
1429 | info = sdscatprintf(info, | |
1430 | "loading_start_time:%ld\r\n" | |
1431 | "loading_total_bytes:%llu\r\n" | |
1432 | "loading_loaded_bytes:%llu\r\n" | |
1433 | "loading_loaded_perc:%.2f\r\n" | |
1434 | "loading_eta_seconds:%ld\r\n" | |
1435 | ,(unsigned long) server.loading_start_time, | |
1436 | (unsigned long long) server.loading_total_bytes, | |
1437 | (unsigned long long) server.loading_loaded_bytes, | |
1438 | perc, | |
1439 | eta | |
1440 | ); | |
1441 | } | |
e2641e09 | 1442 | } |
1b085c9f | 1443 | |
1b085c9f | 1444 | /* Stats */ |
1445 | if (allsections || defsections || !strcasecmp(section,"stats")) { | |
1446 | if (sections++) info = sdscat(info,"\r\n"); | |
97e7f8ae | 1447 | info = sdscatprintf(info, |
1b085c9f | 1448 | "# Stats\r\n" |
1449 | "total_connections_received:%lld\r\n" | |
1450 | "total_commands_processed:%lld\r\n" | |
1451 | "expired_keys:%lld\r\n" | |
1452 | "evicted_keys:%lld\r\n" | |
1453 | "keyspace_hits:%lld\r\n" | |
1454 | "keyspace_misses:%lld\r\n" | |
1455 | "pubsub_channels:%ld\r\n" | |
615e414c | 1456 | "pubsub_patterns:%u\r\n" |
1457 | "latest_fork_usec:%lld\r\n", | |
1b085c9f | 1458 | server.stat_numconnections, |
1459 | server.stat_numcommands, | |
1460 | server.stat_expiredkeys, | |
1461 | server.stat_evictedkeys, | |
1462 | server.stat_keyspace_hits, | |
1463 | server.stat_keyspace_misses, | |
1464 | dictSize(server.pubsub_channels), | |
615e414c | 1465 | listLength(server.pubsub_patterns), |
1466 | server.stat_fork_time); | |
97e7f8ae | 1467 | } |
67a1810b | 1468 | |
1b085c9f | 1469 | /* Replication */ |
1470 | if (allsections || defsections || !strcasecmp(section,"replication")) { | |
1471 | if (sections++) info = sdscat(info,"\r\n"); | |
1472 | info = sdscatprintf(info, | |
1473 | "# Replication\r\n" | |
1474 | "role:%s\r\n", | |
1475 | server.masterhost == NULL ? "master" : "slave"); | |
1476 | if (server.masterhost) { | |
1477 | info = sdscatprintf(info, | |
1478 | "master_host:%s\r\n" | |
1479 | "master_port:%d\r\n" | |
1480 | "master_link_status:%s\r\n" | |
1481 | "master_last_io_seconds_ago:%d\r\n" | |
1482 | "master_sync_in_progress:%d\r\n" | |
1483 | ,server.masterhost, | |
1484 | server.masterport, | |
1485 | (server.replstate == REDIS_REPL_CONNECTED) ? | |
1486 | "up" : "down", | |
1487 | server.master ? | |
1488 | ((int)(time(NULL)-server.master->lastinteraction)) : -1, | |
1489 | server.replstate == REDIS_REPL_TRANSFER | |
1490 | ); | |
1491 | ||
1492 | if (server.replstate == REDIS_REPL_TRANSFER) { | |
1493 | info = sdscatprintf(info, | |
1494 | "master_sync_left_bytes:%ld\r\n" | |
1495 | "master_sync_last_io_seconds_ago:%d\r\n" | |
1496 | ,(long)server.repl_transfer_left, | |
1497 | (int)(time(NULL)-server.repl_transfer_lastio) | |
1498 | ); | |
1499 | } | |
07486df6 | 1500 | |
1501 | if (server.replstate != REDIS_REPL_CONNECTED) { | |
1502 | info = sdscatprintf(info, | |
1503 | "master_link_down_since_seconds:%ld\r\n", | |
1504 | (long)time(NULL)-server.repl_down_since); | |
1505 | } | |
67a1810b | 1506 | } |
1b085c9f | 1507 | info = sdscatprintf(info, |
1508 | "connected_slaves:%d\r\n", | |
1509 | listLength(server.slaves)); | |
67a1810b | 1510 | } |
67a1810b | 1511 | |
0d808ef2 | 1512 | /* CPU */ |
1513 | if (allsections || defsections || !strcasecmp(section,"cpu")) { | |
1b085c9f | 1514 | if (sections++) info = sdscat(info,"\r\n"); |
1515 | info = sdscatprintf(info, | |
0d808ef2 | 1516 | "# CPU\r\n" |
1b085c9f | 1517 | "used_cpu_sys:%.2f\r\n" |
1518 | "used_cpu_user:%.2f\r\n" | |
5a9dd97c | 1519 | "used_cpu_sys_children:%.2f\r\n" |
1520 | "used_cpu_user_children:%.2f\r\n", | |
1b085c9f | 1521 | (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000, |
d83eda48 | 1522 | (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000, |
1523 | (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000, | |
1524 | (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000); | |
0d808ef2 | 1525 | } |
1b085c9f | 1526 | |
0d808ef2 | 1527 | /* cmdtime */ |
1528 | if (allsections || !strcasecmp(section,"commandstats")) { | |
1529 | if (sections++) info = sdscat(info,"\r\n"); | |
1530 | info = sdscatprintf(info, "# Commandstats\r\n"); | |
d7ed7fd2 | 1531 | numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); |
1b085c9f | 1532 | for (j = 0; j < numcommands; j++) { |
d7ed7fd2 | 1533 | struct redisCommand *c = redisCommandTable+j; |
0d808ef2 | 1534 | |
d7ed7fd2 | 1535 | if (!c->calls) continue; |
1536 | info = sdscatprintf(info, | |
1537 | "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n", | |
1538 | c->name, c->calls, c->microseconds, | |
1539 | (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls)); | |
1b085c9f | 1540 | } |
d9cb288c | 1541 | } |
1542 | ||
1c708b25 SS |
1543 | /* Clusetr */ |
1544 | if (allsections || defsections || !strcasecmp(section,"cluster")) { | |
1545 | if (sections++) info = sdscat(info,"\r\n"); | |
1546 | info = sdscatprintf(info, | |
1547 | "# Cluster\r\n" | |
1548 | "cluster_enabled:%d\r\n", | |
1549 | server.cluster_enabled); | |
1550 | } | |
1551 | ||
1b085c9f | 1552 | /* Key space */ |
1553 | if (allsections || defsections || !strcasecmp(section,"keyspace")) { | |
1554 | if (sections++) info = sdscat(info,"\r\n"); | |
1555 | info = sdscatprintf(info, "# Keyspace\r\n"); | |
1556 | for (j = 0; j < server.dbnum; j++) { | |
1557 | long long keys, vkeys; | |
e2641e09 | 1558 | |
1b085c9f | 1559 | keys = dictSize(server.db[j].dict); |
1560 | vkeys = dictSize(server.db[j].expires); | |
1561 | if (keys || vkeys) { | |
1562 | info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n", | |
1563 | j, keys, vkeys); | |
1564 | } | |
e2641e09 | 1565 | } |
1566 | } | |
1567 | return info; | |
1568 | } | |
1569 | ||
1570 | void infoCommand(redisClient *c) { | |
1b085c9f | 1571 | char *section = c->argc == 2 ? c->argv[1]->ptr : "default"; |
1572 | ||
1573 | if (c->argc > 2) { | |
1574 | addReply(c,shared.syntaxerr); | |
1575 | return; | |
1576 | } | |
1577 | sds info = genRedisInfoString(section); | |
e2641e09 | 1578 | addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n", |
1579 | (unsigned long)sdslen(info))); | |
1580 | addReplySds(c,info); | |
1581 | addReply(c,shared.crlf); | |
1582 | } | |
1583 | ||
1584 | void monitorCommand(redisClient *c) { | |
1585 | /* ignore MONITOR if aleady slave or in monitor mode */ | |
1586 | if (c->flags & REDIS_SLAVE) return; | |
1587 | ||
1588 | c->flags |= (REDIS_SLAVE|REDIS_MONITOR); | |
1589 | c->slaveseldb = 0; | |
1590 | listAddNodeTail(server.monitors,c); | |
1591 | addReply(c,shared.ok); | |
1592 | } | |
1593 | ||
1594 | /* ============================ Maxmemory directive ======================== */ | |
1595 | ||
e2641e09 | 1596 | /* This function gets called when 'maxmemory' is set on the config file to limit |
1597 | * the max memory used by the server, and we are out of memory. | |
1598 | * This function will try to, in order: | |
1599 | * | |
1600 | * - Free objects from the free list | |
1601 | * - Try to remove keys with an EXPIRE set | |
1602 | * | |
1603 | * It is not possible to free enough memory to reach used-memory < maxmemory | |
1604 | * the server will start refusing commands that will enlarge even more the | |
1605 | * memory usage. | |
1606 | */ | |
1607 | void freeMemoryIfNeeded(void) { | |
165346ca | 1608 | /* Remove keys accordingly to the active policy as long as we are |
1609 | * over the memory limit. */ | |
5402c426 | 1610 | if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return; |
1611 | ||
ca734d17 | 1612 | while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) { |
e2641e09 | 1613 | int j, k, freed = 0; |
1614 | ||
165346ca | 1615 | for (j = 0; j < server.dbnum; j++) { |
10c12171 | 1616 | long bestval = 0; /* just to prevent warning */ |
165346ca | 1617 | sds bestkey = NULL; |
1618 | struct dictEntry *de; | |
1619 | redisDb *db = server.db+j; | |
1620 | dict *dict; | |
1621 | ||
1622 | if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || | |
1623 | server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM) | |
1624 | { | |
1625 | dict = server.db[j].dict; | |
1626 | } else { | |
1627 | dict = server.db[j].expires; | |
1628 | } | |
1629 | if (dictSize(dict) == 0) continue; | |
1630 | ||
1631 | /* volatile-random and allkeys-random policy */ | |
1632 | if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM || | |
1633 | server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM) | |
1634 | { | |
1635 | de = dictGetRandomKey(dict); | |
1636 | bestkey = dictGetEntryKey(de); | |
1637 | } | |
1638 | ||
1639 | /* volatile-lru and allkeys-lru policy */ | |
1640 | else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || | |
1641 | server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU) | |
1642 | { | |
1643 | for (k = 0; k < server.maxmemory_samples; k++) { | |
1644 | sds thiskey; | |
1645 | long thisval; | |
1646 | robj *o; | |
1647 | ||
1648 | de = dictGetRandomKey(dict); | |
1649 | thiskey = dictGetEntryKey(de); | |
0c2f75c6 | 1650 | /* When policy is volatile-lru we need an additonal lookup |
1651 | * to locate the real key, as dict is set to db->expires. */ | |
1652 | if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU) | |
1653 | de = dictFind(db->dict, thiskey); | |
165346ca | 1654 | o = dictGetEntryVal(de); |
1655 | thisval = estimateObjectIdleTime(o); | |
1656 | ||
1657 | /* Higher idle time is better candidate for deletion */ | |
1658 | if (bestkey == NULL || thisval > bestval) { | |
1659 | bestkey = thiskey; | |
1660 | bestval = thisval; | |
1661 | } | |
1662 | } | |
1663 | } | |
1664 | ||
1665 | /* volatile-ttl */ | |
1666 | else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) { | |
1667 | for (k = 0; k < server.maxmemory_samples; k++) { | |
1668 | sds thiskey; | |
1669 | long thisval; | |
1670 | ||
1671 | de = dictGetRandomKey(dict); | |
1672 | thiskey = dictGetEntryKey(de); | |
1673 | thisval = (long) dictGetEntryVal(de); | |
1674 | ||
1675 | /* Expire sooner (minor expire unix timestamp) is better | |
1676 | * candidate for deletion */ | |
1677 | if (bestkey == NULL || thisval < bestval) { | |
1678 | bestkey = thiskey; | |
1679 | bestval = thisval; | |
1680 | } | |
1681 | } | |
1682 | } | |
1683 | ||
1684 | /* Finally remove the selected key. */ | |
1685 | if (bestkey) { | |
1686 | robj *keyobj = createStringObject(bestkey,sdslen(bestkey)); | |
452229b6 | 1687 | propagateExpire(db,keyobj); |
165346ca | 1688 | dbDelete(db,keyobj); |
f21779ff | 1689 | server.stat_evictedkeys++; |
165346ca | 1690 | decrRefCount(keyobj); |
1691 | freed++; | |
1692 | } | |
1693 | } | |
1694 | if (!freed) return; /* nothing to free... */ | |
1695 | } | |
e2641e09 | 1696 | } |
1697 | ||
1698 | /* =================================== Main! ================================ */ | |
1699 | ||
1700 | #ifdef __linux__ | |
1701 | int linuxOvercommitMemoryValue(void) { | |
1702 | FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); | |
1703 | char buf[64]; | |
1704 | ||
1705 | if (!fp) return -1; | |
1706 | if (fgets(buf,64,fp) == NULL) { | |
1707 | fclose(fp); | |
1708 | return -1; | |
1709 | } | |
1710 | fclose(fp); | |
1711 | ||
1712 | return atoi(buf); | |
1713 | } | |
1714 | ||
1715 | void linuxOvercommitMemoryWarning(void) { | |
1716 | if (linuxOvercommitMemoryValue() == 0) { | |
1717 | 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."); | |
1718 | } | |
1719 | } | |
1720 | #endif /* __linux__ */ | |
1721 | ||
695fe874 | 1722 | void createPidFile(void) { |
1723 | /* Try to write the pid file in a best-effort way. */ | |
1724 | FILE *fp = fopen(server.pidfile,"w"); | |
1725 | if (fp) { | |
8ce39260 | 1726 | fprintf(fp,"%d\n",(int)getpid()); |
695fe874 | 1727 | fclose(fp); |
1728 | } | |
1729 | } | |
1730 | ||
e2641e09 | 1731 | void daemonize(void) { |
1732 | int fd; | |
e2641e09 | 1733 | |
1734 | if (fork() != 0) exit(0); /* parent exits */ | |
1735 | setsid(); /* create a new session */ | |
1736 | ||
1737 | /* Every output goes to /dev/null. If Redis is daemonized but | |
1738 | * the 'logfile' is set to 'stdout' in the configuration file | |
1739 | * it will not log at all. */ | |
1740 | if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { | |
1741 | dup2(fd, STDIN_FILENO); | |
1742 | dup2(fd, STDOUT_FILENO); | |
1743 | dup2(fd, STDERR_FILENO); | |
1744 | if (fd > STDERR_FILENO) close(fd); | |
1745 | } | |
e2641e09 | 1746 | } |
1747 | ||
1748 | void version() { | |
1749 | printf("Redis server version %s (%s:%d)\n", REDIS_VERSION, | |
1750 | redisGitSHA1(), atoi(redisGitDirty()) > 0); | |
1751 | exit(0); | |
1752 | } | |
1753 | ||
1754 | void usage() { | |
1755 | fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n"); | |
1756 | fprintf(stderr," ./redis-server - (read config from stdin)\n"); | |
1757 | exit(1); | |
1758 | } | |
1759 | ||
996d503d | 1760 | void redisAsciiArt(void) { |
1761 | #include "asciilogo.h" | |
1762 | char *buf = zmalloc(1024*16); | |
1763 | ||
1764 | snprintf(buf,1024*16,ascii_logo, | |
1765 | REDIS_VERSION, | |
1766 | redisGitSHA1(), | |
1767 | strtol(redisGitDirty(),NULL,10) > 0, | |
1768 | (sizeof(long) == 8) ? "64" : "32", | |
1769 | server.cluster_enabled ? "cluster" : "stand alone", | |
1770 | server.port, | |
1771 | (long) getpid() | |
1772 | ); | |
1773 | redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf); | |
1774 | zfree(buf); | |
1775 | } | |
1776 | ||
e2641e09 | 1777 | int main(int argc, char **argv) { |
4d60dea8 | 1778 | long long start; |
e2641e09 | 1779 | |
7feb90fa | 1780 | zmalloc_enable_thread_safeness(); |
e2641e09 | 1781 | initServerConfig(); |
e2641e09 | 1782 | if (argc == 2) { |
1783 | if (strcmp(argv[1], "-v") == 0 || | |
1784 | strcmp(argv[1], "--version") == 0) version(); | |
1785 | if (strcmp(argv[1], "--help") == 0) usage(); | |
1786 | resetServerSaveParams(); | |
1787 | loadServerConfig(argv[1]); | |
1788 | } else if ((argc > 2)) { | |
1789 | usage(); | |
1790 | } else { | |
1791 | 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'"); | |
1792 | } | |
1793 | if (server.daemonize) daemonize(); | |
1794 | initServer(); | |
695fe874 | 1795 | if (server.daemonize) createPidFile(); |
996d503d | 1796 | redisAsciiArt(); |
e2641e09 | 1797 | redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION); |
1798 | #ifdef __linux__ | |
1799 | linuxOvercommitMemoryWarning(); | |
1800 | #endif | |
4d60dea8 | 1801 | start = ustime(); |
c9d0c362 | 1802 | if (server.appendonly) { |
e2641e09 | 1803 | if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK) |
4d60dea8 | 1804 | redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000); |
e2641e09 | 1805 | } else { |
6d61e5bf | 1806 | if (rdbLoad(server.dbfilename) == REDIS_OK) { |
1807 | redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds", | |
1808 | (float)(ustime()-start)/1000000); | |
1809 | } else if (errno != ENOENT) { | |
1810 | redisLog(REDIS_WARNING,"Fatal error loading the DB. Exiting."); | |
1811 | exit(1); | |
1812 | } | |
e2641e09 | 1813 | } |
a5639e7d PN |
1814 | if (server.ipfd > 0) |
1815 | redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port); | |
1816 | if (server.sofd > 0) | |
5d10923f | 1817 | redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket); |
e2641e09 | 1818 | aeSetBeforeSleepProc(server.el,beforeSleep); |
1819 | aeMain(server.el); | |
1820 | aeDeleteEventLoop(server.el); | |
1821 | return 0; | |
1822 | } | |
1823 | ||
e2641e09 | 1824 | #ifdef HAVE_BACKTRACE |
633a9410 | 1825 | static void *getMcontextEip(ucontext_t *uc) { |
e2641e09 | 1826 | #if defined(__FreeBSD__) |
1827 | return (void*) uc->uc_mcontext.mc_eip; | |
1828 | #elif defined(__dietlibc__) | |
1829 | return (void*) uc->uc_mcontext.eip; | |
1830 | #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6) | |
1831 | #if __x86_64__ | |
1832 | return (void*) uc->uc_mcontext->__ss.__rip; | |
ef9444e0 | 1833 | #elif __i386__ |
e2641e09 | 1834 | return (void*) uc->uc_mcontext->__ss.__eip; |
ef9444e0 KT |
1835 | #else |
1836 | return (void*) uc->uc_mcontext->__ss.__srr0; | |
e2641e09 | 1837 | #endif |
1838 | #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) | |
1839 | #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) | |
1840 | return (void*) uc->uc_mcontext->__ss.__rip; | |
1841 | #else | |
1842 | return (void*) uc->uc_mcontext->__ss.__eip; | |
1843 | #endif | |
3688d7f3 | 1844 | #elif defined(__i386__) |
1845 | return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */ | |
1846 | #elif defined(__X86_64__) || defined(__x86_64__) | |
1847 | return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */ | |
e2641e09 | 1848 | #elif defined(__ia64__) /* Linux IA64 */ |
1849 | return (void*) uc->uc_mcontext.sc_ip; | |
1850 | #else | |
1851 | return NULL; | |
1852 | #endif | |
1853 | } | |
1854 | ||
633a9410 | 1855 | static void sigsegvHandler(int sig, siginfo_t *info, void *secret) { |
e2641e09 | 1856 | void *trace[100]; |
1857 | char **messages = NULL; | |
1858 | int i, trace_size = 0; | |
1859 | ucontext_t *uc = (ucontext_t*) secret; | |
1860 | sds infostring; | |
da47440d | 1861 | struct sigaction act; |
e2641e09 | 1862 | REDIS_NOTUSED(info); |
1863 | ||
1864 | redisLog(REDIS_WARNING, | |
1865 | "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig); | |
1b085c9f | 1866 | infostring = genRedisInfoString("all"); |
9c104c68 | 1867 | redisLogRaw(REDIS_WARNING, infostring); |
e2641e09 | 1868 | /* It's not safe to sdsfree() the returned string under memory |
1869 | * corruption conditions. Let it leak as we are going to abort */ | |
1870 | ||
1871 | trace_size = backtrace(trace, 100); | |
1872 | /* overwrite sigaction with caller's address */ | |
1873 | if (getMcontextEip(uc) != NULL) { | |
1874 | trace[1] = getMcontextEip(uc); | |
1875 | } | |
1876 | messages = backtrace_symbols(trace, trace_size); | |
1877 | ||
1878 | for (i=1; i<trace_size; ++i) | |
1879 | redisLog(REDIS_WARNING,"%s", messages[i]); | |
1880 | ||
1881 | /* free(messages); Don't call free() with possibly corrupted memory. */ | |
695fe874 | 1882 | if (server.daemonize) unlink(server.pidfile); |
da47440d | 1883 | |
1884 | /* Make sure we exit with the right signal at the end. So for instance | |
1885 | * the core will be dumped if enabled. */ | |
1886 | sigemptyset (&act.sa_mask); | |
1887 | /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction | |
1888 | * is used. Otherwise, sa_handler is used */ | |
1889 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND; | |
1890 | act.sa_handler = SIG_DFL; | |
1891 | sigaction (sig, &act, NULL); | |
1892 | kill(getpid(),sig); | |
e2641e09 | 1893 | } |
633a9410 | 1894 | #endif /* HAVE_BACKTRACE */ |
e2641e09 | 1895 | |
633a9410 | 1896 | static void sigtermHandler(int sig) { |
e2641e09 | 1897 | REDIS_NOTUSED(sig); |
1898 | ||
633a9410 | 1899 | redisLog(REDIS_WARNING,"Received SIGTERM, scheduling shutdown..."); |
e2641e09 | 1900 | server.shutdown_asap = 1; |
1901 | } | |
1902 | ||
633a9410 | 1903 | void setupSignalHandlers(void) { |
e2641e09 | 1904 | struct sigaction act; |
1905 | ||
633a9410 PN |
1906 | /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. |
1907 | * Otherwise, sa_handler is used. */ | |
1908 | sigemptyset(&act.sa_mask); | |
e2641e09 | 1909 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND; |
1910 | act.sa_handler = sigtermHandler; | |
633a9410 | 1911 | sigaction(SIGTERM, &act, NULL); |
e2641e09 | 1912 | |
633a9410 PN |
1913 | #ifdef HAVE_BACKTRACE |
1914 | sigemptyset(&act.sa_mask); | |
1915 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO; | |
1916 | act.sa_sigaction = sigsegvHandler; | |
1917 | sigaction(SIGSEGV, &act, NULL); | |
1918 | sigaction(SIGBUS, &act, NULL); | |
1919 | sigaction(SIGFPE, &act, NULL); | |
1920 | sigaction(SIGILL, &act, NULL); | |
1921 | #endif | |
1922 | return; | |
e2641e09 | 1923 | } |
e2641e09 | 1924 | |
1925 | /* The End */ |