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