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