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