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