]>
Commit | Line | Data |
---|---|---|
1 | /* | |
2 | * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> | |
3 | * All rights reserved. | |
4 | * | |
5 | * Redistribution and use in source and binary forms, with or without | |
6 | * modification, are permitted provided that the following conditions are met: | |
7 | * | |
8 | * * Redistributions of source code must retain the above copyright notice, | |
9 | * this list of conditions and the following disclaimer. | |
10 | * * Redistributions in binary form must reproduce the above copyright | |
11 | * notice, this list of conditions and the following disclaimer in the | |
12 | * documentation and/or other materials provided with the distribution. | |
13 | * * Neither the name of Redis nor the names of its contributors may be used | |
14 | * to endorse or promote products derived from this software without | |
15 | * specific prior written permission. | |
16 | * | |
17 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
18 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
19 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
20 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
21 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
22 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
23 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
24 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
25 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
26 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
27 | * POSSIBILITY OF SUCH DAMAGE. | |
28 | */ | |
29 | ||
30 | #include "redis.h" | |
31 | ||
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> | |
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 | #include <sys/resource.h> | |
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}, | |
78 | {"strlen",strlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
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}, | |
174 | {"persist",persistCommand,2,REDIS_CMD_INLINE,NULL,1,1,1}, | |
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; | |
192 | char *c = ".-*#"; | |
193 | char buf[64]; | |
194 | time_t now; | |
195 | ||
196 | if (level < server.verbosity) return; | |
197 | ||
198 | fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a"); | |
199 | if (!fp) return; | |
200 | ||
201 | va_start(ap, fmt); | |
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); | |
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 */ | |
343 | NULL /* val destructor */ | |
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 | ||
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 | void updateLRUClock(void) { | |
482 | server.lruclock = (time(NULL)/REDIS_LRU_CLOCK_RESOLUTION) & | |
483 | REDIS_LRU_CLOCK_MAX; | |
484 | } | |
485 | ||
486 | int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { | |
487 | int j, loops = server.cronloops++; | |
488 | REDIS_NOTUSED(eventLoop); | |
489 | REDIS_NOTUSED(id); | |
490 | REDIS_NOTUSED(clientData); | |
491 | ||
492 | /* We take a cached value of the unix time in the global state because | |
493 | * with virtual memory and aging there is to store the current time | |
494 | * in objects at every object access, and accuracy is not needed. | |
495 | * To access a global var is faster than calling time(NULL) */ | |
496 | server.unixtime = time(NULL); | |
497 | /* We have just 22 bits per object for LRU information. | |
498 | * So we use an (eventually wrapping) LRU clock with 10 seconds resolution. | |
499 | * 2^22 bits with 10 seconds resoluton is more or less 1.5 years. | |
500 | * | |
501 | * Note that even if this will wrap after 1.5 years it's not a problem, | |
502 | * everything will still work but just some object will appear younger | |
503 | * to Redis. But for this to happen a given object should never be touched | |
504 | * for 1.5 years. | |
505 | * | |
506 | * Note that you can change the resolution altering the | |
507 | * REDIS_LRU_CLOCK_RESOLUTION define. | |
508 | */ | |
509 | updateLRUClock(); | |
510 | ||
511 | /* We received a SIGTERM, shutting down here in a safe way, as it is | |
512 | * not ok doing so inside the signal handler. */ | |
513 | if (server.shutdown_asap) { | |
514 | if (prepareForShutdown() == REDIS_OK) exit(0); | |
515 | redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); | |
516 | } | |
517 | ||
518 | /* Show some info about non-empty databases */ | |
519 | for (j = 0; j < server.dbnum; j++) { | |
520 | long long size, used, vkeys; | |
521 | ||
522 | size = dictSlots(server.db[j].dict); | |
523 | used = dictSize(server.db[j].dict); | |
524 | vkeys = dictSize(server.db[j].expires); | |
525 | if (!(loops % 50) && (used || vkeys)) { | |
526 | redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); | |
527 | /* dictPrintStats(server.dict); */ | |
528 | } | |
529 | } | |
530 | ||
531 | /* We don't want to resize the hash tables while a bacground saving | |
532 | * is in progress: the saving child is created using fork() that is | |
533 | * implemented with a copy-on-write semantic in most modern systems, so | |
534 | * if we resize the HT while there is the saving child at work actually | |
535 | * a lot of memory movements in the parent will cause a lot of pages | |
536 | * copied. */ | |
537 | if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) { | |
538 | if (!(loops % 10)) tryResizeHashTables(); | |
539 | if (server.activerehashing) incrementallyRehash(); | |
540 | } | |
541 | ||
542 | /* Show information about connected clients */ | |
543 | if (!(loops % 50)) { | |
544 | redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use", | |
545 | listLength(server.clients)-listLength(server.slaves), | |
546 | listLength(server.slaves), | |
547 | zmalloc_used_memory()); | |
548 | } | |
549 | ||
550 | /* Close connections of timedout clients */ | |
551 | if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients) | |
552 | closeTimedoutClients(); | |
553 | ||
554 | /* Check if a background saving or AOF rewrite in progress terminated */ | |
555 | if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) { | |
556 | int statloc; | |
557 | pid_t pid; | |
558 | ||
559 | if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { | |
560 | if (pid == server.bgsavechildpid) { | |
561 | backgroundSaveDoneHandler(statloc); | |
562 | } else { | |
563 | backgroundRewriteDoneHandler(statloc); | |
564 | } | |
565 | updateDictResizePolicy(); | |
566 | } | |
567 | } else { | |
568 | /* If there is not a background saving in progress check if | |
569 | * we have to save now */ | |
570 | time_t now = time(NULL); | |
571 | for (j = 0; j < server.saveparamslen; j++) { | |
572 | struct saveparam *sp = server.saveparams+j; | |
573 | ||
574 | if (server.dirty >= sp->changes && | |
575 | now-server.lastsave > sp->seconds) { | |
576 | redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...", | |
577 | sp->changes, sp->seconds); | |
578 | rdbSaveBackground(server.dbfilename); | |
579 | break; | |
580 | } | |
581 | } | |
582 | } | |
583 | ||
584 | /* Expire a few keys per cycle, only if this is a master. | |
585 | * On slaves we wait for DEL operations synthesized by the master | |
586 | * in order to guarantee a strict consistency. */ | |
587 | if (server.masterhost == NULL) activeExpireCycle(); | |
588 | ||
589 | /* Swap a few keys on disk if we are over the memory limit and VM | |
590 | * is enbled. Try to free objects from the free list first. */ | |
591 | if (vmCanSwapOut()) { | |
592 | while (server.vm_enabled && zmalloc_used_memory() > | |
593 | server.vm_max_memory) | |
594 | { | |
595 | int retval; | |
596 | ||
597 | if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue; | |
598 | retval = (server.vm_max_threads == 0) ? | |
599 | vmSwapOneObjectBlocking() : | |
600 | vmSwapOneObjectThreaded(); | |
601 | if (retval == REDIS_ERR && !(loops % 300) && | |
602 | zmalloc_used_memory() > | |
603 | (server.vm_max_memory+server.vm_max_memory/10)) | |
604 | { | |
605 | redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!"); | |
606 | } | |
607 | /* Note that when using threade I/O we free just one object, | |
608 | * because anyway when the I/O thread in charge to swap this | |
609 | * object out will finish, the handler of completed jobs | |
610 | * will try to swap more objects if we are still out of memory. */ | |
611 | if (retval == REDIS_ERR || server.vm_max_threads > 0) break; | |
612 | } | |
613 | } | |
614 | ||
615 | /* Check if we should connect to a MASTER */ | |
616 | if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) { | |
617 | redisLog(REDIS_NOTICE,"Connecting to MASTER..."); | |
618 | if (syncWithMaster() == REDIS_OK) { | |
619 | redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded"); | |
620 | if (server.appendonly) rewriteAppendOnlyFileBackground(); | |
621 | } | |
622 | } | |
623 | return 100; | |
624 | } | |
625 | ||
626 | /* This function gets called every time Redis is entering the | |
627 | * main loop of the event driven library, that is, before to sleep | |
628 | * for ready file descriptors. */ | |
629 | void beforeSleep(struct aeEventLoop *eventLoop) { | |
630 | REDIS_NOTUSED(eventLoop); | |
631 | ||
632 | /* Awake clients that got all the swapped keys they requested */ | |
633 | if (server.vm_enabled && listLength(server.io_ready_clients)) { | |
634 | listIter li; | |
635 | listNode *ln; | |
636 | ||
637 | listRewind(server.io_ready_clients,&li); | |
638 | while((ln = listNext(&li))) { | |
639 | redisClient *c = ln->value; | |
640 | struct redisCommand *cmd; | |
641 | ||
642 | /* Resume the client. */ | |
643 | listDelNode(server.io_ready_clients,ln); | |
644 | c->flags &= (~REDIS_IO_WAIT); | |
645 | server.vm_blocked_clients--; | |
646 | aeCreateFileEvent(server.el, c->fd, AE_READABLE, | |
647 | readQueryFromClient, c); | |
648 | cmd = lookupCommand(c->argv[0]->ptr); | |
649 | redisAssert(cmd != NULL); | |
650 | call(c,cmd); | |
651 | resetClient(c); | |
652 | /* There may be more data to process in the input buffer. */ | |
653 | if (c->querybuf && sdslen(c->querybuf) > 0) | |
654 | processInputBuffer(c); | |
655 | } | |
656 | } | |
657 | /* Write the AOF buffer on disk */ | |
658 | flushAppendOnlyFile(); | |
659 | } | |
660 | ||
661 | /* =========================== Server initialization ======================== */ | |
662 | ||
663 | void createSharedObjects(void) { | |
664 | int j; | |
665 | ||
666 | shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n")); | |
667 | shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n")); | |
668 | shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n")); | |
669 | shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n")); | |
670 | shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n")); | |
671 | shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n")); | |
672 | shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n")); | |
673 | shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n")); | |
674 | shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n")); | |
675 | shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n")); | |
676 | shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n")); | |
677 | shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n")); | |
678 | shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew( | |
679 | "-ERR Operation against a key holding the wrong kind of value\r\n")); | |
680 | shared.nokeyerr = createObject(REDIS_STRING,sdsnew( | |
681 | "-ERR no such key\r\n")); | |
682 | shared.syntaxerr = createObject(REDIS_STRING,sdsnew( | |
683 | "-ERR syntax error\r\n")); | |
684 | shared.sameobjecterr = createObject(REDIS_STRING,sdsnew( | |
685 | "-ERR source and destination objects are the same\r\n")); | |
686 | shared.outofrangeerr = createObject(REDIS_STRING,sdsnew( | |
687 | "-ERR index out of range\r\n")); | |
688 | shared.space = createObject(REDIS_STRING,sdsnew(" ")); | |
689 | shared.colon = createObject(REDIS_STRING,sdsnew(":")); | |
690 | shared.plus = createObject(REDIS_STRING,sdsnew("+")); | |
691 | shared.select0 = createStringObject("select 0\r\n",10); | |
692 | shared.select1 = createStringObject("select 1\r\n",10); | |
693 | shared.select2 = createStringObject("select 2\r\n",10); | |
694 | shared.select3 = createStringObject("select 3\r\n",10); | |
695 | shared.select4 = createStringObject("select 4\r\n",10); | |
696 | shared.select5 = createStringObject("select 5\r\n",10); | |
697 | shared.select6 = createStringObject("select 6\r\n",10); | |
698 | shared.select7 = createStringObject("select 7\r\n",10); | |
699 | shared.select8 = createStringObject("select 8\r\n",10); | |
700 | shared.select9 = createStringObject("select 9\r\n",10); | |
701 | shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); | |
702 | shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); | |
703 | shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); | |
704 | shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); | |
705 | shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); | |
706 | shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); | |
707 | shared.mbulk3 = createStringObject("*3\r\n",4); | |
708 | shared.mbulk4 = createStringObject("*4\r\n",4); | |
709 | for (j = 0; j < REDIS_SHARED_INTEGERS; j++) { | |
710 | shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j); | |
711 | shared.integers[j]->encoding = REDIS_ENCODING_INT; | |
712 | } | |
713 | } | |
714 | ||
715 | void initServerConfig() { | |
716 | server.dbnum = REDIS_DEFAULT_DBNUM; | |
717 | server.port = REDIS_SERVERPORT; | |
718 | server.verbosity = REDIS_VERBOSE; | |
719 | server.maxidletime = REDIS_MAXIDLETIME; | |
720 | server.saveparams = NULL; | |
721 | server.logfile = NULL; /* NULL = log on standard output */ | |
722 | server.bindaddr = NULL; | |
723 | server.glueoutputbuf = 1; | |
724 | server.daemonize = 0; | |
725 | server.appendonly = 0; | |
726 | server.appendfsync = APPENDFSYNC_EVERYSEC; | |
727 | server.no_appendfsync_on_rewrite = 0; | |
728 | server.lastfsync = time(NULL); | |
729 | server.appendfd = -1; | |
730 | server.appendseldb = -1; /* Make sure the first time will not match */ | |
731 | server.pidfile = zstrdup("/var/run/redis.pid"); | |
732 | server.dbfilename = zstrdup("dump.rdb"); | |
733 | server.appendfilename = zstrdup("appendonly.aof"); | |
734 | server.requirepass = NULL; | |
735 | server.rdbcompression = 1; | |
736 | server.activerehashing = 1; | |
737 | server.maxclients = 0; | |
738 | server.blpop_blocked_clients = 0; | |
739 | server.maxmemory = 0; | |
740 | server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU; | |
741 | server.maxmemory_samples = 3; | |
742 | server.vm_enabled = 0; | |
743 | server.vm_swap_file = zstrdup("/tmp/redis-%p.vm"); | |
744 | server.vm_page_size = 256; /* 256 bytes per page */ | |
745 | server.vm_pages = 1024*1024*100; /* 104 millions of pages */ | |
746 | server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */ | |
747 | server.vm_max_threads = 4; | |
748 | server.vm_blocked_clients = 0; | |
749 | server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES; | |
750 | server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE; | |
751 | server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES; | |
752 | server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE; | |
753 | server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES; | |
754 | server.shutdown_asap = 0; | |
755 | ||
756 | updateLRUClock(); | |
757 | resetServerSaveParams(); | |
758 | ||
759 | appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ | |
760 | appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ | |
761 | appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ | |
762 | /* Replication related */ | |
763 | server.isslave = 0; | |
764 | server.masterauth = NULL; | |
765 | server.masterhost = NULL; | |
766 | server.masterport = 6379; | |
767 | server.master = NULL; | |
768 | server.replstate = REDIS_REPL_NONE; | |
769 | ||
770 | /* Double constants initialization */ | |
771 | R_Zero = 0.0; | |
772 | R_PosInf = 1.0/R_Zero; | |
773 | R_NegInf = -1.0/R_Zero; | |
774 | R_Nan = R_Zero/R_Zero; | |
775 | } | |
776 | ||
777 | void initServer() { | |
778 | int j; | |
779 | ||
780 | signal(SIGHUP, SIG_IGN); | |
781 | signal(SIGPIPE, SIG_IGN); | |
782 | setupSigSegvAction(); | |
783 | ||
784 | server.mainthread = pthread_self(); | |
785 | server.devnull = fopen("/dev/null","w"); | |
786 | if (server.devnull == NULL) { | |
787 | redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr); | |
788 | exit(1); | |
789 | } | |
790 | server.clients = listCreate(); | |
791 | server.slaves = listCreate(); | |
792 | server.monitors = listCreate(); | |
793 | server.objfreelist = listCreate(); | |
794 | createSharedObjects(); | |
795 | server.el = aeCreateEventLoop(); | |
796 | server.db = zmalloc(sizeof(redisDb)*server.dbnum); | |
797 | server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr); | |
798 | if (server.fd == -1) { | |
799 | redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr); | |
800 | exit(1); | |
801 | } | |
802 | for (j = 0; j < server.dbnum; j++) { | |
803 | server.db[j].dict = dictCreate(&dbDictType,NULL); | |
804 | server.db[j].expires = dictCreate(&keyptrDictType,NULL); | |
805 | server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); | |
806 | server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); | |
807 | if (server.vm_enabled) | |
808 | server.db[j].io_keys = dictCreate(&keylistDictType,NULL); | |
809 | server.db[j].id = j; | |
810 | } | |
811 | server.pubsub_channels = dictCreate(&keylistDictType,NULL); | |
812 | server.pubsub_patterns = listCreate(); | |
813 | listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); | |
814 | listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); | |
815 | server.cronloops = 0; | |
816 | server.bgsavechildpid = -1; | |
817 | server.bgrewritechildpid = -1; | |
818 | server.bgrewritebuf = sdsempty(); | |
819 | server.aofbuf = sdsempty(); | |
820 | server.lastsave = time(NULL); | |
821 | server.dirty = 0; | |
822 | server.stat_numcommands = 0; | |
823 | server.stat_numconnections = 0; | |
824 | server.stat_expiredkeys = 0; | |
825 | server.stat_starttime = time(NULL); | |
826 | server.stat_keyspace_misses = 0; | |
827 | server.stat_keyspace_hits = 0; | |
828 | server.unixtime = time(NULL); | |
829 | aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL); | |
830 | if (aeCreateFileEvent(server.el, server.fd, AE_READABLE, | |
831 | acceptHandler, NULL) == AE_ERR) oom("creating file event"); | |
832 | ||
833 | if (server.appendonly) { | |
834 | server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644); | |
835 | if (server.appendfd == -1) { | |
836 | redisLog(REDIS_WARNING, "Can't open the append-only file: %s", | |
837 | strerror(errno)); | |
838 | exit(1); | |
839 | } | |
840 | } | |
841 | ||
842 | if (server.vm_enabled) vmInit(); | |
843 | } | |
844 | ||
845 | int qsortRedisCommands(const void *r1, const void *r2) { | |
846 | return strcasecmp( | |
847 | ((struct redisCommand*)r1)->name, | |
848 | ((struct redisCommand*)r2)->name); | |
849 | } | |
850 | ||
851 | void sortCommandTable() { | |
852 | /* Copy and sort the read-only version of the command table */ | |
853 | commandTable = (struct redisCommand*)zmalloc(sizeof(readonlyCommandTable)); | |
854 | memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable)); | |
855 | qsort(commandTable, | |
856 | sizeof(readonlyCommandTable)/sizeof(struct redisCommand), | |
857 | sizeof(struct redisCommand),qsortRedisCommands); | |
858 | } | |
859 | ||
860 | /* ====================== Commands lookup and execution ===================== */ | |
861 | ||
862 | struct redisCommand *lookupCommand(char *name) { | |
863 | struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0}; | |
864 | return bsearch( | |
865 | &tmp, | |
866 | commandTable, | |
867 | sizeof(readonlyCommandTable)/sizeof(struct redisCommand), | |
868 | sizeof(struct redisCommand), | |
869 | qsortRedisCommands); | |
870 | } | |
871 | ||
872 | /* Call() is the core of Redis execution of a command */ | |
873 | void call(redisClient *c, struct redisCommand *cmd) { | |
874 | long long dirty; | |
875 | ||
876 | dirty = server.dirty; | |
877 | cmd->proc(c); | |
878 | dirty = server.dirty-dirty; | |
879 | ||
880 | if (server.appendonly && dirty) | |
881 | feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc); | |
882 | if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) && | |
883 | listLength(server.slaves)) | |
884 | replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc); | |
885 | if (listLength(server.monitors)) | |
886 | replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc); | |
887 | server.stat_numcommands++; | |
888 | } | |
889 | ||
890 | /* If this function gets called we already read a whole | |
891 | * command, argments are in the client argv/argc fields. | |
892 | * processCommand() execute the command or prepare the | |
893 | * server for a bulk read from the client. | |
894 | * | |
895 | * If 1 is returned the client is still alive and valid and | |
896 | * and other operations can be performed by the caller. Otherwise | |
897 | * if 0 is returned the client was destroied (i.e. after QUIT). */ | |
898 | int processCommand(redisClient *c) { | |
899 | struct redisCommand *cmd; | |
900 | ||
901 | /* Handle the multi bulk command type. This is an alternative protocol | |
902 | * supported by Redis in order to receive commands that are composed of | |
903 | * multiple binary-safe "bulk" arguments. The latency of processing is | |
904 | * a bit higher but this allows things like multi-sets, so if this | |
905 | * protocol is used only for MSET and similar commands this is a big win. */ | |
906 | if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') { | |
907 | c->multibulk = atoi(((char*)c->argv[0]->ptr)+1); | |
908 | if (c->multibulk <= 0) { | |
909 | resetClient(c); | |
910 | return 1; | |
911 | } else { | |
912 | decrRefCount(c->argv[c->argc-1]); | |
913 | c->argc--; | |
914 | return 1; | |
915 | } | |
916 | } else if (c->multibulk) { | |
917 | if (c->bulklen == -1) { | |
918 | if (((char*)c->argv[0]->ptr)[0] != '$') { | |
919 | addReplyError(c,"multi bulk protocol error"); | |
920 | resetClient(c); | |
921 | return 1; | |
922 | } else { | |
923 | char *eptr; | |
924 | long bulklen = strtol(((char*)c->argv[0]->ptr)+1,&eptr,10); | |
925 | int perr = eptr[0] != '\0'; | |
926 | ||
927 | decrRefCount(c->argv[0]); | |
928 | if (perr || bulklen == LONG_MIN || bulklen == LONG_MAX || | |
929 | bulklen < 0 || bulklen > 1024*1024*1024) | |
930 | { | |
931 | c->argc--; | |
932 | addReplyError(c,"invalid bulk write count"); | |
933 | resetClient(c); | |
934 | return 1; | |
935 | } | |
936 | c->argc--; | |
937 | c->bulklen = bulklen+2; /* add two bytes for CR+LF */ | |
938 | return 1; | |
939 | } | |
940 | } else { | |
941 | c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1)); | |
942 | c->mbargv[c->mbargc] = c->argv[0]; | |
943 | c->mbargc++; | |
944 | c->argc--; | |
945 | c->multibulk--; | |
946 | if (c->multibulk == 0) { | |
947 | robj **auxargv; | |
948 | int auxargc; | |
949 | ||
950 | /* Here we need to swap the multi-bulk argc/argv with the | |
951 | * normal argc/argv of the client structure. */ | |
952 | auxargv = c->argv; | |
953 | c->argv = c->mbargv; | |
954 | c->mbargv = auxargv; | |
955 | ||
956 | auxargc = c->argc; | |
957 | c->argc = c->mbargc; | |
958 | c->mbargc = auxargc; | |
959 | ||
960 | /* We need to set bulklen to something different than -1 | |
961 | * in order for the code below to process the command without | |
962 | * to try to read the last argument of a bulk command as | |
963 | * a special argument. */ | |
964 | c->bulklen = 0; | |
965 | /* continue below and process the command */ | |
966 | } else { | |
967 | c->bulklen = -1; | |
968 | return 1; | |
969 | } | |
970 | } | |
971 | } | |
972 | /* -- end of multi bulk commands processing -- */ | |
973 | ||
974 | /* The QUIT command is handled as a special case. Normal command | |
975 | * procs are unable to close the client connection safely */ | |
976 | if (!strcasecmp(c->argv[0]->ptr,"quit")) { | |
977 | freeClient(c); | |
978 | return 0; | |
979 | } | |
980 | ||
981 | /* Now lookup the command and check ASAP about trivial error conditions | |
982 | * such wrong arity, bad command name and so forth. */ | |
983 | cmd = lookupCommand(c->argv[0]->ptr); | |
984 | if (!cmd) { | |
985 | addReplyErrorFormat(c,"unknown command '%s'", | |
986 | (char*)c->argv[0]->ptr); | |
987 | resetClient(c); | |
988 | return 1; | |
989 | } else if ((cmd->arity > 0 && cmd->arity != c->argc) || | |
990 | (c->argc < -cmd->arity)) { | |
991 | addReplyErrorFormat(c,"wrong number of arguments for '%s' command", | |
992 | cmd->name); | |
993 | resetClient(c); | |
994 | return 1; | |
995 | } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) { | |
996 | /* This is a bulk command, we have to read the last argument yet. */ | |
997 | char *eptr; | |
998 | long bulklen = strtol(c->argv[c->argc-1]->ptr,&eptr,10); | |
999 | int perr = eptr[0] != '\0'; | |
1000 | ||
1001 | decrRefCount(c->argv[c->argc-1]); | |
1002 | if (perr || bulklen == LONG_MAX || bulklen == LONG_MIN || | |
1003 | bulklen < 0 || bulklen > 1024*1024*1024) | |
1004 | { | |
1005 | c->argc--; | |
1006 | addReplyError(c,"invalid bulk write count"); | |
1007 | resetClient(c); | |
1008 | return 1; | |
1009 | } | |
1010 | c->argc--; | |
1011 | c->bulklen = bulklen+2; /* add two bytes for CR+LF */ | |
1012 | /* It is possible that the bulk read is already in the | |
1013 | * buffer. Check this condition and handle it accordingly. | |
1014 | * This is just a fast path, alternative to call processInputBuffer(). | |
1015 | * It's a good idea since the code is small and this condition | |
1016 | * happens most of the times. */ | |
1017 | if ((signed)sdslen(c->querybuf) >= c->bulklen) { | |
1018 | c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2); | |
1019 | c->argc++; | |
1020 | c->querybuf = sdsrange(c->querybuf,c->bulklen,-1); | |
1021 | } else { | |
1022 | /* Otherwise return... there is to read the last argument | |
1023 | * from the socket. */ | |
1024 | return 1; | |
1025 | } | |
1026 | } | |
1027 | /* Let's try to encode the bulk object to save space. */ | |
1028 | if (cmd->flags & REDIS_CMD_BULK) | |
1029 | c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]); | |
1030 | ||
1031 | /* Check if the user is authenticated */ | |
1032 | if (server.requirepass && !c->authenticated && cmd->proc != authCommand) { | |
1033 | addReplyError(c,"operation not permitted"); | |
1034 | resetClient(c); | |
1035 | return 1; | |
1036 | } | |
1037 | ||
1038 | /* Handle the maxmemory directive. | |
1039 | * | |
1040 | * First we try to free some memory if possible (if there are volatile | |
1041 | * keys in the dataset). If there are not the only thing we can do | |
1042 | * is returning an error. */ | |
1043 | if (server.maxmemory) freeMemoryIfNeeded(); | |
1044 | if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) && | |
1045 | zmalloc_used_memory() > server.maxmemory) | |
1046 | { | |
1047 | addReplyError(c,"command not allowed when used memory > 'maxmemory'"); | |
1048 | resetClient(c); | |
1049 | return 1; | |
1050 | } | |
1051 | ||
1052 | /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ | |
1053 | if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0) | |
1054 | && | |
1055 | cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand && | |
1056 | cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) { | |
1057 | addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context"); | |
1058 | resetClient(c); | |
1059 | return 1; | |
1060 | } | |
1061 | ||
1062 | /* Exec the command */ | |
1063 | if (c->flags & REDIS_MULTI && | |
1064 | cmd->proc != execCommand && cmd->proc != discardCommand && | |
1065 | cmd->proc != multiCommand && cmd->proc != watchCommand) | |
1066 | { | |
1067 | queueMultiCommand(c,cmd); | |
1068 | addReply(c,shared.queued); | |
1069 | } else { | |
1070 | if (server.vm_enabled && server.vm_max_threads > 0 && | |
1071 | blockClientOnSwappedKeys(c,cmd)) return 1; | |
1072 | call(c,cmd); | |
1073 | } | |
1074 | ||
1075 | /* Prepare the client for the next command */ | |
1076 | resetClient(c); | |
1077 | return 1; | |
1078 | } | |
1079 | ||
1080 | /*================================== Shutdown =============================== */ | |
1081 | ||
1082 | int prepareForShutdown() { | |
1083 | redisLog(REDIS_WARNING,"User requested shutdown, saving DB..."); | |
1084 | /* Kill the saving child if there is a background saving in progress. | |
1085 | We want to avoid race conditions, for instance our saving child may | |
1086 | overwrite the synchronous saving did by SHUTDOWN. */ | |
1087 | if (server.bgsavechildpid != -1) { | |
1088 | redisLog(REDIS_WARNING,"There is a live saving child. Killing it!"); | |
1089 | kill(server.bgsavechildpid,SIGKILL); | |
1090 | rdbRemoveTempFile(server.bgsavechildpid); | |
1091 | } | |
1092 | if (server.appendonly) { | |
1093 | /* Append only file: fsync() the AOF and exit */ | |
1094 | aof_fsync(server.appendfd); | |
1095 | if (server.vm_enabled) unlink(server.vm_swap_file); | |
1096 | } else if (server.saveparamslen > 0) { | |
1097 | /* Snapshotting. Perform a SYNC SAVE and exit */ | |
1098 | if (rdbSave(server.dbfilename) != REDIS_OK) { | |
1099 | /* Ooops.. error saving! The best we can do is to continue | |
1100 | * operating. Note that if there was a background saving process, | |
1101 | * in the next cron() Redis will be notified that the background | |
1102 | * saving aborted, handling special stuff like slaves pending for | |
1103 | * synchronization... */ | |
1104 | redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit"); | |
1105 | return REDIS_ERR; | |
1106 | } | |
1107 | } else { | |
1108 | redisLog(REDIS_WARNING,"Not saving DB."); | |
1109 | } | |
1110 | if (server.daemonize) unlink(server.pidfile); | |
1111 | redisLog(REDIS_WARNING,"Server exit now, bye bye..."); | |
1112 | return REDIS_OK; | |
1113 | } | |
1114 | ||
1115 | /*================================== Commands =============================== */ | |
1116 | ||
1117 | void authCommand(redisClient *c) { | |
1118 | if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) { | |
1119 | c->authenticated = 1; | |
1120 | addReply(c,shared.ok); | |
1121 | } else { | |
1122 | c->authenticated = 0; | |
1123 | addReplyError(c,"invalid password"); | |
1124 | } | |
1125 | } | |
1126 | ||
1127 | void pingCommand(redisClient *c) { | |
1128 | addReply(c,shared.pong); | |
1129 | } | |
1130 | ||
1131 | void echoCommand(redisClient *c) { | |
1132 | addReplyBulk(c,c->argv[1]); | |
1133 | } | |
1134 | ||
1135 | /* Convert an amount of bytes into a human readable string in the form | |
1136 | * of 100B, 2G, 100M, 4K, and so forth. */ | |
1137 | void bytesToHuman(char *s, unsigned long long n) { | |
1138 | double d; | |
1139 | ||
1140 | if (n < 1024) { | |
1141 | /* Bytes */ | |
1142 | sprintf(s,"%lluB",n); | |
1143 | return; | |
1144 | } else if (n < (1024*1024)) { | |
1145 | d = (double)n/(1024); | |
1146 | sprintf(s,"%.2fK",d); | |
1147 | } else if (n < (1024LL*1024*1024)) { | |
1148 | d = (double)n/(1024*1024); | |
1149 | sprintf(s,"%.2fM",d); | |
1150 | } else if (n < (1024LL*1024*1024*1024)) { | |
1151 | d = (double)n/(1024LL*1024*1024); | |
1152 | sprintf(s,"%.2fG",d); | |
1153 | } | |
1154 | } | |
1155 | ||
1156 | /* Create the string returned by the INFO command. This is decoupled | |
1157 | * by the INFO command itself as we need to report the same information | |
1158 | * on memory corruption problems. */ | |
1159 | sds genRedisInfoString(void) { | |
1160 | sds info; | |
1161 | time_t uptime = time(NULL)-server.stat_starttime; | |
1162 | int j; | |
1163 | char hmem[64]; | |
1164 | struct rusage self_ru, c_ru; | |
1165 | ||
1166 | getrusage(RUSAGE_SELF, &self_ru); | |
1167 | getrusage(RUSAGE_CHILDREN, &c_ru); | |
1168 | ||
1169 | bytesToHuman(hmem,zmalloc_used_memory()); | |
1170 | info = sdscatprintf(sdsempty(), | |
1171 | "redis_version:%s\r\n" | |
1172 | "redis_git_sha1:%s\r\n" | |
1173 | "redis_git_dirty:%d\r\n" | |
1174 | "arch_bits:%s\r\n" | |
1175 | "multiplexing_api:%s\r\n" | |
1176 | "process_id:%ld\r\n" | |
1177 | "uptime_in_seconds:%ld\r\n" | |
1178 | "uptime_in_days:%ld\r\n" | |
1179 | "lru_clock:%ld\r\n" | |
1180 | "used_cpu_sys:%.2f\r\n" | |
1181 | "used_cpu_user:%.2f\r\n" | |
1182 | "used_cpu_sys_childrens:%.2f\r\n" | |
1183 | "used_cpu_user_childrens:%.2f\r\n" | |
1184 | "connected_clients:%d\r\n" | |
1185 | "connected_slaves:%d\r\n" | |
1186 | "blocked_clients:%d\r\n" | |
1187 | "used_memory:%zu\r\n" | |
1188 | "used_memory_human:%s\r\n" | |
1189 | "mem_fragmentation_ratio:%.2f\r\n" | |
1190 | "use_tcmalloc:%d\r\n" | |
1191 | "changes_since_last_save:%lld\r\n" | |
1192 | "bgsave_in_progress:%d\r\n" | |
1193 | "last_save_time:%ld\r\n" | |
1194 | "bgrewriteaof_in_progress:%d\r\n" | |
1195 | "total_connections_received:%lld\r\n" | |
1196 | "total_commands_processed:%lld\r\n" | |
1197 | "expired_keys:%lld\r\n" | |
1198 | "keyspace_hits:%lld\r\n" | |
1199 | "keyspace_misses:%lld\r\n" | |
1200 | "hash_max_zipmap_entries:%zu\r\n" | |
1201 | "hash_max_zipmap_value:%zu\r\n" | |
1202 | "pubsub_channels:%ld\r\n" | |
1203 | "pubsub_patterns:%u\r\n" | |
1204 | "vm_enabled:%d\r\n" | |
1205 | "role:%s\r\n" | |
1206 | ,REDIS_VERSION, | |
1207 | redisGitSHA1(), | |
1208 | strtol(redisGitDirty(),NULL,10) > 0, | |
1209 | (sizeof(long) == 8) ? "64" : "32", | |
1210 | aeGetApiName(), | |
1211 | (long) getpid(), | |
1212 | uptime, | |
1213 | uptime/(3600*24), | |
1214 | (unsigned long) server.lruclock, | |
1215 | (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000, | |
1216 | (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000, | |
1217 | (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000, | |
1218 | (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000, | |
1219 | listLength(server.clients)-listLength(server.slaves), | |
1220 | listLength(server.slaves), | |
1221 | server.blpop_blocked_clients, | |
1222 | zmalloc_used_memory(), | |
1223 | hmem, | |
1224 | zmalloc_get_fragmentation_ratio(), | |
1225 | #ifdef USE_TCMALLOC | |
1226 | 1, | |
1227 | #else | |
1228 | 0, | |
1229 | #endif | |
1230 | server.dirty, | |
1231 | server.bgsavechildpid != -1, | |
1232 | server.lastsave, | |
1233 | server.bgrewritechildpid != -1, | |
1234 | server.stat_numconnections, | |
1235 | server.stat_numcommands, | |
1236 | server.stat_expiredkeys, | |
1237 | server.stat_keyspace_hits, | |
1238 | server.stat_keyspace_misses, | |
1239 | server.hash_max_zipmap_entries, | |
1240 | server.hash_max_zipmap_value, | |
1241 | dictSize(server.pubsub_channels), | |
1242 | listLength(server.pubsub_patterns), | |
1243 | server.vm_enabled != 0, | |
1244 | server.masterhost == NULL ? "master" : "slave" | |
1245 | ); | |
1246 | if (server.masterhost) { | |
1247 | info = sdscatprintf(info, | |
1248 | "master_host:%s\r\n" | |
1249 | "master_port:%d\r\n" | |
1250 | "master_link_status:%s\r\n" | |
1251 | "master_last_io_seconds_ago:%d\r\n" | |
1252 | ,server.masterhost, | |
1253 | server.masterport, | |
1254 | (server.replstate == REDIS_REPL_CONNECTED) ? | |
1255 | "up" : "down", | |
1256 | server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1 | |
1257 | ); | |
1258 | } | |
1259 | if (server.vm_enabled) { | |
1260 | lockThreadedIO(); | |
1261 | info = sdscatprintf(info, | |
1262 | "vm_conf_max_memory:%llu\r\n" | |
1263 | "vm_conf_page_size:%llu\r\n" | |
1264 | "vm_conf_pages:%llu\r\n" | |
1265 | "vm_stats_used_pages:%llu\r\n" | |
1266 | "vm_stats_swapped_objects:%llu\r\n" | |
1267 | "vm_stats_swappin_count:%llu\r\n" | |
1268 | "vm_stats_swappout_count:%llu\r\n" | |
1269 | "vm_stats_io_newjobs_len:%lu\r\n" | |
1270 | "vm_stats_io_processing_len:%lu\r\n" | |
1271 | "vm_stats_io_processed_len:%lu\r\n" | |
1272 | "vm_stats_io_active_threads:%lu\r\n" | |
1273 | "vm_stats_blocked_clients:%lu\r\n" | |
1274 | ,(unsigned long long) server.vm_max_memory, | |
1275 | (unsigned long long) server.vm_page_size, | |
1276 | (unsigned long long) server.vm_pages, | |
1277 | (unsigned long long) server.vm_stats_used_pages, | |
1278 | (unsigned long long) server.vm_stats_swapped_objects, | |
1279 | (unsigned long long) server.vm_stats_swapins, | |
1280 | (unsigned long long) server.vm_stats_swapouts, | |
1281 | (unsigned long) listLength(server.io_newjobs), | |
1282 | (unsigned long) listLength(server.io_processing), | |
1283 | (unsigned long) listLength(server.io_processed), | |
1284 | (unsigned long) server.io_active_threads, | |
1285 | (unsigned long) server.vm_blocked_clients | |
1286 | ); | |
1287 | unlockThreadedIO(); | |
1288 | } | |
1289 | for (j = 0; j < server.dbnum; j++) { | |
1290 | long long keys, vkeys; | |
1291 | ||
1292 | keys = dictSize(server.db[j].dict); | |
1293 | vkeys = dictSize(server.db[j].expires); | |
1294 | if (keys || vkeys) { | |
1295 | info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n", | |
1296 | j, keys, vkeys); | |
1297 | } | |
1298 | } | |
1299 | return info; | |
1300 | } | |
1301 | ||
1302 | void infoCommand(redisClient *c) { | |
1303 | sds info = genRedisInfoString(); | |
1304 | addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n", | |
1305 | (unsigned long)sdslen(info))); | |
1306 | addReplySds(c,info); | |
1307 | addReply(c,shared.crlf); | |
1308 | } | |
1309 | ||
1310 | void monitorCommand(redisClient *c) { | |
1311 | /* ignore MONITOR if aleady slave or in monitor mode */ | |
1312 | if (c->flags & REDIS_SLAVE) return; | |
1313 | ||
1314 | c->flags |= (REDIS_SLAVE|REDIS_MONITOR); | |
1315 | c->slaveseldb = 0; | |
1316 | listAddNodeTail(server.monitors,c); | |
1317 | addReply(c,shared.ok); | |
1318 | } | |
1319 | ||
1320 | /* ============================ Maxmemory directive ======================== */ | |
1321 | ||
1322 | /* Try to free one object form the pre-allocated objects free list. | |
1323 | * This is useful under low mem conditions as by default we take 1 million | |
1324 | * free objects allocated. On success REDIS_OK is returned, otherwise | |
1325 | * REDIS_ERR. */ | |
1326 | int tryFreeOneObjectFromFreelist(void) { | |
1327 | robj *o; | |
1328 | ||
1329 | if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex); | |
1330 | if (listLength(server.objfreelist)) { | |
1331 | listNode *head = listFirst(server.objfreelist); | |
1332 | o = listNodeValue(head); | |
1333 | listDelNode(server.objfreelist,head); | |
1334 | if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex); | |
1335 | zfree(o); | |
1336 | return REDIS_OK; | |
1337 | } else { | |
1338 | if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex); | |
1339 | return REDIS_ERR; | |
1340 | } | |
1341 | } | |
1342 | ||
1343 | /* This function gets called when 'maxmemory' is set on the config file to limit | |
1344 | * the max memory used by the server, and we are out of memory. | |
1345 | * This function will try to, in order: | |
1346 | * | |
1347 | * - Free objects from the free list | |
1348 | * - Try to remove keys with an EXPIRE set | |
1349 | * | |
1350 | * It is not possible to free enough memory to reach used-memory < maxmemory | |
1351 | * the server will start refusing commands that will enlarge even more the | |
1352 | * memory usage. | |
1353 | */ | |
1354 | void freeMemoryIfNeeded(void) { | |
1355 | /* Remove keys accordingly to the active policy as long as we are | |
1356 | * over the memory limit. */ | |
1357 | while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) { | |
1358 | int j, k, freed = 0; | |
1359 | ||
1360 | /* Basic strategy -- remove objects from the free list. */ | |
1361 | if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue; | |
1362 | ||
1363 | for (j = 0; j < server.dbnum; j++) { | |
1364 | long bestval; | |
1365 | sds bestkey = NULL; | |
1366 | struct dictEntry *de; | |
1367 | redisDb *db = server.db+j; | |
1368 | dict *dict; | |
1369 | ||
1370 | if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || | |
1371 | server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM) | |
1372 | { | |
1373 | dict = server.db[j].dict; | |
1374 | } else { | |
1375 | dict = server.db[j].expires; | |
1376 | } | |
1377 | if (dictSize(dict) == 0) continue; | |
1378 | ||
1379 | /* volatile-random and allkeys-random policy */ | |
1380 | if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM || | |
1381 | server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM) | |
1382 | { | |
1383 | de = dictGetRandomKey(dict); | |
1384 | bestkey = dictGetEntryKey(de); | |
1385 | } | |
1386 | ||
1387 | /* volatile-lru and allkeys-lru policy */ | |
1388 | else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || | |
1389 | server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU) | |
1390 | { | |
1391 | for (k = 0; k < server.maxmemory_samples; k++) { | |
1392 | sds thiskey; | |
1393 | long thisval; | |
1394 | robj *o; | |
1395 | ||
1396 | de = dictGetRandomKey(dict); | |
1397 | thiskey = dictGetEntryKey(de); | |
1398 | o = dictGetEntryVal(de); | |
1399 | thisval = estimateObjectIdleTime(o); | |
1400 | ||
1401 | /* Higher idle time is better candidate for deletion */ | |
1402 | if (bestkey == NULL || thisval > bestval) { | |
1403 | bestkey = thiskey; | |
1404 | bestval = thisval; | |
1405 | } | |
1406 | } | |
1407 | } | |
1408 | ||
1409 | /* volatile-ttl */ | |
1410 | else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) { | |
1411 | for (k = 0; k < server.maxmemory_samples; k++) { | |
1412 | sds thiskey; | |
1413 | long thisval; | |
1414 | ||
1415 | de = dictGetRandomKey(dict); | |
1416 | thiskey = dictGetEntryKey(de); | |
1417 | thisval = (long) dictGetEntryVal(de); | |
1418 | ||
1419 | /* Expire sooner (minor expire unix timestamp) is better | |
1420 | * candidate for deletion */ | |
1421 | if (bestkey == NULL || thisval < bestval) { | |
1422 | bestkey = thiskey; | |
1423 | bestval = thisval; | |
1424 | } | |
1425 | } | |
1426 | } | |
1427 | ||
1428 | /* Finally remove the selected key. */ | |
1429 | if (bestkey) { | |
1430 | robj *keyobj = createStringObject(bestkey,sdslen(bestkey)); | |
1431 | dbDelete(db,keyobj); | |
1432 | server.stat_expiredkeys++; | |
1433 | decrRefCount(keyobj); | |
1434 | freed++; | |
1435 | } | |
1436 | } | |
1437 | if (!freed) return; /* nothing to free... */ | |
1438 | } | |
1439 | ||
1440 | while(0) { | |
1441 | int j, k, freed = 0; | |
1442 | for (j = 0; j < server.dbnum; j++) { | |
1443 | int minttl = -1; | |
1444 | sds minkey = NULL; | |
1445 | robj *keyobj = NULL; | |
1446 | struct dictEntry *de; | |
1447 | ||
1448 | if (dictSize(server.db[j].expires)) { | |
1449 | freed = 1; | |
1450 | /* From a sample of three keys drop the one nearest to | |
1451 | * the natural expire */ | |
1452 | for (k = 0; k < 3; k++) { | |
1453 | time_t t; | |
1454 | ||
1455 | de = dictGetRandomKey(server.db[j].expires); | |
1456 | t = (time_t) dictGetEntryVal(de); | |
1457 | if (minttl == -1 || t < minttl) { | |
1458 | minkey = dictGetEntryKey(de); | |
1459 | minttl = t; | |
1460 | } | |
1461 | } | |
1462 | keyobj = createStringObject(minkey,sdslen(minkey)); | |
1463 | dbDelete(server.db+j,keyobj); | |
1464 | server.stat_expiredkeys++; | |
1465 | decrRefCount(keyobj); | |
1466 | } | |
1467 | } | |
1468 | if (!freed) return; /* nothing to free... */ | |
1469 | } | |
1470 | } | |
1471 | ||
1472 | /* =================================== Main! ================================ */ | |
1473 | ||
1474 | #ifdef __linux__ | |
1475 | int linuxOvercommitMemoryValue(void) { | |
1476 | FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); | |
1477 | char buf[64]; | |
1478 | ||
1479 | if (!fp) return -1; | |
1480 | if (fgets(buf,64,fp) == NULL) { | |
1481 | fclose(fp); | |
1482 | return -1; | |
1483 | } | |
1484 | fclose(fp); | |
1485 | ||
1486 | return atoi(buf); | |
1487 | } | |
1488 | ||
1489 | void linuxOvercommitMemoryWarning(void) { | |
1490 | if (linuxOvercommitMemoryValue() == 0) { | |
1491 | 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."); | |
1492 | } | |
1493 | } | |
1494 | #endif /* __linux__ */ | |
1495 | ||
1496 | void createPidFile(void) { | |
1497 | /* Try to write the pid file in a best-effort way. */ | |
1498 | FILE *fp = fopen(server.pidfile,"w"); | |
1499 | if (fp) { | |
1500 | fprintf(fp,"%d\n",getpid()); | |
1501 | fclose(fp); | |
1502 | } | |
1503 | } | |
1504 | ||
1505 | void daemonize(void) { | |
1506 | int fd; | |
1507 | ||
1508 | if (fork() != 0) exit(0); /* parent exits */ | |
1509 | setsid(); /* create a new session */ | |
1510 | ||
1511 | /* Every output goes to /dev/null. If Redis is daemonized but | |
1512 | * the 'logfile' is set to 'stdout' in the configuration file | |
1513 | * it will not log at all. */ | |
1514 | if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { | |
1515 | dup2(fd, STDIN_FILENO); | |
1516 | dup2(fd, STDOUT_FILENO); | |
1517 | dup2(fd, STDERR_FILENO); | |
1518 | if (fd > STDERR_FILENO) close(fd); | |
1519 | } | |
1520 | } | |
1521 | ||
1522 | void version() { | |
1523 | printf("Redis server version %s (%s:%d)\n", REDIS_VERSION, | |
1524 | redisGitSHA1(), atoi(redisGitDirty()) > 0); | |
1525 | exit(0); | |
1526 | } | |
1527 | ||
1528 | void usage() { | |
1529 | fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n"); | |
1530 | fprintf(stderr," ./redis-server - (read config from stdin)\n"); | |
1531 | exit(1); | |
1532 | } | |
1533 | ||
1534 | int main(int argc, char **argv) { | |
1535 | time_t start; | |
1536 | ||
1537 | initServerConfig(); | |
1538 | sortCommandTable(); | |
1539 | if (argc == 2) { | |
1540 | if (strcmp(argv[1], "-v") == 0 || | |
1541 | strcmp(argv[1], "--version") == 0) version(); | |
1542 | if (strcmp(argv[1], "--help") == 0) usage(); | |
1543 | resetServerSaveParams(); | |
1544 | loadServerConfig(argv[1]); | |
1545 | } else if ((argc > 2)) { | |
1546 | usage(); | |
1547 | } else { | |
1548 | 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'"); | |
1549 | } | |
1550 | if (server.daemonize) daemonize(); | |
1551 | initServer(); | |
1552 | if (server.daemonize) createPidFile(); | |
1553 | redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION); | |
1554 | #ifdef __linux__ | |
1555 | linuxOvercommitMemoryWarning(); | |
1556 | #endif | |
1557 | start = time(NULL); | |
1558 | if (server.appendonly) { | |
1559 | if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK) | |
1560 | redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start); | |
1561 | } else { | |
1562 | if (rdbLoad(server.dbfilename) == REDIS_OK) | |
1563 | redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start); | |
1564 | } | |
1565 | redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port); | |
1566 | aeSetBeforeSleepProc(server.el,beforeSleep); | |
1567 | aeMain(server.el); | |
1568 | aeDeleteEventLoop(server.el); | |
1569 | return 0; | |
1570 | } | |
1571 | ||
1572 | /* ============================= Backtrace support ========================= */ | |
1573 | ||
1574 | #ifdef HAVE_BACKTRACE | |
1575 | void *getMcontextEip(ucontext_t *uc) { | |
1576 | #if defined(__FreeBSD__) | |
1577 | return (void*) uc->uc_mcontext.mc_eip; | |
1578 | #elif defined(__dietlibc__) | |
1579 | return (void*) uc->uc_mcontext.eip; | |
1580 | #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6) | |
1581 | #if __x86_64__ | |
1582 | return (void*) uc->uc_mcontext->__ss.__rip; | |
1583 | #else | |
1584 | return (void*) uc->uc_mcontext->__ss.__eip; | |
1585 | #endif | |
1586 | #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) | |
1587 | #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) | |
1588 | return (void*) uc->uc_mcontext->__ss.__rip; | |
1589 | #else | |
1590 | return (void*) uc->uc_mcontext->__ss.__eip; | |
1591 | #endif | |
1592 | #elif defined(__i386__) | |
1593 | return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */ | |
1594 | #elif defined(__X86_64__) || defined(__x86_64__) | |
1595 | return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */ | |
1596 | #elif defined(__ia64__) /* Linux IA64 */ | |
1597 | return (void*) uc->uc_mcontext.sc_ip; | |
1598 | #else | |
1599 | return NULL; | |
1600 | #endif | |
1601 | } | |
1602 | ||
1603 | void segvHandler(int sig, siginfo_t *info, void *secret) { | |
1604 | void *trace[100]; | |
1605 | char **messages = NULL; | |
1606 | int i, trace_size = 0; | |
1607 | ucontext_t *uc = (ucontext_t*) secret; | |
1608 | sds infostring; | |
1609 | REDIS_NOTUSED(info); | |
1610 | ||
1611 | redisLog(REDIS_WARNING, | |
1612 | "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig); | |
1613 | infostring = genRedisInfoString(); | |
1614 | redisLog(REDIS_WARNING, "%s",infostring); | |
1615 | /* It's not safe to sdsfree() the returned string under memory | |
1616 | * corruption conditions. Let it leak as we are going to abort */ | |
1617 | ||
1618 | trace_size = backtrace(trace, 100); | |
1619 | /* overwrite sigaction with caller's address */ | |
1620 | if (getMcontextEip(uc) != NULL) { | |
1621 | trace[1] = getMcontextEip(uc); | |
1622 | } | |
1623 | messages = backtrace_symbols(trace, trace_size); | |
1624 | ||
1625 | for (i=1; i<trace_size; ++i) | |
1626 | redisLog(REDIS_WARNING,"%s", messages[i]); | |
1627 | ||
1628 | /* free(messages); Don't call free() with possibly corrupted memory. */ | |
1629 | if (server.daemonize) unlink(server.pidfile); | |
1630 | _exit(0); | |
1631 | } | |
1632 | ||
1633 | void sigtermHandler(int sig) { | |
1634 | REDIS_NOTUSED(sig); | |
1635 | ||
1636 | redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down..."); | |
1637 | server.shutdown_asap = 1; | |
1638 | } | |
1639 | ||
1640 | void setupSigSegvAction(void) { | |
1641 | struct sigaction act; | |
1642 | ||
1643 | sigemptyset (&act.sa_mask); | |
1644 | /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction | |
1645 | * is used. Otherwise, sa_handler is used */ | |
1646 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO; | |
1647 | act.sa_sigaction = segvHandler; | |
1648 | sigaction (SIGSEGV, &act, NULL); | |
1649 | sigaction (SIGBUS, &act, NULL); | |
1650 | sigaction (SIGFPE, &act, NULL); | |
1651 | sigaction (SIGILL, &act, NULL); | |
1652 | sigaction (SIGBUS, &act, NULL); | |
1653 | ||
1654 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND; | |
1655 | act.sa_handler = sigtermHandler; | |
1656 | sigaction (SIGTERM, &act, NULL); | |
1657 | return; | |
1658 | } | |
1659 | ||
1660 | #else /* HAVE_BACKTRACE */ | |
1661 | void setupSigSegvAction(void) { | |
1662 | } | |
1663 | #endif /* HAVE_BACKTRACE */ | |
1664 | ||
1665 | /* The End */ |