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