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