]>
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> | |
54 | ||
55 | /* Our shared "common" objects */ | |
56 | ||
57 | struct sharedObjectsStruct shared; | |
58 | ||
59 | /* Global vars that are actally used as constants. The following double | |
60 | * values are used for double on-disk serialization, and are initialized | |
61 | * at runtime to avoid strange compiler optimizations. */ | |
62 | ||
63 | double R_Zero, R_PosInf, R_NegInf, R_Nan; | |
64 | ||
65 | /*================================= Globals ================================= */ | |
66 | ||
67 | /* Global vars */ | |
68 | struct redisServer server; /* server global state */ | |
69 | struct redisCommand *commandTable; | |
70 | struct redisCommand readonlyCommandTable[] = { | |
71 | {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
72 | {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0}, | |
73 | {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0}, | |
74 | {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0}, | |
75 | {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
76 | {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
80091bba | 77 | {"strlen",strlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, |
e2641e09 | 78 | {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0}, |
79 | {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
80 | {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
81 | {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
82 | {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1}, | |
83 | {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
84 | {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
85 | {"rpushx",rpushxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
86 | {"lpushx",lpushxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
87 | {"linsert",linsertCommand,5,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
88 | {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
89 | {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
90 | {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1}, | |
91 | {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1}, | |
92 | {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
93 | {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1}, | |
94 | {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
95 | {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
96 | {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
97 | {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1}, | |
98 | {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1}, | |
99 | {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
100 | {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1}, | |
101 | {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1}, | |
102 | {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1}, | |
103 | {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
104 | {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
105 | {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
106 | {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1}, | |
107 | {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1}, | |
108 | {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1}, | |
109 | {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1}, | |
110 | {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1}, | |
111 | {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1}, | |
112 | {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
113 | {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
114 | {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
115 | {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1}, | |
116 | {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
117 | {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
118 | {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0}, | |
119 | {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0}, | |
120 | {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
121 | {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
122 | {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
123 | {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1}, | |
124 | {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
125 | {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
126 | {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1}, | |
127 | {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1}, | |
128 | {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
129 | {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
130 | {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1}, | |
131 | {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
132 | {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1}, | |
133 | {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
134 | {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1}, | |
135 | {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
136 | {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
137 | {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
138 | {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
139 | {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1}, | |
140 | {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
141 | {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
142 | {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
143 | {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2}, | |
144 | {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2}, | |
145 | {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
146 | {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0}, | |
147 | {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1}, | |
148 | {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1}, | |
149 | {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1}, | |
150 | {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0}, | |
151 | {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0}, | |
152 | {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0}, | |
153 | {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
154 | {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0}, | |
155 | {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
156 | {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0}, | |
157 | {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
158 | {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
159 | {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
160 | {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
161 | {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
162 | {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
163 | {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
164 | {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0}, | |
165 | {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
166 | {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
167 | {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
168 | {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
169 | {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
170 | {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
171 | {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
172 | {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
a539d29a | 173 | {"persist",persistCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, |
e2641e09 | 174 | {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0}, |
175 | {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0}, | |
176 | {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0}, | |
177 | {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0}, | |
178 | {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
179 | {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0}, | |
180 | {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0}, | |
181 | {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0}, | |
182 | {"watch",watchCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0}, | |
183 | {"unwatch",unwatchCommand,1,REDIS_CMD_INLINE,NULL,0,0,0} | |
184 | }; | |
185 | ||
186 | /*============================ Utility functions ============================ */ | |
187 | ||
188 | void redisLog(int level, const char *fmt, ...) { | |
189 | va_list ap; | |
190 | FILE *fp; | |
23072961 | 191 | char *c = ".-*#"; |
192 | char buf[64]; | |
193 | time_t now; | |
194 | ||
195 | if (level < server.verbosity) return; | |
e2641e09 | 196 | |
197 | fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a"); | |
198 | if (!fp) return; | |
199 | ||
200 | va_start(ap, fmt); | |
23072961 | 201 | now = time(NULL); |
202 | strftime(buf,64,"%d %b %H:%M:%S",localtime(&now)); | |
203 | fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]); | |
204 | vfprintf(fp, fmt, ap); | |
205 | fprintf(fp,"\n"); | |
206 | fflush(fp); | |
e2641e09 | 207 | va_end(ap); |
208 | ||
209 | if (server.logfile) fclose(fp); | |
210 | } | |
211 | ||
212 | /* Redis generally does not try to recover from out of memory conditions | |
213 | * when allocating objects or strings, it is not clear if it will be possible | |
214 | * to report this condition to the client since the networking layer itself | |
215 | * is based on heap allocation for send buffers, so we simply abort. | |
216 | * At least the code will be simpler to read... */ | |
217 | void oom(const char *msg) { | |
218 | redisLog(REDIS_WARNING, "%s: Out of memory\n",msg); | |
219 | sleep(1); | |
220 | abort(); | |
221 | } | |
222 | ||
223 | /*====================== Hash table type implementation ==================== */ | |
224 | ||
225 | /* This is an hash table type that uses the SDS dynamic strings libary as | |
226 | * keys and radis objects as values (objects can hold SDS strings, | |
227 | * lists, sets). */ | |
228 | ||
229 | void dictVanillaFree(void *privdata, void *val) | |
230 | { | |
231 | DICT_NOTUSED(privdata); | |
232 | zfree(val); | |
233 | } | |
234 | ||
235 | void dictListDestructor(void *privdata, void *val) | |
236 | { | |
237 | DICT_NOTUSED(privdata); | |
238 | listRelease((list*)val); | |
239 | } | |
240 | ||
241 | int dictSdsKeyCompare(void *privdata, const void *key1, | |
242 | const void *key2) | |
243 | { | |
244 | int l1,l2; | |
245 | DICT_NOTUSED(privdata); | |
246 | ||
247 | l1 = sdslen((sds)key1); | |
248 | l2 = sdslen((sds)key2); | |
249 | if (l1 != l2) return 0; | |
250 | return memcmp(key1, key2, l1) == 0; | |
251 | } | |
252 | ||
253 | void dictRedisObjectDestructor(void *privdata, void *val) | |
254 | { | |
255 | DICT_NOTUSED(privdata); | |
256 | ||
257 | if (val == NULL) return; /* Values of swapped out keys as set to NULL */ | |
258 | decrRefCount(val); | |
259 | } | |
260 | ||
261 | void dictSdsDestructor(void *privdata, void *val) | |
262 | { | |
263 | DICT_NOTUSED(privdata); | |
264 | ||
265 | sdsfree(val); | |
266 | } | |
267 | ||
268 | int dictObjKeyCompare(void *privdata, const void *key1, | |
269 | const void *key2) | |
270 | { | |
271 | const robj *o1 = key1, *o2 = key2; | |
272 | return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); | |
273 | } | |
274 | ||
275 | unsigned int dictObjHash(const void *key) { | |
276 | const robj *o = key; | |
277 | return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
278 | } | |
279 | ||
280 | unsigned int dictSdsHash(const void *key) { | |
281 | return dictGenHashFunction((unsigned char*)key, sdslen((char*)key)); | |
282 | } | |
283 | ||
284 | int dictEncObjKeyCompare(void *privdata, const void *key1, | |
285 | const void *key2) | |
286 | { | |
287 | robj *o1 = (robj*) key1, *o2 = (robj*) key2; | |
288 | int cmp; | |
289 | ||
290 | if (o1->encoding == REDIS_ENCODING_INT && | |
291 | o2->encoding == REDIS_ENCODING_INT) | |
292 | return o1->ptr == o2->ptr; | |
293 | ||
294 | o1 = getDecodedObject(o1); | |
295 | o2 = getDecodedObject(o2); | |
296 | cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); | |
297 | decrRefCount(o1); | |
298 | decrRefCount(o2); | |
299 | return cmp; | |
300 | } | |
301 | ||
302 | unsigned int dictEncObjHash(const void *key) { | |
303 | robj *o = (robj*) key; | |
304 | ||
305 | if (o->encoding == REDIS_ENCODING_RAW) { | |
306 | return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
307 | } else { | |
308 | if (o->encoding == REDIS_ENCODING_INT) { | |
309 | char buf[32]; | |
310 | int len; | |
311 | ||
312 | len = ll2string(buf,32,(long)o->ptr); | |
313 | return dictGenHashFunction((unsigned char*)buf, len); | |
314 | } else { | |
315 | unsigned int hash; | |
316 | ||
317 | o = getDecodedObject(o); | |
318 | hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
319 | decrRefCount(o); | |
320 | return hash; | |
321 | } | |
322 | } | |
323 | } | |
324 | ||
325 | /* Sets type */ | |
326 | dictType setDictType = { | |
327 | dictEncObjHash, /* hash function */ | |
328 | NULL, /* key dup */ | |
329 | NULL, /* val dup */ | |
330 | dictEncObjKeyCompare, /* key compare */ | |
331 | dictRedisObjectDestructor, /* key destructor */ | |
332 | NULL /* val destructor */ | |
333 | }; | |
334 | ||
335 | /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ | |
336 | dictType zsetDictType = { | |
337 | dictEncObjHash, /* hash function */ | |
338 | NULL, /* key dup */ | |
339 | NULL, /* val dup */ | |
340 | dictEncObjKeyCompare, /* key compare */ | |
341 | dictRedisObjectDestructor, /* key destructor */ | |
342 | dictVanillaFree /* val destructor of malloc(sizeof(double)) */ | |
343 | }; | |
344 | ||
345 | /* Db->dict, keys are sds strings, vals are Redis objects. */ | |
346 | dictType dbDictType = { | |
347 | dictSdsHash, /* hash function */ | |
348 | NULL, /* key dup */ | |
349 | NULL, /* val dup */ | |
350 | dictSdsKeyCompare, /* key compare */ | |
351 | dictSdsDestructor, /* key destructor */ | |
352 | dictRedisObjectDestructor /* val destructor */ | |
353 | }; | |
354 | ||
355 | /* Db->expires */ | |
356 | dictType keyptrDictType = { | |
357 | dictSdsHash, /* hash function */ | |
358 | NULL, /* key dup */ | |
359 | NULL, /* val dup */ | |
360 | dictSdsKeyCompare, /* key compare */ | |
361 | NULL, /* key destructor */ | |
362 | NULL /* val destructor */ | |
363 | }; | |
364 | ||
365 | /* Hash type hash table (note that small hashes are represented with zimpaps) */ | |
366 | dictType hashDictType = { | |
367 | dictEncObjHash, /* hash function */ | |
368 | NULL, /* key dup */ | |
369 | NULL, /* val dup */ | |
370 | dictEncObjKeyCompare, /* key compare */ | |
371 | dictRedisObjectDestructor, /* key destructor */ | |
372 | dictRedisObjectDestructor /* val destructor */ | |
373 | }; | |
374 | ||
375 | /* Keylist hash table type has unencoded redis objects as keys and | |
376 | * lists as values. It's used for blocking operations (BLPOP) and to | |
377 | * map swapped keys to a list of clients waiting for this keys to be loaded. */ | |
378 | dictType keylistDictType = { | |
379 | dictObjHash, /* hash function */ | |
380 | NULL, /* key dup */ | |
381 | NULL, /* val dup */ | |
382 | dictObjKeyCompare, /* key compare */ | |
383 | dictRedisObjectDestructor, /* key destructor */ | |
384 | dictListDestructor /* val destructor */ | |
385 | }; | |
386 | ||
387 | int htNeedsResize(dict *dict) { | |
388 | long long size, used; | |
389 | ||
390 | size = dictSlots(dict); | |
391 | used = dictSize(dict); | |
392 | return (size && used && size > DICT_HT_INITIAL_SIZE && | |
393 | (used*100/size < REDIS_HT_MINFILL)); | |
394 | } | |
395 | ||
396 | /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL | |
397 | * we resize the hash table to save memory */ | |
398 | void tryResizeHashTables(void) { | |
399 | int j; | |
400 | ||
401 | for (j = 0; j < server.dbnum; j++) { | |
402 | if (htNeedsResize(server.db[j].dict)) | |
403 | dictResize(server.db[j].dict); | |
404 | if (htNeedsResize(server.db[j].expires)) | |
405 | dictResize(server.db[j].expires); | |
406 | } | |
407 | } | |
408 | ||
409 | /* Our hash table implementation performs rehashing incrementally while | |
410 | * we write/read from the hash table. Still if the server is idle, the hash | |
411 | * table will use two tables for a long time. So we try to use 1 millisecond | |
412 | * of CPU time at every serverCron() loop in order to rehash some key. */ | |
413 | void incrementallyRehash(void) { | |
414 | int j; | |
415 | ||
416 | for (j = 0; j < server.dbnum; j++) { | |
417 | if (dictIsRehashing(server.db[j].dict)) { | |
418 | dictRehashMilliseconds(server.db[j].dict,1); | |
419 | break; /* already used our millisecond for this loop... */ | |
420 | } | |
421 | } | |
422 | } | |
423 | ||
424 | /* This function is called once a background process of some kind terminates, | |
425 | * as we want to avoid resizing the hash tables when there is a child in order | |
426 | * to play well with copy-on-write (otherwise when a resize happens lots of | |
427 | * memory pages are copied). The goal of this function is to update the ability | |
428 | * for dict.c to resize the hash tables accordingly to the fact we have o not | |
429 | * running childs. */ | |
430 | void updateDictResizePolicy(void) { | |
431 | if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) | |
432 | dictEnableResize(); | |
433 | else | |
434 | dictDisableResize(); | |
435 | } | |
436 | ||
437 | /* ======================= Cron: called every 100 ms ======================== */ | |
438 | ||
bcf2995c | 439 | /* Try to expire a few timed out keys. The algorithm used is adaptive and |
440 | * will use few CPU cycles if there are few expiring keys, otherwise | |
441 | * it will get more aggressive to avoid that too much memory is used by | |
442 | * keys that can be removed from the keyspace. */ | |
443 | void activeExpireCycle(void) { | |
444 | int j; | |
445 | ||
446 | for (j = 0; j < server.dbnum; j++) { | |
447 | int expired; | |
448 | redisDb *db = server.db+j; | |
449 | ||
450 | /* Continue to expire if at the end of the cycle more than 25% | |
451 | * of the keys were expired. */ | |
452 | do { | |
453 | long num = dictSize(db->expires); | |
454 | time_t now = time(NULL); | |
455 | ||
456 | expired = 0; | |
457 | if (num > REDIS_EXPIRELOOKUPS_PER_CRON) | |
458 | num = REDIS_EXPIRELOOKUPS_PER_CRON; | |
459 | while (num--) { | |
460 | dictEntry *de; | |
461 | time_t t; | |
462 | ||
463 | if ((de = dictGetRandomKey(db->expires)) == NULL) break; | |
464 | t = (time_t) dictGetEntryVal(de); | |
465 | if (now > t) { | |
466 | sds key = dictGetEntryKey(de); | |
467 | robj *keyobj = createStringObject(key,sdslen(key)); | |
468 | ||
469 | propagateExpire(db,keyobj); | |
470 | dbDelete(db,keyobj); | |
471 | decrRefCount(keyobj); | |
472 | expired++; | |
473 | server.stat_expiredkeys++; | |
474 | } | |
475 | } | |
476 | } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4); | |
477 | } | |
478 | } | |
479 | ||
480 | ||
e2641e09 | 481 | int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { |
482 | int j, loops = server.cronloops++; | |
483 | REDIS_NOTUSED(eventLoop); | |
484 | REDIS_NOTUSED(id); | |
485 | REDIS_NOTUSED(clientData); | |
486 | ||
487 | /* We take a cached value of the unix time in the global state because | |
488 | * with virtual memory and aging there is to store the current time | |
489 | * in objects at every object access, and accuracy is not needed. | |
490 | * To access a global var is faster than calling time(NULL) */ | |
491 | server.unixtime = time(NULL); | |
492 | /* We have just 21 bits per object for LRU information. | |
493 | * So we use an (eventually wrapping) LRU clock with minutes resolution. | |
494 | * | |
495 | * When we need to select what object to swap, we compute the minimum | |
496 | * time distance between the current lruclock and the object last access | |
497 | * lruclock info. Even if clocks will wrap on overflow, there is | |
498 | * the interesting property that we are sure that at least | |
499 | * ABS(A-B) minutes passed between current time and timestamp B. | |
500 | * | |
501 | * This is not precise but we don't need at all precision, but just | |
502 | * something statistically reasonable. | |
503 | */ | |
504 | server.lruclock = (time(NULL)/60)&((1<<21)-1); | |
505 | ||
506 | /* We received a SIGTERM, shutting down here in a safe way, as it is | |
507 | * not ok doing so inside the signal handler. */ | |
508 | if (server.shutdown_asap) { | |
509 | if (prepareForShutdown() == REDIS_OK) exit(0); | |
510 | redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); | |
511 | } | |
512 | ||
513 | /* Show some info about non-empty databases */ | |
514 | for (j = 0; j < server.dbnum; j++) { | |
515 | long long size, used, vkeys; | |
516 | ||
517 | size = dictSlots(server.db[j].dict); | |
518 | used = dictSize(server.db[j].dict); | |
519 | vkeys = dictSize(server.db[j].expires); | |
520 | if (!(loops % 50) && (used || vkeys)) { | |
521 | redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); | |
522 | /* dictPrintStats(server.dict); */ | |
523 | } | |
524 | } | |
525 | ||
526 | /* We don't want to resize the hash tables while a bacground saving | |
527 | * is in progress: the saving child is created using fork() that is | |
528 | * implemented with a copy-on-write semantic in most modern systems, so | |
529 | * if we resize the HT while there is the saving child at work actually | |
530 | * a lot of memory movements in the parent will cause a lot of pages | |
531 | * copied. */ | |
532 | if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) { | |
533 | if (!(loops % 10)) tryResizeHashTables(); | |
534 | if (server.activerehashing) incrementallyRehash(); | |
535 | } | |
536 | ||
537 | /* Show information about connected clients */ | |
538 | if (!(loops % 50)) { | |
539 | redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use", | |
540 | listLength(server.clients)-listLength(server.slaves), | |
541 | listLength(server.slaves), | |
542 | zmalloc_used_memory()); | |
543 | } | |
544 | ||
545 | /* Close connections of timedout clients */ | |
546 | if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients) | |
547 | closeTimedoutClients(); | |
548 | ||
549 | /* Check if a background saving or AOF rewrite in progress terminated */ | |
550 | if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) { | |
551 | int statloc; | |
552 | pid_t pid; | |
553 | ||
554 | if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { | |
555 | if (pid == server.bgsavechildpid) { | |
556 | backgroundSaveDoneHandler(statloc); | |
557 | } else { | |
558 | backgroundRewriteDoneHandler(statloc); | |
559 | } | |
560 | updateDictResizePolicy(); | |
561 | } | |
562 | } else { | |
563 | /* If there is not a background saving in progress check if | |
564 | * we have to save now */ | |
565 | time_t now = time(NULL); | |
566 | for (j = 0; j < server.saveparamslen; j++) { | |
567 | struct saveparam *sp = server.saveparams+j; | |
568 | ||
569 | if (server.dirty >= sp->changes && | |
570 | now-server.lastsave > sp->seconds) { | |
571 | redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...", | |
572 | sp->changes, sp->seconds); | |
573 | rdbSaveBackground(server.dbfilename); | |
574 | break; | |
575 | } | |
576 | } | |
577 | } | |
578 | ||
bcf2995c | 579 | /* Expire a few keys per cycle, only if this is a master. |
580 | * On slaves we wait for DEL operations synthesized by the master | |
581 | * in order to guarantee a strict consistency. */ | |
582 | if (server.masterhost == NULL) activeExpireCycle(); | |
e2641e09 | 583 | |
584 | /* Swap a few keys on disk if we are over the memory limit and VM | |
585 | * is enbled. Try to free objects from the free list first. */ | |
586 | if (vmCanSwapOut()) { | |
587 | while (server.vm_enabled && zmalloc_used_memory() > | |
588 | server.vm_max_memory) | |
589 | { | |
590 | int retval; | |
591 | ||
592 | if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue; | |
593 | retval = (server.vm_max_threads == 0) ? | |
594 | vmSwapOneObjectBlocking() : | |
595 | vmSwapOneObjectThreaded(); | |
596 | if (retval == REDIS_ERR && !(loops % 300) && | |
597 | zmalloc_used_memory() > | |
598 | (server.vm_max_memory+server.vm_max_memory/10)) | |
599 | { | |
600 | redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!"); | |
601 | } | |
602 | /* Note that when using threade I/O we free just one object, | |
603 | * because anyway when the I/O thread in charge to swap this | |
604 | * object out will finish, the handler of completed jobs | |
605 | * will try to swap more objects if we are still out of memory. */ | |
606 | if (retval == REDIS_ERR || server.vm_max_threads > 0) break; | |
607 | } | |
608 | } | |
609 | ||
610 | /* Check if we should connect to a MASTER */ | |
611 | if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) { | |
612 | redisLog(REDIS_NOTICE,"Connecting to MASTER..."); | |
613 | if (syncWithMaster() == REDIS_OK) { | |
614 | redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded"); | |
615 | if (server.appendonly) rewriteAppendOnlyFileBackground(); | |
616 | } | |
617 | } | |
618 | return 100; | |
619 | } | |
620 | ||
621 | /* This function gets called every time Redis is entering the | |
622 | * main loop of the event driven library, that is, before to sleep | |
623 | * for ready file descriptors. */ | |
624 | void beforeSleep(struct aeEventLoop *eventLoop) { | |
625 | REDIS_NOTUSED(eventLoop); | |
626 | ||
627 | /* Awake clients that got all the swapped keys they requested */ | |
628 | if (server.vm_enabled && listLength(server.io_ready_clients)) { | |
629 | listIter li; | |
630 | listNode *ln; | |
631 | ||
632 | listRewind(server.io_ready_clients,&li); | |
633 | while((ln = listNext(&li))) { | |
634 | redisClient *c = ln->value; | |
635 | struct redisCommand *cmd; | |
636 | ||
637 | /* Resume the client. */ | |
638 | listDelNode(server.io_ready_clients,ln); | |
639 | c->flags &= (~REDIS_IO_WAIT); | |
640 | server.vm_blocked_clients--; | |
641 | aeCreateFileEvent(server.el, c->fd, AE_READABLE, | |
642 | readQueryFromClient, c); | |
643 | cmd = lookupCommand(c->argv[0]->ptr); | |
644 | redisAssert(cmd != NULL); | |
645 | call(c,cmd); | |
646 | resetClient(c); | |
647 | /* There may be more data to process in the input buffer. */ | |
648 | if (c->querybuf && sdslen(c->querybuf) > 0) | |
649 | processInputBuffer(c); | |
650 | } | |
651 | } | |
652 | /* Write the AOF buffer on disk */ | |
653 | flushAppendOnlyFile(); | |
654 | } | |
655 | ||
656 | /* =========================== Server initialization ======================== */ | |
657 | ||
658 | void createSharedObjects(void) { | |
659 | int j; | |
660 | ||
661 | shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n")); | |
662 | shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n")); | |
663 | shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n")); | |
664 | shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n")); | |
665 | shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n")); | |
666 | shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n")); | |
667 | shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n")); | |
668 | shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n")); | |
669 | shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n")); | |
670 | shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n")); | |
671 | shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n")); | |
672 | shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n")); | |
673 | shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew( | |
674 | "-ERR Operation against a key holding the wrong kind of value\r\n")); | |
675 | shared.nokeyerr = createObject(REDIS_STRING,sdsnew( | |
676 | "-ERR no such key\r\n")); | |
677 | shared.syntaxerr = createObject(REDIS_STRING,sdsnew( | |
678 | "-ERR syntax error\r\n")); | |
679 | shared.sameobjecterr = createObject(REDIS_STRING,sdsnew( | |
680 | "-ERR source and destination objects are the same\r\n")); | |
681 | shared.outofrangeerr = createObject(REDIS_STRING,sdsnew( | |
682 | "-ERR index out of range\r\n")); | |
683 | shared.space = createObject(REDIS_STRING,sdsnew(" ")); | |
684 | shared.colon = createObject(REDIS_STRING,sdsnew(":")); | |
685 | shared.plus = createObject(REDIS_STRING,sdsnew("+")); | |
686 | shared.select0 = createStringObject("select 0\r\n",10); | |
687 | shared.select1 = createStringObject("select 1\r\n",10); | |
688 | shared.select2 = createStringObject("select 2\r\n",10); | |
689 | shared.select3 = createStringObject("select 3\r\n",10); | |
690 | shared.select4 = createStringObject("select 4\r\n",10); | |
691 | shared.select5 = createStringObject("select 5\r\n",10); | |
692 | shared.select6 = createStringObject("select 6\r\n",10); | |
693 | shared.select7 = createStringObject("select 7\r\n",10); | |
694 | shared.select8 = createStringObject("select 8\r\n",10); | |
695 | shared.select9 = createStringObject("select 9\r\n",10); | |
696 | shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); | |
697 | shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); | |
698 | shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); | |
699 | shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); | |
700 | shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); | |
701 | shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); | |
702 | shared.mbulk3 = createStringObject("*3\r\n",4); | |
703 | shared.mbulk4 = createStringObject("*4\r\n",4); | |
704 | for (j = 0; j < REDIS_SHARED_INTEGERS; j++) { | |
705 | shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j); | |
706 | shared.integers[j]->encoding = REDIS_ENCODING_INT; | |
707 | } | |
708 | } | |
709 | ||
710 | void initServerConfig() { | |
711 | server.dbnum = REDIS_DEFAULT_DBNUM; | |
712 | server.port = REDIS_SERVERPORT; | |
713 | server.verbosity = REDIS_VERBOSE; | |
714 | server.maxidletime = REDIS_MAXIDLETIME; | |
715 | server.saveparams = NULL; | |
716 | server.logfile = NULL; /* NULL = log on standard output */ | |
717 | server.bindaddr = NULL; | |
718 | server.glueoutputbuf = 1; | |
719 | server.daemonize = 0; | |
720 | server.appendonly = 0; | |
721 | server.appendfsync = APPENDFSYNC_EVERYSEC; | |
722 | server.no_appendfsync_on_rewrite = 0; | |
723 | server.lastfsync = time(NULL); | |
724 | server.appendfd = -1; | |
725 | server.appendseldb = -1; /* Make sure the first time will not match */ | |
726 | server.pidfile = zstrdup("/var/run/redis.pid"); | |
727 | server.dbfilename = zstrdup("dump.rdb"); | |
728 | server.appendfilename = zstrdup("appendonly.aof"); | |
729 | server.requirepass = NULL; | |
730 | server.rdbcompression = 1; | |
731 | server.activerehashing = 1; | |
732 | server.maxclients = 0; | |
733 | server.blpop_blocked_clients = 0; | |
734 | server.maxmemory = 0; | |
735 | server.vm_enabled = 0; | |
736 | server.vm_swap_file = zstrdup("/tmp/redis-%p.vm"); | |
737 | server.vm_page_size = 256; /* 256 bytes per page */ | |
738 | server.vm_pages = 1024*1024*100; /* 104 millions of pages */ | |
739 | server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */ | |
740 | server.vm_max_threads = 4; | |
741 | server.vm_blocked_clients = 0; | |
742 | server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES; | |
743 | server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE; | |
744 | server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES; | |
745 | server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE; | |
96ffb2fe | 746 | server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES; |
e2641e09 | 747 | server.shutdown_asap = 0; |
748 | ||
749 | resetServerSaveParams(); | |
750 | ||
751 | appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ | |
752 | appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ | |
753 | appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ | |
754 | /* Replication related */ | |
755 | server.isslave = 0; | |
756 | server.masterauth = NULL; | |
757 | server.masterhost = NULL; | |
758 | server.masterport = 6379; | |
759 | server.master = NULL; | |
760 | server.replstate = REDIS_REPL_NONE; | |
761 | ||
762 | /* Double constants initialization */ | |
763 | R_Zero = 0.0; | |
764 | R_PosInf = 1.0/R_Zero; | |
765 | R_NegInf = -1.0/R_Zero; | |
766 | R_Nan = R_Zero/R_Zero; | |
767 | } | |
768 | ||
769 | void initServer() { | |
770 | int j; | |
771 | ||
772 | signal(SIGHUP, SIG_IGN); | |
773 | signal(SIGPIPE, SIG_IGN); | |
774 | setupSigSegvAction(); | |
775 | ||
0e5441d8 | 776 | server.mainthread = pthread_self(); |
e2641e09 | 777 | server.devnull = fopen("/dev/null","w"); |
778 | if (server.devnull == NULL) { | |
779 | redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr); | |
780 | exit(1); | |
781 | } | |
782 | server.clients = listCreate(); | |
783 | server.slaves = listCreate(); | |
784 | server.monitors = listCreate(); | |
785 | server.objfreelist = listCreate(); | |
786 | createSharedObjects(); | |
787 | server.el = aeCreateEventLoop(); | |
788 | server.db = zmalloc(sizeof(redisDb)*server.dbnum); | |
789 | server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr); | |
790 | if (server.fd == -1) { | |
791 | redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr); | |
792 | exit(1); | |
793 | } | |
794 | for (j = 0; j < server.dbnum; j++) { | |
795 | server.db[j].dict = dictCreate(&dbDictType,NULL); | |
796 | server.db[j].expires = dictCreate(&keyptrDictType,NULL); | |
797 | server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); | |
798 | server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); | |
799 | if (server.vm_enabled) | |
800 | server.db[j].io_keys = dictCreate(&keylistDictType,NULL); | |
801 | server.db[j].id = j; | |
802 | } | |
803 | server.pubsub_channels = dictCreate(&keylistDictType,NULL); | |
804 | server.pubsub_patterns = listCreate(); | |
805 | listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); | |
806 | listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); | |
807 | server.cronloops = 0; | |
808 | server.bgsavechildpid = -1; | |
809 | server.bgrewritechildpid = -1; | |
810 | server.bgrewritebuf = sdsempty(); | |
811 | server.aofbuf = sdsempty(); | |
812 | server.lastsave = time(NULL); | |
813 | server.dirty = 0; | |
814 | server.stat_numcommands = 0; | |
815 | server.stat_numconnections = 0; | |
816 | server.stat_expiredkeys = 0; | |
817 | server.stat_starttime = time(NULL); | |
818 | server.unixtime = time(NULL); | |
819 | aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL); | |
820 | if (aeCreateFileEvent(server.el, server.fd, AE_READABLE, | |
821 | acceptHandler, NULL) == AE_ERR) oom("creating file event"); | |
822 | ||
823 | if (server.appendonly) { | |
824 | server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644); | |
825 | if (server.appendfd == -1) { | |
826 | redisLog(REDIS_WARNING, "Can't open the append-only file: %s", | |
827 | strerror(errno)); | |
828 | exit(1); | |
829 | } | |
830 | } | |
831 | ||
832 | if (server.vm_enabled) vmInit(); | |
833 | } | |
834 | ||
835 | int qsortRedisCommands(const void *r1, const void *r2) { | |
836 | return strcasecmp( | |
837 | ((struct redisCommand*)r1)->name, | |
838 | ((struct redisCommand*)r2)->name); | |
839 | } | |
840 | ||
841 | void sortCommandTable() { | |
842 | /* Copy and sort the read-only version of the command table */ | |
b3aa6d71 | 843 | commandTable = (struct redisCommand*)zmalloc(sizeof(readonlyCommandTable)); |
e2641e09 | 844 | memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable)); |
845 | qsort(commandTable, | |
846 | sizeof(readonlyCommandTable)/sizeof(struct redisCommand), | |
847 | sizeof(struct redisCommand),qsortRedisCommands); | |
848 | } | |
849 | ||
850 | /* ====================== Commands lookup and execution ===================== */ | |
851 | ||
852 | struct redisCommand *lookupCommand(char *name) { | |
853 | struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0}; | |
854 | return bsearch( | |
855 | &tmp, | |
856 | commandTable, | |
857 | sizeof(readonlyCommandTable)/sizeof(struct redisCommand), | |
858 | sizeof(struct redisCommand), | |
859 | qsortRedisCommands); | |
860 | } | |
861 | ||
862 | /* Call() is the core of Redis execution of a command */ | |
863 | void call(redisClient *c, struct redisCommand *cmd) { | |
864 | long long dirty; | |
865 | ||
866 | dirty = server.dirty; | |
867 | cmd->proc(c); | |
868 | dirty = server.dirty-dirty; | |
869 | ||
870 | if (server.appendonly && dirty) | |
871 | feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc); | |
872 | if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) && | |
873 | listLength(server.slaves)) | |
874 | replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc); | |
875 | if (listLength(server.monitors)) | |
876 | replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc); | |
877 | server.stat_numcommands++; | |
878 | } | |
879 | ||
880 | /* If this function gets called we already read a whole | |
881 | * command, argments are in the client argv/argc fields. | |
882 | * processCommand() execute the command or prepare the | |
883 | * server for a bulk read from the client. | |
884 | * | |
885 | * If 1 is returned the client is still alive and valid and | |
886 | * and other operations can be performed by the caller. Otherwise | |
887 | * if 0 is returned the client was destroied (i.e. after QUIT). */ | |
888 | int processCommand(redisClient *c) { | |
889 | struct redisCommand *cmd; | |
890 | ||
891 | /* Free some memory if needed (maxmemory setting) */ | |
892 | if (server.maxmemory) freeMemoryIfNeeded(); | |
893 | ||
894 | /* Handle the multi bulk command type. This is an alternative protocol | |
895 | * supported by Redis in order to receive commands that are composed of | |
896 | * multiple binary-safe "bulk" arguments. The latency of processing is | |
897 | * a bit higher but this allows things like multi-sets, so if this | |
898 | * protocol is used only for MSET and similar commands this is a big win. */ | |
899 | if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') { | |
900 | c->multibulk = atoi(((char*)c->argv[0]->ptr)+1); | |
901 | if (c->multibulk <= 0) { | |
902 | resetClient(c); | |
903 | return 1; | |
904 | } else { | |
905 | decrRefCount(c->argv[c->argc-1]); | |
906 | c->argc--; | |
907 | return 1; | |
908 | } | |
909 | } else if (c->multibulk) { | |
910 | if (c->bulklen == -1) { | |
911 | if (((char*)c->argv[0]->ptr)[0] != '$') { | |
912 | addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n")); | |
913 | resetClient(c); | |
914 | return 1; | |
915 | } else { | |
a679185a | 916 | char *eptr; |
917 | long bulklen = strtol(((char*)c->argv[0]->ptr)+1,&eptr,10); | |
918 | int perr = eptr[0] != '\0'; | |
919 | ||
e2641e09 | 920 | decrRefCount(c->argv[0]); |
a679185a | 921 | if (perr || bulklen == LONG_MIN || bulklen == LONG_MAX || |
922 | bulklen < 0 || bulklen > 1024*1024*1024) | |
923 | { | |
e2641e09 | 924 | c->argc--; |
925 | addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n")); | |
926 | resetClient(c); | |
927 | return 1; | |
928 | } | |
929 | c->argc--; | |
930 | c->bulklen = bulklen+2; /* add two bytes for CR+LF */ | |
931 | return 1; | |
932 | } | |
933 | } else { | |
934 | c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1)); | |
935 | c->mbargv[c->mbargc] = c->argv[0]; | |
936 | c->mbargc++; | |
937 | c->argc--; | |
938 | c->multibulk--; | |
939 | if (c->multibulk == 0) { | |
940 | robj **auxargv; | |
941 | int auxargc; | |
942 | ||
943 | /* Here we need to swap the multi-bulk argc/argv with the | |
944 | * normal argc/argv of the client structure. */ | |
945 | auxargv = c->argv; | |
946 | c->argv = c->mbargv; | |
947 | c->mbargv = auxargv; | |
948 | ||
949 | auxargc = c->argc; | |
950 | c->argc = c->mbargc; | |
951 | c->mbargc = auxargc; | |
952 | ||
953 | /* We need to set bulklen to something different than -1 | |
954 | * in order for the code below to process the command without | |
955 | * to try to read the last argument of a bulk command as | |
956 | * a special argument. */ | |
957 | c->bulklen = 0; | |
958 | /* continue below and process the command */ | |
959 | } else { | |
960 | c->bulklen = -1; | |
961 | return 1; | |
962 | } | |
963 | } | |
964 | } | |
965 | /* -- end of multi bulk commands processing -- */ | |
966 | ||
967 | /* The QUIT command is handled as a special case. Normal command | |
968 | * procs are unable to close the client connection safely */ | |
969 | if (!strcasecmp(c->argv[0]->ptr,"quit")) { | |
970 | freeClient(c); | |
971 | return 0; | |
972 | } | |
973 | ||
974 | /* Now lookup the command and check ASAP about trivial error conditions | |
975 | * such wrong arity, bad command name and so forth. */ | |
976 | cmd = lookupCommand(c->argv[0]->ptr); | |
977 | if (!cmd) { | |
978 | addReplySds(c, | |
979 | sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n", | |
980 | (char*)c->argv[0]->ptr)); | |
981 | resetClient(c); | |
982 | return 1; | |
983 | } else if ((cmd->arity > 0 && cmd->arity != c->argc) || | |
984 | (c->argc < -cmd->arity)) { | |
985 | addReplySds(c, | |
986 | sdscatprintf(sdsempty(), | |
987 | "-ERR wrong number of arguments for '%s' command\r\n", | |
988 | cmd->name)); | |
989 | resetClient(c); | |
990 | return 1; | |
991 | } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) { | |
992 | /* This is a bulk command, we have to read the last argument yet. */ | |
a679185a | 993 | char *eptr; |
994 | long bulklen = strtol(c->argv[c->argc-1]->ptr,&eptr,10); | |
995 | int perr = eptr[0] != '\0'; | |
e2641e09 | 996 | |
997 | decrRefCount(c->argv[c->argc-1]); | |
a679185a | 998 | if (perr || bulklen == LONG_MAX || bulklen == LONG_MIN || |
999 | bulklen < 0 || bulklen > 1024*1024*1024) | |
1000 | { | |
e2641e09 | 1001 | c->argc--; |
1002 | addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n")); | |
1003 | resetClient(c); | |
1004 | return 1; | |
1005 | } | |
1006 | c->argc--; | |
1007 | c->bulklen = bulklen+2; /* add two bytes for CR+LF */ | |
1008 | /* It is possible that the bulk read is already in the | |
1009 | * buffer. Check this condition and handle it accordingly. | |
1010 | * This is just a fast path, alternative to call processInputBuffer(). | |
1011 | * It's a good idea since the code is small and this condition | |
1012 | * happens most of the times. */ | |
1013 | if ((signed)sdslen(c->querybuf) >= c->bulklen) { | |
1014 | c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2); | |
1015 | c->argc++; | |
1016 | c->querybuf = sdsrange(c->querybuf,c->bulklen,-1); | |
1017 | } else { | |
1018 | /* Otherwise return... there is to read the last argument | |
1019 | * from the socket. */ | |
1020 | return 1; | |
1021 | } | |
1022 | } | |
1023 | /* Let's try to encode the bulk object to save space. */ | |
1024 | if (cmd->flags & REDIS_CMD_BULK) | |
1025 | c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]); | |
1026 | ||
1027 | /* Check if the user is authenticated */ | |
1028 | if (server.requirepass && !c->authenticated && cmd->proc != authCommand) { | |
1029 | addReplySds(c,sdsnew("-ERR operation not permitted\r\n")); | |
1030 | resetClient(c); | |
1031 | return 1; | |
1032 | } | |
1033 | ||
1034 | /* Handle the maxmemory directive */ | |
1035 | if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) && | |
1036 | zmalloc_used_memory() > server.maxmemory) | |
1037 | { | |
1038 | addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n")); | |
1039 | resetClient(c); | |
1040 | return 1; | |
1041 | } | |
1042 | ||
1043 | /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ | |
1044 | if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0) | |
1045 | && | |
1046 | cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand && | |
1047 | cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) { | |
1048 | addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n")); | |
1049 | resetClient(c); | |
1050 | return 1; | |
1051 | } | |
1052 | ||
1053 | /* Exec the command */ | |
1054 | if (c->flags & REDIS_MULTI && | |
1055 | cmd->proc != execCommand && cmd->proc != discardCommand && | |
1056 | cmd->proc != multiCommand && cmd->proc != watchCommand) | |
1057 | { | |
1058 | queueMultiCommand(c,cmd); | |
1059 | addReply(c,shared.queued); | |
1060 | } else { | |
1061 | if (server.vm_enabled && server.vm_max_threads > 0 && | |
1062 | blockClientOnSwappedKeys(c,cmd)) return 1; | |
1063 | call(c,cmd); | |
1064 | } | |
1065 | ||
1066 | /* Prepare the client for the next command */ | |
1067 | resetClient(c); | |
1068 | return 1; | |
1069 | } | |
1070 | ||
1071 | /*================================== Shutdown =============================== */ | |
1072 | ||
1073 | int prepareForShutdown() { | |
1074 | redisLog(REDIS_WARNING,"User requested shutdown, saving DB..."); | |
1075 | /* Kill the saving child if there is a background saving in progress. | |
1076 | We want to avoid race conditions, for instance our saving child may | |
1077 | overwrite the synchronous saving did by SHUTDOWN. */ | |
1078 | if (server.bgsavechildpid != -1) { | |
1079 | redisLog(REDIS_WARNING,"There is a live saving child. Killing it!"); | |
1080 | kill(server.bgsavechildpid,SIGKILL); | |
1081 | rdbRemoveTempFile(server.bgsavechildpid); | |
1082 | } | |
1083 | if (server.appendonly) { | |
1084 | /* Append only file: fsync() the AOF and exit */ | |
1085 | aof_fsync(server.appendfd); | |
1086 | if (server.vm_enabled) unlink(server.vm_swap_file); | |
1087 | } else { | |
1088 | /* Snapshotting. Perform a SYNC SAVE and exit */ | |
695fe874 | 1089 | if (rdbSave(server.dbfilename) != REDIS_OK) { |
e2641e09 | 1090 | /* Ooops.. error saving! The best we can do is to continue |
1091 | * operating. Note that if there was a background saving process, | |
1092 | * in the next cron() Redis will be notified that the background | |
1093 | * saving aborted, handling special stuff like slaves pending for | |
1094 | * synchronization... */ | |
1095 | redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit"); | |
1096 | return REDIS_ERR; | |
1097 | } | |
1098 | } | |
695fe874 | 1099 | if (server.daemonize) unlink(server.pidfile); |
e2641e09 | 1100 | redisLog(REDIS_WARNING,"Server exit now, bye bye..."); |
1101 | return REDIS_OK; | |
1102 | } | |
1103 | ||
1104 | /*================================== Commands =============================== */ | |
1105 | ||
1106 | void authCommand(redisClient *c) { | |
1107 | if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) { | |
1108 | c->authenticated = 1; | |
1109 | addReply(c,shared.ok); | |
1110 | } else { | |
1111 | c->authenticated = 0; | |
1112 | addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n")); | |
1113 | } | |
1114 | } | |
1115 | ||
1116 | void pingCommand(redisClient *c) { | |
1117 | addReply(c,shared.pong); | |
1118 | } | |
1119 | ||
1120 | void echoCommand(redisClient *c) { | |
1121 | addReplyBulk(c,c->argv[1]); | |
1122 | } | |
1123 | ||
1124 | /* Convert an amount of bytes into a human readable string in the form | |
1125 | * of 100B, 2G, 100M, 4K, and so forth. */ | |
1126 | void bytesToHuman(char *s, unsigned long long n) { | |
1127 | double d; | |
1128 | ||
1129 | if (n < 1024) { | |
1130 | /* Bytes */ | |
1131 | sprintf(s,"%lluB",n); | |
1132 | return; | |
1133 | } else if (n < (1024*1024)) { | |
1134 | d = (double)n/(1024); | |
1135 | sprintf(s,"%.2fK",d); | |
1136 | } else if (n < (1024LL*1024*1024)) { | |
1137 | d = (double)n/(1024*1024); | |
1138 | sprintf(s,"%.2fM",d); | |
1139 | } else if (n < (1024LL*1024*1024*1024)) { | |
1140 | d = (double)n/(1024LL*1024*1024); | |
1141 | sprintf(s,"%.2fG",d); | |
1142 | } | |
1143 | } | |
1144 | ||
1145 | /* Create the string returned by the INFO command. This is decoupled | |
1146 | * by the INFO command itself as we need to report the same information | |
1147 | * on memory corruption problems. */ | |
1148 | sds genRedisInfoString(void) { | |
1149 | sds info; | |
1150 | time_t uptime = time(NULL)-server.stat_starttime; | |
1151 | int j; | |
1152 | char hmem[64]; | |
1153 | ||
1154 | bytesToHuman(hmem,zmalloc_used_memory()); | |
1155 | info = sdscatprintf(sdsempty(), | |
1156 | "redis_version:%s\r\n" | |
1157 | "redis_git_sha1:%s\r\n" | |
1158 | "redis_git_dirty:%d\r\n" | |
1159 | "arch_bits:%s\r\n" | |
1160 | "multiplexing_api:%s\r\n" | |
1161 | "process_id:%ld\r\n" | |
1162 | "uptime_in_seconds:%ld\r\n" | |
1163 | "uptime_in_days:%ld\r\n" | |
1164 | "connected_clients:%d\r\n" | |
1165 | "connected_slaves:%d\r\n" | |
1166 | "blocked_clients:%d\r\n" | |
1167 | "used_memory:%zu\r\n" | |
1168 | "used_memory_human:%s\r\n" | |
eddb388e | 1169 | "mem_fragmentation_ratio:%.2f\r\n" |
e2641e09 | 1170 | "changes_since_last_save:%lld\r\n" |
1171 | "bgsave_in_progress:%d\r\n" | |
1172 | "last_save_time:%ld\r\n" | |
1173 | "bgrewriteaof_in_progress:%d\r\n" | |
1174 | "total_connections_received:%lld\r\n" | |
1175 | "total_commands_processed:%lld\r\n" | |
1176 | "expired_keys:%lld\r\n" | |
1177 | "hash_max_zipmap_entries:%zu\r\n" | |
1178 | "hash_max_zipmap_value:%zu\r\n" | |
1179 | "pubsub_channels:%ld\r\n" | |
1180 | "pubsub_patterns:%u\r\n" | |
1181 | "vm_enabled:%d\r\n" | |
1182 | "role:%s\r\n" | |
1183 | ,REDIS_VERSION, | |
1184 | redisGitSHA1(), | |
1185 | strtol(redisGitDirty(),NULL,10) > 0, | |
1186 | (sizeof(long) == 8) ? "64" : "32", | |
1187 | aeGetApiName(), | |
1188 | (long) getpid(), | |
1189 | uptime, | |
1190 | uptime/(3600*24), | |
1191 | listLength(server.clients)-listLength(server.slaves), | |
1192 | listLength(server.slaves), | |
1193 | server.blpop_blocked_clients, | |
1194 | zmalloc_used_memory(), | |
1195 | hmem, | |
eddb388e | 1196 | zmalloc_get_fragmentation_ratio(), |
e2641e09 | 1197 | server.dirty, |
1198 | server.bgsavechildpid != -1, | |
1199 | server.lastsave, | |
1200 | server.bgrewritechildpid != -1, | |
1201 | server.stat_numconnections, | |
1202 | server.stat_numcommands, | |
1203 | server.stat_expiredkeys, | |
1204 | server.hash_max_zipmap_entries, | |
1205 | server.hash_max_zipmap_value, | |
1206 | dictSize(server.pubsub_channels), | |
1207 | listLength(server.pubsub_patterns), | |
1208 | server.vm_enabled != 0, | |
1209 | server.masterhost == NULL ? "master" : "slave" | |
1210 | ); | |
1211 | if (server.masterhost) { | |
1212 | info = sdscatprintf(info, | |
1213 | "master_host:%s\r\n" | |
1214 | "master_port:%d\r\n" | |
1215 | "master_link_status:%s\r\n" | |
1216 | "master_last_io_seconds_ago:%d\r\n" | |
1217 | ,server.masterhost, | |
1218 | server.masterport, | |
1219 | (server.replstate == REDIS_REPL_CONNECTED) ? | |
1220 | "up" : "down", | |
1221 | server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1 | |
1222 | ); | |
1223 | } | |
1224 | if (server.vm_enabled) { | |
1225 | lockThreadedIO(); | |
1226 | info = sdscatprintf(info, | |
1227 | "vm_conf_max_memory:%llu\r\n" | |
1228 | "vm_conf_page_size:%llu\r\n" | |
1229 | "vm_conf_pages:%llu\r\n" | |
1230 | "vm_stats_used_pages:%llu\r\n" | |
1231 | "vm_stats_swapped_objects:%llu\r\n" | |
1232 | "vm_stats_swappin_count:%llu\r\n" | |
1233 | "vm_stats_swappout_count:%llu\r\n" | |
1234 | "vm_stats_io_newjobs_len:%lu\r\n" | |
1235 | "vm_stats_io_processing_len:%lu\r\n" | |
1236 | "vm_stats_io_processed_len:%lu\r\n" | |
1237 | "vm_stats_io_active_threads:%lu\r\n" | |
1238 | "vm_stats_blocked_clients:%lu\r\n" | |
1239 | ,(unsigned long long) server.vm_max_memory, | |
1240 | (unsigned long long) server.vm_page_size, | |
1241 | (unsigned long long) server.vm_pages, | |
1242 | (unsigned long long) server.vm_stats_used_pages, | |
1243 | (unsigned long long) server.vm_stats_swapped_objects, | |
1244 | (unsigned long long) server.vm_stats_swapins, | |
1245 | (unsigned long long) server.vm_stats_swapouts, | |
1246 | (unsigned long) listLength(server.io_newjobs), | |
1247 | (unsigned long) listLength(server.io_processing), | |
1248 | (unsigned long) listLength(server.io_processed), | |
1249 | (unsigned long) server.io_active_threads, | |
1250 | (unsigned long) server.vm_blocked_clients | |
1251 | ); | |
1252 | unlockThreadedIO(); | |
1253 | } | |
1254 | for (j = 0; j < server.dbnum; j++) { | |
1255 | long long keys, vkeys; | |
1256 | ||
1257 | keys = dictSize(server.db[j].dict); | |
1258 | vkeys = dictSize(server.db[j].expires); | |
1259 | if (keys || vkeys) { | |
1260 | info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n", | |
1261 | j, keys, vkeys); | |
1262 | } | |
1263 | } | |
1264 | return info; | |
1265 | } | |
1266 | ||
1267 | void infoCommand(redisClient *c) { | |
1268 | sds info = genRedisInfoString(); | |
1269 | addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n", | |
1270 | (unsigned long)sdslen(info))); | |
1271 | addReplySds(c,info); | |
1272 | addReply(c,shared.crlf); | |
1273 | } | |
1274 | ||
1275 | void monitorCommand(redisClient *c) { | |
1276 | /* ignore MONITOR if aleady slave or in monitor mode */ | |
1277 | if (c->flags & REDIS_SLAVE) return; | |
1278 | ||
1279 | c->flags |= (REDIS_SLAVE|REDIS_MONITOR); | |
1280 | c->slaveseldb = 0; | |
1281 | listAddNodeTail(server.monitors,c); | |
1282 | addReply(c,shared.ok); | |
1283 | } | |
1284 | ||
1285 | /* ============================ Maxmemory directive ======================== */ | |
1286 | ||
1287 | /* Try to free one object form the pre-allocated objects free list. | |
1288 | * This is useful under low mem conditions as by default we take 1 million | |
1289 | * free objects allocated. On success REDIS_OK is returned, otherwise | |
1290 | * REDIS_ERR. */ | |
1291 | int tryFreeOneObjectFromFreelist(void) { | |
1292 | robj *o; | |
1293 | ||
1294 | if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex); | |
1295 | if (listLength(server.objfreelist)) { | |
1296 | listNode *head = listFirst(server.objfreelist); | |
1297 | o = listNodeValue(head); | |
1298 | listDelNode(server.objfreelist,head); | |
1299 | if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex); | |
1300 | zfree(o); | |
1301 | return REDIS_OK; | |
1302 | } else { | |
1303 | if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex); | |
1304 | return REDIS_ERR; | |
1305 | } | |
1306 | } | |
1307 | ||
1308 | /* This function gets called when 'maxmemory' is set on the config file to limit | |
1309 | * the max memory used by the server, and we are out of memory. | |
1310 | * This function will try to, in order: | |
1311 | * | |
1312 | * - Free objects from the free list | |
1313 | * - Try to remove keys with an EXPIRE set | |
1314 | * | |
1315 | * It is not possible to free enough memory to reach used-memory < maxmemory | |
1316 | * the server will start refusing commands that will enlarge even more the | |
1317 | * memory usage. | |
1318 | */ | |
1319 | void freeMemoryIfNeeded(void) { | |
1320 | while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) { | |
1321 | int j, k, freed = 0; | |
1322 | ||
1323 | if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue; | |
1324 | for (j = 0; j < server.dbnum; j++) { | |
1325 | int minttl = -1; | |
357d3673 | 1326 | sds minkey = NULL; |
1327 | robj *keyobj = NULL; | |
e2641e09 | 1328 | struct dictEntry *de; |
1329 | ||
1330 | if (dictSize(server.db[j].expires)) { | |
1331 | freed = 1; | |
1332 | /* From a sample of three keys drop the one nearest to | |
1333 | * the natural expire */ | |
1334 | for (k = 0; k < 3; k++) { | |
1335 | time_t t; | |
1336 | ||
1337 | de = dictGetRandomKey(server.db[j].expires); | |
1338 | t = (time_t) dictGetEntryVal(de); | |
1339 | if (minttl == -1 || t < minttl) { | |
1340 | minkey = dictGetEntryKey(de); | |
1341 | minttl = t; | |
1342 | } | |
1343 | } | |
357d3673 | 1344 | keyobj = createStringObject(minkey,sdslen(minkey)); |
1345 | dbDelete(server.db+j,keyobj); | |
1346 | decrRefCount(keyobj); | |
e2641e09 | 1347 | } |
1348 | } | |
1349 | if (!freed) return; /* nothing to free... */ | |
1350 | } | |
1351 | } | |
1352 | ||
1353 | /* =================================== Main! ================================ */ | |
1354 | ||
1355 | #ifdef __linux__ | |
1356 | int linuxOvercommitMemoryValue(void) { | |
1357 | FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); | |
1358 | char buf[64]; | |
1359 | ||
1360 | if (!fp) return -1; | |
1361 | if (fgets(buf,64,fp) == NULL) { | |
1362 | fclose(fp); | |
1363 | return -1; | |
1364 | } | |
1365 | fclose(fp); | |
1366 | ||
1367 | return atoi(buf); | |
1368 | } | |
1369 | ||
1370 | void linuxOvercommitMemoryWarning(void) { | |
1371 | if (linuxOvercommitMemoryValue() == 0) { | |
1372 | 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."); | |
1373 | } | |
1374 | } | |
1375 | #endif /* __linux__ */ | |
1376 | ||
695fe874 | 1377 | void createPidFile(void) { |
1378 | /* Try to write the pid file in a best-effort way. */ | |
1379 | FILE *fp = fopen(server.pidfile,"w"); | |
1380 | if (fp) { | |
1381 | fprintf(fp,"%d\n",getpid()); | |
1382 | fclose(fp); | |
1383 | } | |
1384 | } | |
1385 | ||
e2641e09 | 1386 | void daemonize(void) { |
1387 | int fd; | |
e2641e09 | 1388 | |
1389 | if (fork() != 0) exit(0); /* parent exits */ | |
1390 | setsid(); /* create a new session */ | |
1391 | ||
1392 | /* Every output goes to /dev/null. If Redis is daemonized but | |
1393 | * the 'logfile' is set to 'stdout' in the configuration file | |
1394 | * it will not log at all. */ | |
1395 | if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { | |
1396 | dup2(fd, STDIN_FILENO); | |
1397 | dup2(fd, STDOUT_FILENO); | |
1398 | dup2(fd, STDERR_FILENO); | |
1399 | if (fd > STDERR_FILENO) close(fd); | |
1400 | } | |
e2641e09 | 1401 | } |
1402 | ||
1403 | void version() { | |
1404 | printf("Redis server version %s (%s:%d)\n", REDIS_VERSION, | |
1405 | redisGitSHA1(), atoi(redisGitDirty()) > 0); | |
1406 | exit(0); | |
1407 | } | |
1408 | ||
1409 | void usage() { | |
1410 | fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n"); | |
1411 | fprintf(stderr," ./redis-server - (read config from stdin)\n"); | |
1412 | exit(1); | |
1413 | } | |
1414 | ||
1415 | int main(int argc, char **argv) { | |
1416 | time_t start; | |
1417 | ||
1418 | initServerConfig(); | |
1419 | sortCommandTable(); | |
1420 | if (argc == 2) { | |
1421 | if (strcmp(argv[1], "-v") == 0 || | |
1422 | strcmp(argv[1], "--version") == 0) version(); | |
1423 | if (strcmp(argv[1], "--help") == 0) usage(); | |
1424 | resetServerSaveParams(); | |
1425 | loadServerConfig(argv[1]); | |
1426 | } else if ((argc > 2)) { | |
1427 | usage(); | |
1428 | } else { | |
1429 | 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'"); | |
1430 | } | |
1431 | if (server.daemonize) daemonize(); | |
1432 | initServer(); | |
695fe874 | 1433 | if (server.daemonize) createPidFile(); |
e2641e09 | 1434 | redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION); |
1435 | #ifdef __linux__ | |
1436 | linuxOvercommitMemoryWarning(); | |
1437 | #endif | |
1438 | start = time(NULL); | |
1439 | if (server.appendonly) { | |
1440 | if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK) | |
1441 | redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start); | |
1442 | } else { | |
1443 | if (rdbLoad(server.dbfilename) == REDIS_OK) | |
1444 | redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start); | |
1445 | } | |
1446 | redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port); | |
1447 | aeSetBeforeSleepProc(server.el,beforeSleep); | |
1448 | aeMain(server.el); | |
1449 | aeDeleteEventLoop(server.el); | |
1450 | return 0; | |
1451 | } | |
1452 | ||
1453 | /* ============================= Backtrace support ========================= */ | |
1454 | ||
1455 | #ifdef HAVE_BACKTRACE | |
1456 | void *getMcontextEip(ucontext_t *uc) { | |
1457 | #if defined(__FreeBSD__) | |
1458 | return (void*) uc->uc_mcontext.mc_eip; | |
1459 | #elif defined(__dietlibc__) | |
1460 | return (void*) uc->uc_mcontext.eip; | |
1461 | #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6) | |
1462 | #if __x86_64__ | |
1463 | return (void*) uc->uc_mcontext->__ss.__rip; | |
1464 | #else | |
1465 | return (void*) uc->uc_mcontext->__ss.__eip; | |
1466 | #endif | |
1467 | #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) | |
1468 | #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) | |
1469 | return (void*) uc->uc_mcontext->__ss.__rip; | |
1470 | #else | |
1471 | return (void*) uc->uc_mcontext->__ss.__eip; | |
1472 | #endif | |
3688d7f3 | 1473 | #elif defined(__i386__) |
1474 | return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */ | |
1475 | #elif defined(__X86_64__) || defined(__x86_64__) | |
1476 | return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */ | |
e2641e09 | 1477 | #elif defined(__ia64__) /* Linux IA64 */ |
1478 | return (void*) uc->uc_mcontext.sc_ip; | |
1479 | #else | |
1480 | return NULL; | |
1481 | #endif | |
1482 | } | |
1483 | ||
1484 | void segvHandler(int sig, siginfo_t *info, void *secret) { | |
1485 | void *trace[100]; | |
1486 | char **messages = NULL; | |
1487 | int i, trace_size = 0; | |
1488 | ucontext_t *uc = (ucontext_t*) secret; | |
1489 | sds infostring; | |
1490 | REDIS_NOTUSED(info); | |
1491 | ||
1492 | redisLog(REDIS_WARNING, | |
1493 | "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig); | |
1494 | infostring = genRedisInfoString(); | |
1495 | redisLog(REDIS_WARNING, "%s",infostring); | |
1496 | /* It's not safe to sdsfree() the returned string under memory | |
1497 | * corruption conditions. Let it leak as we are going to abort */ | |
1498 | ||
1499 | trace_size = backtrace(trace, 100); | |
1500 | /* overwrite sigaction with caller's address */ | |
1501 | if (getMcontextEip(uc) != NULL) { | |
1502 | trace[1] = getMcontextEip(uc); | |
1503 | } | |
1504 | messages = backtrace_symbols(trace, trace_size); | |
1505 | ||
1506 | for (i=1; i<trace_size; ++i) | |
1507 | redisLog(REDIS_WARNING,"%s", messages[i]); | |
1508 | ||
1509 | /* free(messages); Don't call free() with possibly corrupted memory. */ | |
695fe874 | 1510 | if (server.daemonize) unlink(server.pidfile); |
e2641e09 | 1511 | _exit(0); |
1512 | } | |
1513 | ||
1514 | void sigtermHandler(int sig) { | |
1515 | REDIS_NOTUSED(sig); | |
1516 | ||
1517 | redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down..."); | |
1518 | server.shutdown_asap = 1; | |
1519 | } | |
1520 | ||
1521 | void setupSigSegvAction(void) { | |
1522 | struct sigaction act; | |
1523 | ||
1524 | sigemptyset (&act.sa_mask); | |
1525 | /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction | |
1526 | * is used. Otherwise, sa_handler is used */ | |
1527 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO; | |
1528 | act.sa_sigaction = segvHandler; | |
1529 | sigaction (SIGSEGV, &act, NULL); | |
1530 | sigaction (SIGBUS, &act, NULL); | |
1531 | sigaction (SIGFPE, &act, NULL); | |
1532 | sigaction (SIGILL, &act, NULL); | |
1533 | sigaction (SIGBUS, &act, NULL); | |
1534 | ||
1535 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND; | |
1536 | act.sa_handler = sigtermHandler; | |
1537 | sigaction (SIGTERM, &act, NULL); | |
1538 | return; | |
1539 | } | |
1540 | ||
1541 | #else /* HAVE_BACKTRACE */ | |
1542 | void setupSigSegvAction(void) { | |
1543 | } | |
1544 | #endif /* HAVE_BACKTRACE */ | |
1545 | ||
1546 | /* The End */ |