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