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