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