]>
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}, | |
127 | {"zscore",zscoreCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1}, | |
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 | ||
255 | void dictRedisObjectDestructor(void *privdata, void *val) | |
256 | { | |
257 | DICT_NOTUSED(privdata); | |
258 | ||
259 | if (val == NULL) return; /* Values of swapped out keys as set to NULL */ | |
260 | decrRefCount(val); | |
261 | } | |
262 | ||
263 | void dictSdsDestructor(void *privdata, void *val) | |
264 | { | |
265 | DICT_NOTUSED(privdata); | |
266 | ||
267 | sdsfree(val); | |
268 | } | |
269 | ||
270 | int dictObjKeyCompare(void *privdata, const void *key1, | |
271 | const void *key2) | |
272 | { | |
273 | const robj *o1 = key1, *o2 = key2; | |
274 | return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); | |
275 | } | |
276 | ||
277 | unsigned int dictObjHash(const void *key) { | |
278 | const robj *o = key; | |
279 | return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
280 | } | |
281 | ||
282 | unsigned int dictSdsHash(const void *key) { | |
283 | return dictGenHashFunction((unsigned char*)key, sdslen((char*)key)); | |
284 | } | |
285 | ||
286 | int dictEncObjKeyCompare(void *privdata, const void *key1, | |
287 | const void *key2) | |
288 | { | |
289 | robj *o1 = (robj*) key1, *o2 = (robj*) key2; | |
290 | int cmp; | |
291 | ||
292 | if (o1->encoding == REDIS_ENCODING_INT && | |
293 | o2->encoding == REDIS_ENCODING_INT) | |
294 | return o1->ptr == o2->ptr; | |
295 | ||
296 | o1 = getDecodedObject(o1); | |
297 | o2 = getDecodedObject(o2); | |
298 | cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); | |
299 | decrRefCount(o1); | |
300 | decrRefCount(o2); | |
301 | return cmp; | |
302 | } | |
303 | ||
304 | unsigned int dictEncObjHash(const void *key) { | |
305 | robj *o = (robj*) key; | |
306 | ||
307 | if (o->encoding == REDIS_ENCODING_RAW) { | |
308 | return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
309 | } else { | |
310 | if (o->encoding == REDIS_ENCODING_INT) { | |
311 | char buf[32]; | |
312 | int len; | |
313 | ||
314 | len = ll2string(buf,32,(long)o->ptr); | |
315 | return dictGenHashFunction((unsigned char*)buf, len); | |
316 | } else { | |
317 | unsigned int hash; | |
318 | ||
319 | o = getDecodedObject(o); | |
320 | hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); | |
321 | decrRefCount(o); | |
322 | return hash; | |
323 | } | |
324 | } | |
325 | } | |
326 | ||
327 | /* Sets type */ | |
328 | dictType setDictType = { | |
329 | dictEncObjHash, /* hash function */ | |
330 | NULL, /* key dup */ | |
331 | NULL, /* val dup */ | |
332 | dictEncObjKeyCompare, /* key compare */ | |
333 | dictRedisObjectDestructor, /* key destructor */ | |
334 | NULL /* val destructor */ | |
335 | }; | |
336 | ||
337 | /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ | |
338 | dictType zsetDictType = { | |
339 | dictEncObjHash, /* hash function */ | |
340 | NULL, /* key dup */ | |
341 | NULL, /* val dup */ | |
342 | dictEncObjKeyCompare, /* key compare */ | |
343 | dictRedisObjectDestructor, /* key destructor */ | |
69ef89f2 | 344 | NULL /* val destructor */ |
e2641e09 | 345 | }; |
346 | ||
347 | /* Db->dict, keys are sds strings, vals are Redis objects. */ | |
348 | dictType dbDictType = { | |
349 | dictSdsHash, /* hash function */ | |
350 | NULL, /* key dup */ | |
351 | NULL, /* val dup */ | |
352 | dictSdsKeyCompare, /* key compare */ | |
353 | dictSdsDestructor, /* key destructor */ | |
354 | dictRedisObjectDestructor /* val destructor */ | |
355 | }; | |
356 | ||
357 | /* Db->expires */ | |
358 | dictType keyptrDictType = { | |
359 | dictSdsHash, /* hash function */ | |
360 | NULL, /* key dup */ | |
361 | NULL, /* val dup */ | |
362 | dictSdsKeyCompare, /* key compare */ | |
363 | NULL, /* key destructor */ | |
364 | NULL /* val destructor */ | |
365 | }; | |
366 | ||
367 | /* Hash type hash table (note that small hashes are represented with zimpaps) */ | |
368 | dictType hashDictType = { | |
369 | dictEncObjHash, /* hash function */ | |
370 | NULL, /* key dup */ | |
371 | NULL, /* val dup */ | |
372 | dictEncObjKeyCompare, /* key compare */ | |
373 | dictRedisObjectDestructor, /* key destructor */ | |
374 | dictRedisObjectDestructor /* val destructor */ | |
375 | }; | |
376 | ||
377 | /* Keylist hash table type has unencoded redis objects as keys and | |
378 | * lists as values. It's used for blocking operations (BLPOP) and to | |
379 | * map swapped keys to a list of clients waiting for this keys to be loaded. */ | |
380 | dictType keylistDictType = { | |
381 | dictObjHash, /* hash function */ | |
382 | NULL, /* key dup */ | |
383 | NULL, /* val dup */ | |
384 | dictObjKeyCompare, /* key compare */ | |
385 | dictRedisObjectDestructor, /* key destructor */ | |
386 | dictListDestructor /* val destructor */ | |
387 | }; | |
388 | ||
389 | int htNeedsResize(dict *dict) { | |
390 | long long size, used; | |
391 | ||
392 | size = dictSlots(dict); | |
393 | used = dictSize(dict); | |
394 | return (size && used && size > DICT_HT_INITIAL_SIZE && | |
395 | (used*100/size < REDIS_HT_MINFILL)); | |
396 | } | |
397 | ||
398 | /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL | |
399 | * we resize the hash table to save memory */ | |
400 | void tryResizeHashTables(void) { | |
401 | int j; | |
402 | ||
403 | for (j = 0; j < server.dbnum; j++) { | |
404 | if (htNeedsResize(server.db[j].dict)) | |
405 | dictResize(server.db[j].dict); | |
406 | if (htNeedsResize(server.db[j].expires)) | |
407 | dictResize(server.db[j].expires); | |
408 | } | |
409 | } | |
410 | ||
411 | /* Our hash table implementation performs rehashing incrementally while | |
412 | * we write/read from the hash table. Still if the server is idle, the hash | |
413 | * table will use two tables for a long time. So we try to use 1 millisecond | |
414 | * of CPU time at every serverCron() loop in order to rehash some key. */ | |
415 | void incrementallyRehash(void) { | |
416 | int j; | |
417 | ||
418 | for (j = 0; j < server.dbnum; j++) { | |
419 | if (dictIsRehashing(server.db[j].dict)) { | |
420 | dictRehashMilliseconds(server.db[j].dict,1); | |
421 | break; /* already used our millisecond for this loop... */ | |
422 | } | |
423 | } | |
424 | } | |
425 | ||
426 | /* This function is called once a background process of some kind terminates, | |
427 | * as we want to avoid resizing the hash tables when there is a child in order | |
428 | * to play well with copy-on-write (otherwise when a resize happens lots of | |
429 | * memory pages are copied). The goal of this function is to update the ability | |
430 | * for dict.c to resize the hash tables accordingly to the fact we have o not | |
431 | * running childs. */ | |
432 | void updateDictResizePolicy(void) { | |
433 | if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) | |
434 | dictEnableResize(); | |
435 | else | |
436 | dictDisableResize(); | |
437 | } | |
438 | ||
439 | /* ======================= Cron: called every 100 ms ======================== */ | |
440 | ||
bcf2995c | 441 | /* Try to expire a few timed out keys. The algorithm used is adaptive and |
442 | * will use few CPU cycles if there are few expiring keys, otherwise | |
443 | * it will get more aggressive to avoid that too much memory is used by | |
444 | * keys that can be removed from the keyspace. */ | |
445 | void activeExpireCycle(void) { | |
446 | int j; | |
447 | ||
448 | for (j = 0; j < server.dbnum; j++) { | |
449 | int expired; | |
450 | redisDb *db = server.db+j; | |
451 | ||
452 | /* Continue to expire if at the end of the cycle more than 25% | |
453 | * of the keys were expired. */ | |
454 | do { | |
455 | long num = dictSize(db->expires); | |
456 | time_t now = time(NULL); | |
457 | ||
458 | expired = 0; | |
459 | if (num > REDIS_EXPIRELOOKUPS_PER_CRON) | |
460 | num = REDIS_EXPIRELOOKUPS_PER_CRON; | |
461 | while (num--) { | |
462 | dictEntry *de; | |
463 | time_t t; | |
464 | ||
465 | if ((de = dictGetRandomKey(db->expires)) == NULL) break; | |
466 | t = (time_t) dictGetEntryVal(de); | |
467 | if (now > t) { | |
468 | sds key = dictGetEntryKey(de); | |
469 | robj *keyobj = createStringObject(key,sdslen(key)); | |
470 | ||
471 | propagateExpire(db,keyobj); | |
472 | dbDelete(db,keyobj); | |
473 | decrRefCount(keyobj); | |
474 | expired++; | |
475 | server.stat_expiredkeys++; | |
476 | } | |
477 | } | |
478 | } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4); | |
479 | } | |
480 | } | |
481 | ||
165346ca | 482 | void updateLRUClock(void) { |
483 | server.lruclock = (time(NULL)/REDIS_LRU_CLOCK_RESOLUTION) & | |
484 | REDIS_LRU_CLOCK_MAX; | |
485 | } | |
bcf2995c | 486 | |
e2641e09 | 487 | int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { |
488 | int j, loops = server.cronloops++; | |
489 | REDIS_NOTUSED(eventLoop); | |
490 | REDIS_NOTUSED(id); | |
491 | REDIS_NOTUSED(clientData); | |
492 | ||
493 | /* We take a cached value of the unix time in the global state because | |
494 | * with virtual memory and aging there is to store the current time | |
495 | * in objects at every object access, and accuracy is not needed. | |
496 | * To access a global var is faster than calling time(NULL) */ | |
497 | server.unixtime = time(NULL); | |
ef59a8bc | 498 | /* We have just 22 bits per object for LRU information. |
165346ca | 499 | * So we use an (eventually wrapping) LRU clock with 10 seconds resolution. |
500 | * 2^22 bits with 10 seconds resoluton is more or less 1.5 years. | |
e2641e09 | 501 | * |
165346ca | 502 | * Note that even if this will wrap after 1.5 years it's not a problem, |
ef59a8bc | 503 | * everything will still work but just some object will appear younger |
165346ca | 504 | * to Redis. But for this to happen a given object should never be touched |
505 | * for 1.5 years. | |
506 | * | |
507 | * Note that you can change the resolution altering the | |
508 | * REDIS_LRU_CLOCK_RESOLUTION define. | |
e2641e09 | 509 | */ |
165346ca | 510 | updateLRUClock(); |
e2641e09 | 511 | |
512 | /* We received a SIGTERM, shutting down here in a safe way, as it is | |
513 | * not ok doing so inside the signal handler. */ | |
514 | if (server.shutdown_asap) { | |
515 | if (prepareForShutdown() == REDIS_OK) exit(0); | |
516 | redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); | |
517 | } | |
518 | ||
519 | /* Show some info about non-empty databases */ | |
520 | for (j = 0; j < server.dbnum; j++) { | |
521 | long long size, used, vkeys; | |
522 | ||
523 | size = dictSlots(server.db[j].dict); | |
524 | used = dictSize(server.db[j].dict); | |
525 | vkeys = dictSize(server.db[j].expires); | |
526 | if (!(loops % 50) && (used || vkeys)) { | |
527 | redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); | |
528 | /* dictPrintStats(server.dict); */ | |
529 | } | |
530 | } | |
531 | ||
532 | /* We don't want to resize the hash tables while a bacground saving | |
533 | * is in progress: the saving child is created using fork() that is | |
534 | * implemented with a copy-on-write semantic in most modern systems, so | |
535 | * if we resize the HT while there is the saving child at work actually | |
536 | * a lot of memory movements in the parent will cause a lot of pages | |
537 | * copied. */ | |
538 | if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) { | |
539 | if (!(loops % 10)) tryResizeHashTables(); | |
540 | if (server.activerehashing) incrementallyRehash(); | |
541 | } | |
542 | ||
543 | /* Show information about connected clients */ | |
544 | if (!(loops % 50)) { | |
545 | redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use", | |
546 | listLength(server.clients)-listLength(server.slaves), | |
547 | listLength(server.slaves), | |
548 | zmalloc_used_memory()); | |
549 | } | |
550 | ||
551 | /* Close connections of timedout clients */ | |
552 | if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients) | |
553 | closeTimedoutClients(); | |
554 | ||
555 | /* Check if a background saving or AOF rewrite in progress terminated */ | |
556 | if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) { | |
557 | int statloc; | |
558 | pid_t pid; | |
559 | ||
560 | if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { | |
561 | if (pid == server.bgsavechildpid) { | |
562 | backgroundSaveDoneHandler(statloc); | |
563 | } else { | |
564 | backgroundRewriteDoneHandler(statloc); | |
565 | } | |
566 | updateDictResizePolicy(); | |
567 | } | |
568 | } else { | |
569 | /* If there is not a background saving in progress check if | |
570 | * we have to save now */ | |
571 | time_t now = time(NULL); | |
572 | for (j = 0; j < server.saveparamslen; j++) { | |
573 | struct saveparam *sp = server.saveparams+j; | |
574 | ||
575 | if (server.dirty >= sp->changes && | |
576 | now-server.lastsave > sp->seconds) { | |
577 | redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...", | |
578 | sp->changes, sp->seconds); | |
579 | rdbSaveBackground(server.dbfilename); | |
580 | break; | |
581 | } | |
582 | } | |
583 | } | |
584 | ||
bcf2995c | 585 | /* Expire a few keys per cycle, only if this is a master. |
586 | * On slaves we wait for DEL operations synthesized by the master | |
587 | * in order to guarantee a strict consistency. */ | |
588 | if (server.masterhost == NULL) activeExpireCycle(); | |
e2641e09 | 589 | |
590 | /* Swap a few keys on disk if we are over the memory limit and VM | |
591 | * is enbled. Try to free objects from the free list first. */ | |
592 | if (vmCanSwapOut()) { | |
593 | while (server.vm_enabled && zmalloc_used_memory() > | |
594 | server.vm_max_memory) | |
595 | { | |
596 | int retval; | |
597 | ||
598 | if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue; | |
599 | retval = (server.vm_max_threads == 0) ? | |
600 | vmSwapOneObjectBlocking() : | |
601 | vmSwapOneObjectThreaded(); | |
602 | if (retval == REDIS_ERR && !(loops % 300) && | |
603 | zmalloc_used_memory() > | |
604 | (server.vm_max_memory+server.vm_max_memory/10)) | |
605 | { | |
606 | redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!"); | |
607 | } | |
608 | /* Note that when using threade I/O we free just one object, | |
609 | * because anyway when the I/O thread in charge to swap this | |
610 | * object out will finish, the handler of completed jobs | |
611 | * will try to swap more objects if we are still out of memory. */ | |
612 | if (retval == REDIS_ERR || server.vm_max_threads > 0) break; | |
613 | } | |
614 | } | |
615 | ||
616 | /* Check if we should connect to a MASTER */ | |
617 | if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) { | |
618 | redisLog(REDIS_NOTICE,"Connecting to MASTER..."); | |
619 | if (syncWithMaster() == REDIS_OK) { | |
620 | redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded"); | |
621 | if (server.appendonly) rewriteAppendOnlyFileBackground(); | |
622 | } | |
623 | } | |
624 | return 100; | |
625 | } | |
626 | ||
627 | /* This function gets called every time Redis is entering the | |
628 | * main loop of the event driven library, that is, before to sleep | |
629 | * for ready file descriptors. */ | |
630 | void beforeSleep(struct aeEventLoop *eventLoop) { | |
631 | REDIS_NOTUSED(eventLoop); | |
632 | ||
633 | /* Awake clients that got all the swapped keys they requested */ | |
634 | if (server.vm_enabled && listLength(server.io_ready_clients)) { | |
635 | listIter li; | |
636 | listNode *ln; | |
637 | ||
638 | listRewind(server.io_ready_clients,&li); | |
639 | while((ln = listNext(&li))) { | |
640 | redisClient *c = ln->value; | |
641 | struct redisCommand *cmd; | |
642 | ||
643 | /* Resume the client. */ | |
644 | listDelNode(server.io_ready_clients,ln); | |
645 | c->flags &= (~REDIS_IO_WAIT); | |
646 | server.vm_blocked_clients--; | |
647 | aeCreateFileEvent(server.el, c->fd, AE_READABLE, | |
648 | readQueryFromClient, c); | |
649 | cmd = lookupCommand(c->argv[0]->ptr); | |
650 | redisAssert(cmd != NULL); | |
651 | call(c,cmd); | |
652 | resetClient(c); | |
653 | /* There may be more data to process in the input buffer. */ | |
654 | if (c->querybuf && sdslen(c->querybuf) > 0) | |
655 | processInputBuffer(c); | |
656 | } | |
657 | } | |
658 | /* Write the AOF buffer on disk */ | |
659 | flushAppendOnlyFile(); | |
660 | } | |
661 | ||
662 | /* =========================== Server initialization ======================== */ | |
663 | ||
664 | void createSharedObjects(void) { | |
665 | int j; | |
666 | ||
667 | shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n")); | |
668 | shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n")); | |
669 | shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n")); | |
670 | shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n")); | |
671 | shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n")); | |
672 | shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n")); | |
673 | shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n")); | |
674 | shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n")); | |
675 | shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n")); | |
676 | shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n")); | |
677 | shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n")); | |
678 | shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n")); | |
679 | shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew( | |
680 | "-ERR Operation against a key holding the wrong kind of value\r\n")); | |
681 | shared.nokeyerr = createObject(REDIS_STRING,sdsnew( | |
682 | "-ERR no such key\r\n")); | |
683 | shared.syntaxerr = createObject(REDIS_STRING,sdsnew( | |
684 | "-ERR syntax error\r\n")); | |
685 | shared.sameobjecterr = createObject(REDIS_STRING,sdsnew( | |
686 | "-ERR source and destination objects are the same\r\n")); | |
687 | shared.outofrangeerr = createObject(REDIS_STRING,sdsnew( | |
688 | "-ERR index out of range\r\n")); | |
689 | shared.space = createObject(REDIS_STRING,sdsnew(" ")); | |
690 | shared.colon = createObject(REDIS_STRING,sdsnew(":")); | |
691 | shared.plus = createObject(REDIS_STRING,sdsnew("+")); | |
692 | shared.select0 = createStringObject("select 0\r\n",10); | |
693 | shared.select1 = createStringObject("select 1\r\n",10); | |
694 | shared.select2 = createStringObject("select 2\r\n",10); | |
695 | shared.select3 = createStringObject("select 3\r\n",10); | |
696 | shared.select4 = createStringObject("select 4\r\n",10); | |
697 | shared.select5 = createStringObject("select 5\r\n",10); | |
698 | shared.select6 = createStringObject("select 6\r\n",10); | |
699 | shared.select7 = createStringObject("select 7\r\n",10); | |
700 | shared.select8 = createStringObject("select 8\r\n",10); | |
701 | shared.select9 = createStringObject("select 9\r\n",10); | |
702 | shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); | |
703 | shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); | |
704 | shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); | |
705 | shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); | |
706 | shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); | |
707 | shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); | |
708 | shared.mbulk3 = createStringObject("*3\r\n",4); | |
709 | shared.mbulk4 = createStringObject("*4\r\n",4); | |
710 | for (j = 0; j < REDIS_SHARED_INTEGERS; j++) { | |
711 | shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j); | |
712 | shared.integers[j]->encoding = REDIS_ENCODING_INT; | |
713 | } | |
714 | } | |
715 | ||
716 | void initServerConfig() { | |
717 | server.dbnum = REDIS_DEFAULT_DBNUM; | |
718 | server.port = REDIS_SERVERPORT; | |
719 | server.verbosity = REDIS_VERBOSE; | |
720 | server.maxidletime = REDIS_MAXIDLETIME; | |
721 | server.saveparams = NULL; | |
722 | server.logfile = NULL; /* NULL = log on standard output */ | |
723 | server.bindaddr = NULL; | |
724 | server.glueoutputbuf = 1; | |
725 | server.daemonize = 0; | |
726 | server.appendonly = 0; | |
727 | server.appendfsync = APPENDFSYNC_EVERYSEC; | |
728 | server.no_appendfsync_on_rewrite = 0; | |
729 | server.lastfsync = time(NULL); | |
730 | server.appendfd = -1; | |
731 | server.appendseldb = -1; /* Make sure the first time will not match */ | |
732 | server.pidfile = zstrdup("/var/run/redis.pid"); | |
733 | server.dbfilename = zstrdup("dump.rdb"); | |
734 | server.appendfilename = zstrdup("appendonly.aof"); | |
735 | server.requirepass = NULL; | |
736 | server.rdbcompression = 1; | |
737 | server.activerehashing = 1; | |
738 | server.maxclients = 0; | |
739 | server.blpop_blocked_clients = 0; | |
740 | server.maxmemory = 0; | |
165346ca | 741 | server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU; |
742 | server.maxmemory_samples = 3; | |
e2641e09 | 743 | server.vm_enabled = 0; |
744 | server.vm_swap_file = zstrdup("/tmp/redis-%p.vm"); | |
745 | server.vm_page_size = 256; /* 256 bytes per page */ | |
746 | server.vm_pages = 1024*1024*100; /* 104 millions of pages */ | |
747 | server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */ | |
748 | server.vm_max_threads = 4; | |
749 | server.vm_blocked_clients = 0; | |
750 | server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES; | |
751 | server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE; | |
752 | server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES; | |
753 | server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE; | |
96ffb2fe | 754 | server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES; |
e2641e09 | 755 | server.shutdown_asap = 0; |
756 | ||
95506e46 | 757 | updateLRUClock(); |
e2641e09 | 758 | resetServerSaveParams(); |
759 | ||
760 | appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ | |
761 | appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ | |
762 | appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ | |
763 | /* Replication related */ | |
764 | server.isslave = 0; | |
765 | server.masterauth = NULL; | |
766 | server.masterhost = NULL; | |
767 | server.masterport = 6379; | |
768 | server.master = NULL; | |
769 | server.replstate = REDIS_REPL_NONE; | |
770 | ||
771 | /* Double constants initialization */ | |
772 | R_Zero = 0.0; | |
773 | R_PosInf = 1.0/R_Zero; | |
774 | R_NegInf = -1.0/R_Zero; | |
775 | R_Nan = R_Zero/R_Zero; | |
776 | } | |
777 | ||
778 | void initServer() { | |
779 | int j; | |
780 | ||
781 | signal(SIGHUP, SIG_IGN); | |
782 | signal(SIGPIPE, SIG_IGN); | |
783 | setupSigSegvAction(); | |
784 | ||
0e5441d8 | 785 | server.mainthread = pthread_self(); |
e2641e09 | 786 | server.devnull = fopen("/dev/null","w"); |
787 | if (server.devnull == NULL) { | |
788 | redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr); | |
789 | exit(1); | |
790 | } | |
791 | server.clients = listCreate(); | |
792 | server.slaves = listCreate(); | |
793 | server.monitors = listCreate(); | |
794 | server.objfreelist = listCreate(); | |
795 | createSharedObjects(); | |
796 | server.el = aeCreateEventLoop(); | |
797 | server.db = zmalloc(sizeof(redisDb)*server.dbnum); | |
798 | server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr); | |
799 | if (server.fd == -1) { | |
800 | redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr); | |
801 | exit(1); | |
802 | } | |
803 | for (j = 0; j < server.dbnum; j++) { | |
804 | server.db[j].dict = dictCreate(&dbDictType,NULL); | |
805 | server.db[j].expires = dictCreate(&keyptrDictType,NULL); | |
806 | server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); | |
807 | server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); | |
808 | if (server.vm_enabled) | |
809 | server.db[j].io_keys = dictCreate(&keylistDictType,NULL); | |
810 | server.db[j].id = j; | |
811 | } | |
812 | server.pubsub_channels = dictCreate(&keylistDictType,NULL); | |
813 | server.pubsub_patterns = listCreate(); | |
814 | listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); | |
815 | listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); | |
816 | server.cronloops = 0; | |
817 | server.bgsavechildpid = -1; | |
818 | server.bgrewritechildpid = -1; | |
819 | server.bgrewritebuf = sdsempty(); | |
820 | server.aofbuf = sdsempty(); | |
821 | server.lastsave = time(NULL); | |
822 | server.dirty = 0; | |
823 | server.stat_numcommands = 0; | |
824 | server.stat_numconnections = 0; | |
825 | server.stat_expiredkeys = 0; | |
826 | server.stat_starttime = time(NULL); | |
53eeeaff | 827 | server.stat_keyspace_misses = 0; |
828 | server.stat_keyspace_hits = 0; | |
e2641e09 | 829 | server.unixtime = time(NULL); |
830 | aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL); | |
831 | if (aeCreateFileEvent(server.el, server.fd, AE_READABLE, | |
832 | acceptHandler, NULL) == AE_ERR) oom("creating file event"); | |
833 | ||
834 | if (server.appendonly) { | |
835 | server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644); | |
836 | if (server.appendfd == -1) { | |
837 | redisLog(REDIS_WARNING, "Can't open the append-only file: %s", | |
838 | strerror(errno)); | |
839 | exit(1); | |
840 | } | |
841 | } | |
842 | ||
843 | if (server.vm_enabled) vmInit(); | |
844 | } | |
845 | ||
846 | int qsortRedisCommands(const void *r1, const void *r2) { | |
847 | return strcasecmp( | |
848 | ((struct redisCommand*)r1)->name, | |
849 | ((struct redisCommand*)r2)->name); | |
850 | } | |
851 | ||
852 | void sortCommandTable() { | |
853 | /* Copy and sort the read-only version of the command table */ | |
b3aa6d71 | 854 | commandTable = (struct redisCommand*)zmalloc(sizeof(readonlyCommandTable)); |
e2641e09 | 855 | memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable)); |
856 | qsort(commandTable, | |
857 | sizeof(readonlyCommandTable)/sizeof(struct redisCommand), | |
858 | sizeof(struct redisCommand),qsortRedisCommands); | |
859 | } | |
860 | ||
861 | /* ====================== Commands lookup and execution ===================== */ | |
862 | ||
863 | struct redisCommand *lookupCommand(char *name) { | |
864 | struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0}; | |
865 | return bsearch( | |
866 | &tmp, | |
867 | commandTable, | |
868 | sizeof(readonlyCommandTable)/sizeof(struct redisCommand), | |
869 | sizeof(struct redisCommand), | |
870 | qsortRedisCommands); | |
871 | } | |
872 | ||
873 | /* Call() is the core of Redis execution of a command */ | |
874 | void call(redisClient *c, struct redisCommand *cmd) { | |
875 | long long dirty; | |
876 | ||
877 | dirty = server.dirty; | |
878 | cmd->proc(c); | |
879 | dirty = server.dirty-dirty; | |
880 | ||
881 | if (server.appendonly && dirty) | |
882 | feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc); | |
883 | if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) && | |
884 | listLength(server.slaves)) | |
885 | replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc); | |
886 | if (listLength(server.monitors)) | |
887 | replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc); | |
888 | server.stat_numcommands++; | |
889 | } | |
890 | ||
891 | /* If this function gets called we already read a whole | |
892 | * command, argments are in the client argv/argc fields. | |
893 | * processCommand() execute the command or prepare the | |
894 | * server for a bulk read from the client. | |
895 | * | |
896 | * If 1 is returned the client is still alive and valid and | |
897 | * and other operations can be performed by the caller. Otherwise | |
898 | * if 0 is returned the client was destroied (i.e. after QUIT). */ | |
899 | int processCommand(redisClient *c) { | |
900 | struct redisCommand *cmd; | |
901 | ||
941c9fa2 PN |
902 | /* The QUIT command is handled separately. Normal command procs will |
903 | * go through checking for replication and QUIT will cause trouble | |
904 | * when FORCE_REPLICATION is enabled and would be implemented in | |
905 | * a regular command proc. */ | |
e2641e09 | 906 | if (!strcasecmp(c->argv[0]->ptr,"quit")) { |
941c9fa2 | 907 | addReply(c,shared.ok); |
5e78edb3 | 908 | c->flags |= REDIS_CLOSE_AFTER_REPLY; |
cd8788f2 | 909 | return REDIS_ERR; |
e2641e09 | 910 | } |
911 | ||
912 | /* Now lookup the command and check ASAP about trivial error conditions | |
913 | * such wrong arity, bad command name and so forth. */ | |
914 | cmd = lookupCommand(c->argv[0]->ptr); | |
915 | if (!cmd) { | |
3ab20376 PN |
916 | addReplyErrorFormat(c,"unknown command '%s'", |
917 | (char*)c->argv[0]->ptr); | |
cd8788f2 | 918 | return REDIS_OK; |
e2641e09 | 919 | } else if ((cmd->arity > 0 && cmd->arity != c->argc) || |
920 | (c->argc < -cmd->arity)) { | |
3ab20376 PN |
921 | addReplyErrorFormat(c,"wrong number of arguments for '%s' command", |
922 | cmd->name); | |
cd8788f2 | 923 | return REDIS_OK; |
e2641e09 | 924 | } |
e2641e09 | 925 | |
926 | /* Check if the user is authenticated */ | |
927 | if (server.requirepass && !c->authenticated && cmd->proc != authCommand) { | |
3ab20376 | 928 | addReplyError(c,"operation not permitted"); |
cd8788f2 | 929 | return REDIS_OK; |
e2641e09 | 930 | } |
931 | ||
1dd10ca2 | 932 | /* Handle the maxmemory directive. |
933 | * | |
934 | * First we try to free some memory if possible (if there are volatile | |
935 | * keys in the dataset). If there are not the only thing we can do | |
936 | * is returning an error. */ | |
937 | if (server.maxmemory) freeMemoryIfNeeded(); | |
e2641e09 | 938 | if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) && |
939 | zmalloc_used_memory() > server.maxmemory) | |
940 | { | |
3ab20376 | 941 | addReplyError(c,"command not allowed when used memory > 'maxmemory'"); |
cd8788f2 | 942 | return REDIS_OK; |
e2641e09 | 943 | } |
944 | ||
945 | /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ | |
946 | if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0) | |
947 | && | |
948 | cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand && | |
949 | cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) { | |
3ab20376 | 950 | addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context"); |
cd8788f2 | 951 | return REDIS_OK; |
e2641e09 | 952 | } |
953 | ||
954 | /* Exec the command */ | |
955 | if (c->flags & REDIS_MULTI && | |
956 | cmd->proc != execCommand && cmd->proc != discardCommand && | |
957 | cmd->proc != multiCommand && cmd->proc != watchCommand) | |
958 | { | |
959 | queueMultiCommand(c,cmd); | |
960 | addReply(c,shared.queued); | |
961 | } else { | |
962 | if (server.vm_enabled && server.vm_max_threads > 0 && | |
9da6caac | 963 | blockClientOnSwappedKeys(c,cmd)) return REDIS_ERR; |
e2641e09 | 964 | call(c,cmd); |
965 | } | |
cd8788f2 | 966 | return REDIS_OK; |
e2641e09 | 967 | } |
968 | ||
969 | /*================================== Shutdown =============================== */ | |
970 | ||
971 | int prepareForShutdown() { | |
972 | redisLog(REDIS_WARNING,"User requested shutdown, saving DB..."); | |
973 | /* Kill the saving child if there is a background saving in progress. | |
974 | We want to avoid race conditions, for instance our saving child may | |
975 | overwrite the synchronous saving did by SHUTDOWN. */ | |
976 | if (server.bgsavechildpid != -1) { | |
977 | redisLog(REDIS_WARNING,"There is a live saving child. Killing it!"); | |
978 | kill(server.bgsavechildpid,SIGKILL); | |
979 | rdbRemoveTempFile(server.bgsavechildpid); | |
980 | } | |
981 | if (server.appendonly) { | |
982 | /* Append only file: fsync() the AOF and exit */ | |
983 | aof_fsync(server.appendfd); | |
984 | if (server.vm_enabled) unlink(server.vm_swap_file); | |
d8a717fb | 985 | } else if (server.saveparamslen > 0) { |
e2641e09 | 986 | /* Snapshotting. Perform a SYNC SAVE and exit */ |
695fe874 | 987 | if (rdbSave(server.dbfilename) != REDIS_OK) { |
e2641e09 | 988 | /* Ooops.. error saving! The best we can do is to continue |
989 | * operating. Note that if there was a background saving process, | |
990 | * in the next cron() Redis will be notified that the background | |
991 | * saving aborted, handling special stuff like slaves pending for | |
992 | * synchronization... */ | |
993 | redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit"); | |
994 | return REDIS_ERR; | |
995 | } | |
d8a717fb RP |
996 | } else { |
997 | redisLog(REDIS_WARNING,"Not saving DB."); | |
e2641e09 | 998 | } |
695fe874 | 999 | if (server.daemonize) unlink(server.pidfile); |
e2641e09 | 1000 | redisLog(REDIS_WARNING,"Server exit now, bye bye..."); |
1001 | return REDIS_OK; | |
1002 | } | |
1003 | ||
1004 | /*================================== Commands =============================== */ | |
1005 | ||
1006 | void authCommand(redisClient *c) { | |
1007 | if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) { | |
1008 | c->authenticated = 1; | |
1009 | addReply(c,shared.ok); | |
1010 | } else { | |
1011 | c->authenticated = 0; | |
3ab20376 | 1012 | addReplyError(c,"invalid password"); |
e2641e09 | 1013 | } |
1014 | } | |
1015 | ||
1016 | void pingCommand(redisClient *c) { | |
1017 | addReply(c,shared.pong); | |
1018 | } | |
1019 | ||
1020 | void echoCommand(redisClient *c) { | |
1021 | addReplyBulk(c,c->argv[1]); | |
1022 | } | |
1023 | ||
1024 | /* Convert an amount of bytes into a human readable string in the form | |
1025 | * of 100B, 2G, 100M, 4K, and so forth. */ | |
1026 | void bytesToHuman(char *s, unsigned long long n) { | |
1027 | double d; | |
1028 | ||
1029 | if (n < 1024) { | |
1030 | /* Bytes */ | |
1031 | sprintf(s,"%lluB",n); | |
1032 | return; | |
1033 | } else if (n < (1024*1024)) { | |
1034 | d = (double)n/(1024); | |
1035 | sprintf(s,"%.2fK",d); | |
1036 | } else if (n < (1024LL*1024*1024)) { | |
1037 | d = (double)n/(1024*1024); | |
1038 | sprintf(s,"%.2fM",d); | |
1039 | } else if (n < (1024LL*1024*1024*1024)) { | |
1040 | d = (double)n/(1024LL*1024*1024); | |
1041 | sprintf(s,"%.2fG",d); | |
1042 | } | |
1043 | } | |
1044 | ||
1045 | /* Create the string returned by the INFO command. This is decoupled | |
1046 | * by the INFO command itself as we need to report the same information | |
1047 | * on memory corruption problems. */ | |
1048 | sds genRedisInfoString(void) { | |
1049 | sds info; | |
1050 | time_t uptime = time(NULL)-server.stat_starttime; | |
1051 | int j; | |
1052 | char hmem[64]; | |
2b00385d | 1053 | struct rusage self_ru, c_ru; |
1054 | ||
1055 | getrusage(RUSAGE_SELF, &self_ru); | |
1056 | getrusage(RUSAGE_CHILDREN, &c_ru); | |
e2641e09 | 1057 | |
1058 | bytesToHuman(hmem,zmalloc_used_memory()); | |
1059 | info = sdscatprintf(sdsempty(), | |
1060 | "redis_version:%s\r\n" | |
1061 | "redis_git_sha1:%s\r\n" | |
1062 | "redis_git_dirty:%d\r\n" | |
1063 | "arch_bits:%s\r\n" | |
1064 | "multiplexing_api:%s\r\n" | |
1065 | "process_id:%ld\r\n" | |
1066 | "uptime_in_seconds:%ld\r\n" | |
1067 | "uptime_in_days:%ld\r\n" | |
ef59a8bc | 1068 | "lru_clock:%ld\r\n" |
2b00385d | 1069 | "used_cpu_sys:%.2f\r\n" |
1070 | "used_cpu_user:%.2f\r\n" | |
1071 | "used_cpu_sys_childrens:%.2f\r\n" | |
1072 | "used_cpu_user_childrens:%.2f\r\n" | |
e2641e09 | 1073 | "connected_clients:%d\r\n" |
1074 | "connected_slaves:%d\r\n" | |
1075 | "blocked_clients:%d\r\n" | |
1076 | "used_memory:%zu\r\n" | |
1077 | "used_memory_human:%s\r\n" | |
eddb388e | 1078 | "mem_fragmentation_ratio:%.2f\r\n" |
13b37159 | 1079 | "use_tcmalloc:%d\r\n" |
e2641e09 | 1080 | "changes_since_last_save:%lld\r\n" |
1081 | "bgsave_in_progress:%d\r\n" | |
1082 | "last_save_time:%ld\r\n" | |
1083 | "bgrewriteaof_in_progress:%d\r\n" | |
1084 | "total_connections_received:%lld\r\n" | |
1085 | "total_commands_processed:%lld\r\n" | |
1086 | "expired_keys:%lld\r\n" | |
53eeeaff | 1087 | "keyspace_hits:%lld\r\n" |
1088 | "keyspace_misses:%lld\r\n" | |
e2641e09 | 1089 | "hash_max_zipmap_entries:%zu\r\n" |
1090 | "hash_max_zipmap_value:%zu\r\n" | |
1091 | "pubsub_channels:%ld\r\n" | |
1092 | "pubsub_patterns:%u\r\n" | |
1093 | "vm_enabled:%d\r\n" | |
1094 | "role:%s\r\n" | |
1095 | ,REDIS_VERSION, | |
1096 | redisGitSHA1(), | |
1097 | strtol(redisGitDirty(),NULL,10) > 0, | |
1098 | (sizeof(long) == 8) ? "64" : "32", | |
1099 | aeGetApiName(), | |
1100 | (long) getpid(), | |
1101 | uptime, | |
1102 | uptime/(3600*24), | |
ef59a8bc | 1103 | (unsigned long) server.lruclock, |
2b00385d | 1104 | (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000, |
1105 | (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000, | |
1106 | (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000, | |
1107 | (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000, | |
e2641e09 | 1108 | listLength(server.clients)-listLength(server.slaves), |
1109 | listLength(server.slaves), | |
1110 | server.blpop_blocked_clients, | |
1111 | zmalloc_used_memory(), | |
1112 | hmem, | |
eddb388e | 1113 | zmalloc_get_fragmentation_ratio(), |
13b37159 | 1114 | #ifdef USE_TCMALLOC |
1115 | 1, | |
1116 | #else | |
1117 | 0, | |
1118 | #endif | |
e2641e09 | 1119 | server.dirty, |
1120 | server.bgsavechildpid != -1, | |
1121 | server.lastsave, | |
1122 | server.bgrewritechildpid != -1, | |
1123 | server.stat_numconnections, | |
1124 | server.stat_numcommands, | |
1125 | server.stat_expiredkeys, | |
53eeeaff | 1126 | server.stat_keyspace_hits, |
1127 | server.stat_keyspace_misses, | |
e2641e09 | 1128 | server.hash_max_zipmap_entries, |
1129 | server.hash_max_zipmap_value, | |
1130 | dictSize(server.pubsub_channels), | |
1131 | listLength(server.pubsub_patterns), | |
1132 | server.vm_enabled != 0, | |
1133 | server.masterhost == NULL ? "master" : "slave" | |
1134 | ); | |
1135 | if (server.masterhost) { | |
1136 | info = sdscatprintf(info, | |
1137 | "master_host:%s\r\n" | |
1138 | "master_port:%d\r\n" | |
1139 | "master_link_status:%s\r\n" | |
1140 | "master_last_io_seconds_ago:%d\r\n" | |
1141 | ,server.masterhost, | |
1142 | server.masterport, | |
1143 | (server.replstate == REDIS_REPL_CONNECTED) ? | |
1144 | "up" : "down", | |
1145 | server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1 | |
1146 | ); | |
1147 | } | |
1148 | if (server.vm_enabled) { | |
1149 | lockThreadedIO(); | |
1150 | info = sdscatprintf(info, | |
1151 | "vm_conf_max_memory:%llu\r\n" | |
1152 | "vm_conf_page_size:%llu\r\n" | |
1153 | "vm_conf_pages:%llu\r\n" | |
1154 | "vm_stats_used_pages:%llu\r\n" | |
1155 | "vm_stats_swapped_objects:%llu\r\n" | |
1156 | "vm_stats_swappin_count:%llu\r\n" | |
1157 | "vm_stats_swappout_count:%llu\r\n" | |
1158 | "vm_stats_io_newjobs_len:%lu\r\n" | |
1159 | "vm_stats_io_processing_len:%lu\r\n" | |
1160 | "vm_stats_io_processed_len:%lu\r\n" | |
1161 | "vm_stats_io_active_threads:%lu\r\n" | |
1162 | "vm_stats_blocked_clients:%lu\r\n" | |
1163 | ,(unsigned long long) server.vm_max_memory, | |
1164 | (unsigned long long) server.vm_page_size, | |
1165 | (unsigned long long) server.vm_pages, | |
1166 | (unsigned long long) server.vm_stats_used_pages, | |
1167 | (unsigned long long) server.vm_stats_swapped_objects, | |
1168 | (unsigned long long) server.vm_stats_swapins, | |
1169 | (unsigned long long) server.vm_stats_swapouts, | |
1170 | (unsigned long) listLength(server.io_newjobs), | |
1171 | (unsigned long) listLength(server.io_processing), | |
1172 | (unsigned long) listLength(server.io_processed), | |
1173 | (unsigned long) server.io_active_threads, | |
1174 | (unsigned long) server.vm_blocked_clients | |
1175 | ); | |
1176 | unlockThreadedIO(); | |
1177 | } | |
1178 | for (j = 0; j < server.dbnum; j++) { | |
1179 | long long keys, vkeys; | |
1180 | ||
1181 | keys = dictSize(server.db[j].dict); | |
1182 | vkeys = dictSize(server.db[j].expires); | |
1183 | if (keys || vkeys) { | |
1184 | info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n", | |
1185 | j, keys, vkeys); | |
1186 | } | |
1187 | } | |
1188 | return info; | |
1189 | } | |
1190 | ||
1191 | void infoCommand(redisClient *c) { | |
1192 | sds info = genRedisInfoString(); | |
1193 | addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n", | |
1194 | (unsigned long)sdslen(info))); | |
1195 | addReplySds(c,info); | |
1196 | addReply(c,shared.crlf); | |
1197 | } | |
1198 | ||
1199 | void monitorCommand(redisClient *c) { | |
1200 | /* ignore MONITOR if aleady slave or in monitor mode */ | |
1201 | if (c->flags & REDIS_SLAVE) return; | |
1202 | ||
1203 | c->flags |= (REDIS_SLAVE|REDIS_MONITOR); | |
1204 | c->slaveseldb = 0; | |
1205 | listAddNodeTail(server.monitors,c); | |
1206 | addReply(c,shared.ok); | |
1207 | } | |
1208 | ||
1209 | /* ============================ Maxmemory directive ======================== */ | |
1210 | ||
1211 | /* Try to free one object form the pre-allocated objects free list. | |
1212 | * This is useful under low mem conditions as by default we take 1 million | |
1213 | * free objects allocated. On success REDIS_OK is returned, otherwise | |
1214 | * REDIS_ERR. */ | |
1215 | int tryFreeOneObjectFromFreelist(void) { | |
1216 | robj *o; | |
1217 | ||
1218 | if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex); | |
1219 | if (listLength(server.objfreelist)) { | |
1220 | listNode *head = listFirst(server.objfreelist); | |
1221 | o = listNodeValue(head); | |
1222 | listDelNode(server.objfreelist,head); | |
1223 | if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex); | |
1224 | zfree(o); | |
1225 | return REDIS_OK; | |
1226 | } else { | |
1227 | if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex); | |
1228 | return REDIS_ERR; | |
1229 | } | |
1230 | } | |
1231 | ||
1232 | /* This function gets called when 'maxmemory' is set on the config file to limit | |
1233 | * the max memory used by the server, and we are out of memory. | |
1234 | * This function will try to, in order: | |
1235 | * | |
1236 | * - Free objects from the free list | |
1237 | * - Try to remove keys with an EXPIRE set | |
1238 | * | |
1239 | * It is not possible to free enough memory to reach used-memory < maxmemory | |
1240 | * the server will start refusing commands that will enlarge even more the | |
1241 | * memory usage. | |
1242 | */ | |
1243 | void freeMemoryIfNeeded(void) { | |
165346ca | 1244 | /* Remove keys accordingly to the active policy as long as we are |
1245 | * over the memory limit. */ | |
e2641e09 | 1246 | while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) { |
1247 | int j, k, freed = 0; | |
1248 | ||
165346ca | 1249 | /* Basic strategy -- remove objects from the free list. */ |
e2641e09 | 1250 | if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue; |
165346ca | 1251 | |
1252 | for (j = 0; j < server.dbnum; j++) { | |
10c12171 | 1253 | long bestval = 0; /* just to prevent warning */ |
165346ca | 1254 | sds bestkey = NULL; |
1255 | struct dictEntry *de; | |
1256 | redisDb *db = server.db+j; | |
1257 | dict *dict; | |
1258 | ||
1259 | if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || | |
1260 | server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM) | |
1261 | { | |
1262 | dict = server.db[j].dict; | |
1263 | } else { | |
1264 | dict = server.db[j].expires; | |
1265 | } | |
1266 | if (dictSize(dict) == 0) continue; | |
1267 | ||
1268 | /* volatile-random and allkeys-random policy */ | |
1269 | if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM || | |
1270 | server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM) | |
1271 | { | |
1272 | de = dictGetRandomKey(dict); | |
1273 | bestkey = dictGetEntryKey(de); | |
1274 | } | |
1275 | ||
1276 | /* volatile-lru and allkeys-lru policy */ | |
1277 | else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || | |
1278 | server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU) | |
1279 | { | |
1280 | for (k = 0; k < server.maxmemory_samples; k++) { | |
1281 | sds thiskey; | |
1282 | long thisval; | |
1283 | robj *o; | |
1284 | ||
1285 | de = dictGetRandomKey(dict); | |
1286 | thiskey = dictGetEntryKey(de); | |
1287 | o = dictGetEntryVal(de); | |
1288 | thisval = estimateObjectIdleTime(o); | |
1289 | ||
1290 | /* Higher idle time is better candidate for deletion */ | |
1291 | if (bestkey == NULL || thisval > bestval) { | |
1292 | bestkey = thiskey; | |
1293 | bestval = thisval; | |
1294 | } | |
1295 | } | |
1296 | } | |
1297 | ||
1298 | /* volatile-ttl */ | |
1299 | else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) { | |
1300 | for (k = 0; k < server.maxmemory_samples; k++) { | |
1301 | sds thiskey; | |
1302 | long thisval; | |
1303 | ||
1304 | de = dictGetRandomKey(dict); | |
1305 | thiskey = dictGetEntryKey(de); | |
1306 | thisval = (long) dictGetEntryVal(de); | |
1307 | ||
1308 | /* Expire sooner (minor expire unix timestamp) is better | |
1309 | * candidate for deletion */ | |
1310 | if (bestkey == NULL || thisval < bestval) { | |
1311 | bestkey = thiskey; | |
1312 | bestval = thisval; | |
1313 | } | |
1314 | } | |
1315 | } | |
1316 | ||
1317 | /* Finally remove the selected key. */ | |
1318 | if (bestkey) { | |
1319 | robj *keyobj = createStringObject(bestkey,sdslen(bestkey)); | |
1320 | dbDelete(db,keyobj); | |
1321 | server.stat_expiredkeys++; | |
1322 | decrRefCount(keyobj); | |
1323 | freed++; | |
1324 | } | |
1325 | } | |
1326 | if (!freed) return; /* nothing to free... */ | |
1327 | } | |
1328 | ||
1329 | while(0) { | |
1330 | int j, k, freed = 0; | |
e2641e09 | 1331 | for (j = 0; j < server.dbnum; j++) { |
1332 | int minttl = -1; | |
357d3673 | 1333 | sds minkey = NULL; |
1334 | robj *keyobj = NULL; | |
e2641e09 | 1335 | struct dictEntry *de; |
1336 | ||
1337 | if (dictSize(server.db[j].expires)) { | |
1338 | freed = 1; | |
1339 | /* From a sample of three keys drop the one nearest to | |
1340 | * the natural expire */ | |
1341 | for (k = 0; k < 3; k++) { | |
1342 | time_t t; | |
1343 | ||
1344 | de = dictGetRandomKey(server.db[j].expires); | |
1345 | t = (time_t) dictGetEntryVal(de); | |
1346 | if (minttl == -1 || t < minttl) { | |
1347 | minkey = dictGetEntryKey(de); | |
1348 | minttl = t; | |
1349 | } | |
1350 | } | |
357d3673 | 1351 | keyobj = createStringObject(minkey,sdslen(minkey)); |
1352 | dbDelete(server.db+j,keyobj); | |
3856f147 | 1353 | server.stat_expiredkeys++; |
357d3673 | 1354 | decrRefCount(keyobj); |
e2641e09 | 1355 | } |
1356 | } | |
1357 | if (!freed) return; /* nothing to free... */ | |
1358 | } | |
1359 | } | |
1360 | ||
1361 | /* =================================== Main! ================================ */ | |
1362 | ||
1363 | #ifdef __linux__ | |
1364 | int linuxOvercommitMemoryValue(void) { | |
1365 | FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); | |
1366 | char buf[64]; | |
1367 | ||
1368 | if (!fp) return -1; | |
1369 | if (fgets(buf,64,fp) == NULL) { | |
1370 | fclose(fp); | |
1371 | return -1; | |
1372 | } | |
1373 | fclose(fp); | |
1374 | ||
1375 | return atoi(buf); | |
1376 | } | |
1377 | ||
1378 | void linuxOvercommitMemoryWarning(void) { | |
1379 | if (linuxOvercommitMemoryValue() == 0) { | |
1380 | 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."); | |
1381 | } | |
1382 | } | |
1383 | #endif /* __linux__ */ | |
1384 | ||
695fe874 | 1385 | void createPidFile(void) { |
1386 | /* Try to write the pid file in a best-effort way. */ | |
1387 | FILE *fp = fopen(server.pidfile,"w"); | |
1388 | if (fp) { | |
1389 | fprintf(fp,"%d\n",getpid()); | |
1390 | fclose(fp); | |
1391 | } | |
1392 | } | |
1393 | ||
e2641e09 | 1394 | void daemonize(void) { |
1395 | int fd; | |
e2641e09 | 1396 | |
1397 | if (fork() != 0) exit(0); /* parent exits */ | |
1398 | setsid(); /* create a new session */ | |
1399 | ||
1400 | /* Every output goes to /dev/null. If Redis is daemonized but | |
1401 | * the 'logfile' is set to 'stdout' in the configuration file | |
1402 | * it will not log at all. */ | |
1403 | if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { | |
1404 | dup2(fd, STDIN_FILENO); | |
1405 | dup2(fd, STDOUT_FILENO); | |
1406 | dup2(fd, STDERR_FILENO); | |
1407 | if (fd > STDERR_FILENO) close(fd); | |
1408 | } | |
e2641e09 | 1409 | } |
1410 | ||
1411 | void version() { | |
1412 | printf("Redis server version %s (%s:%d)\n", REDIS_VERSION, | |
1413 | redisGitSHA1(), atoi(redisGitDirty()) > 0); | |
1414 | exit(0); | |
1415 | } | |
1416 | ||
1417 | void usage() { | |
1418 | fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n"); | |
1419 | fprintf(stderr," ./redis-server - (read config from stdin)\n"); | |
1420 | exit(1); | |
1421 | } | |
1422 | ||
1423 | int main(int argc, char **argv) { | |
1424 | time_t start; | |
1425 | ||
1426 | initServerConfig(); | |
1427 | sortCommandTable(); | |
1428 | if (argc == 2) { | |
1429 | if (strcmp(argv[1], "-v") == 0 || | |
1430 | strcmp(argv[1], "--version") == 0) version(); | |
1431 | if (strcmp(argv[1], "--help") == 0) usage(); | |
1432 | resetServerSaveParams(); | |
1433 | loadServerConfig(argv[1]); | |
1434 | } else if ((argc > 2)) { | |
1435 | usage(); | |
1436 | } else { | |
1437 | 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'"); | |
1438 | } | |
1439 | if (server.daemonize) daemonize(); | |
1440 | initServer(); | |
695fe874 | 1441 | if (server.daemonize) createPidFile(); |
e2641e09 | 1442 | redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION); |
1443 | #ifdef __linux__ | |
1444 | linuxOvercommitMemoryWarning(); | |
1445 | #endif | |
1446 | start = time(NULL); | |
1447 | if (server.appendonly) { | |
1448 | if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK) | |
1449 | redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start); | |
1450 | } else { | |
1451 | if (rdbLoad(server.dbfilename) == REDIS_OK) | |
1452 | redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start); | |
1453 | } | |
1454 | redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port); | |
1455 | aeSetBeforeSleepProc(server.el,beforeSleep); | |
1456 | aeMain(server.el); | |
1457 | aeDeleteEventLoop(server.el); | |
1458 | return 0; | |
1459 | } | |
1460 | ||
1461 | /* ============================= Backtrace support ========================= */ | |
1462 | ||
1463 | #ifdef HAVE_BACKTRACE | |
1464 | void *getMcontextEip(ucontext_t *uc) { | |
1465 | #if defined(__FreeBSD__) | |
1466 | return (void*) uc->uc_mcontext.mc_eip; | |
1467 | #elif defined(__dietlibc__) | |
1468 | return (void*) uc->uc_mcontext.eip; | |
1469 | #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6) | |
1470 | #if __x86_64__ | |
1471 | return (void*) uc->uc_mcontext->__ss.__rip; | |
1472 | #else | |
1473 | return (void*) uc->uc_mcontext->__ss.__eip; | |
1474 | #endif | |
1475 | #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) | |
1476 | #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) | |
1477 | return (void*) uc->uc_mcontext->__ss.__rip; | |
1478 | #else | |
1479 | return (void*) uc->uc_mcontext->__ss.__eip; | |
1480 | #endif | |
3688d7f3 | 1481 | #elif defined(__i386__) |
1482 | return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */ | |
1483 | #elif defined(__X86_64__) || defined(__x86_64__) | |
1484 | return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */ | |
e2641e09 | 1485 | #elif defined(__ia64__) /* Linux IA64 */ |
1486 | return (void*) uc->uc_mcontext.sc_ip; | |
1487 | #else | |
1488 | return NULL; | |
1489 | #endif | |
1490 | } | |
1491 | ||
1492 | void segvHandler(int sig, siginfo_t *info, void *secret) { | |
1493 | void *trace[100]; | |
1494 | char **messages = NULL; | |
1495 | int i, trace_size = 0; | |
1496 | ucontext_t *uc = (ucontext_t*) secret; | |
1497 | sds infostring; | |
da47440d | 1498 | struct sigaction act; |
e2641e09 | 1499 | REDIS_NOTUSED(info); |
1500 | ||
1501 | redisLog(REDIS_WARNING, | |
1502 | "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig); | |
1503 | infostring = genRedisInfoString(); | |
1504 | redisLog(REDIS_WARNING, "%s",infostring); | |
1505 | /* It's not safe to sdsfree() the returned string under memory | |
1506 | * corruption conditions. Let it leak as we are going to abort */ | |
1507 | ||
1508 | trace_size = backtrace(trace, 100); | |
1509 | /* overwrite sigaction with caller's address */ | |
1510 | if (getMcontextEip(uc) != NULL) { | |
1511 | trace[1] = getMcontextEip(uc); | |
1512 | } | |
1513 | messages = backtrace_symbols(trace, trace_size); | |
1514 | ||
1515 | for (i=1; i<trace_size; ++i) | |
1516 | redisLog(REDIS_WARNING,"%s", messages[i]); | |
1517 | ||
1518 | /* free(messages); Don't call free() with possibly corrupted memory. */ | |
695fe874 | 1519 | if (server.daemonize) unlink(server.pidfile); |
da47440d | 1520 | |
1521 | /* Make sure we exit with the right signal at the end. So for instance | |
1522 | * the core will be dumped if enabled. */ | |
1523 | sigemptyset (&act.sa_mask); | |
1524 | /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction | |
1525 | * is used. Otherwise, sa_handler is used */ | |
1526 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND; | |
1527 | act.sa_handler = SIG_DFL; | |
1528 | sigaction (sig, &act, NULL); | |
1529 | kill(getpid(),sig); | |
e2641e09 | 1530 | } |
1531 | ||
1532 | void sigtermHandler(int sig) { | |
1533 | REDIS_NOTUSED(sig); | |
1534 | ||
1535 | redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down..."); | |
1536 | server.shutdown_asap = 1; | |
1537 | } | |
1538 | ||
1539 | void setupSigSegvAction(void) { | |
1540 | struct sigaction act; | |
1541 | ||
1542 | sigemptyset (&act.sa_mask); | |
1543 | /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction | |
1544 | * is used. Otherwise, sa_handler is used */ | |
1545 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO; | |
1546 | act.sa_sigaction = segvHandler; | |
1547 | sigaction (SIGSEGV, &act, NULL); | |
1548 | sigaction (SIGBUS, &act, NULL); | |
1549 | sigaction (SIGFPE, &act, NULL); | |
1550 | sigaction (SIGILL, &act, NULL); | |
1551 | sigaction (SIGBUS, &act, NULL); | |
1552 | ||
1553 | act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND; | |
1554 | act.sa_handler = sigtermHandler; | |
1555 | sigaction (SIGTERM, &act, NULL); | |
1556 | return; | |
1557 | } | |
1558 | ||
1559 | #else /* HAVE_BACKTRACE */ | |
1560 | void setupSigSegvAction(void) { | |
1561 | } | |
1562 | #endif /* HAVE_BACKTRACE */ | |
1563 | ||
1564 | /* The End */ |