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