2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
35 #endif /* HAVE_BACKTRACE */
44 #include <arpa/inet.h>
48 #include <sys/resource.h>
54 #include <sys/resource.h>
56 /* Our shared "common" objects */
58 struct sharedObjectsStruct shared
;
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. */
64 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
66 /*================================= Globals ================================= */
69 struct redisServer server
; /* server global state */
70 struct redisCommand
*commandTable
;
71 struct redisCommand redisCommandTable
[] = {
72 {"get",getCommand
,2,0,NULL
,1,1,1,0,0},
73 {"set",setCommand
,3,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,1,1,1,0,0},
74 {"setnx",setnxCommand
,3,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,1,1,1,0,0},
75 {"setex",setexCommand
,4,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,2,2,1,0,0},
76 {"append",appendCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
77 {"strlen",strlenCommand
,2,0,NULL
,1,1,1,0,0},
78 {"del",delCommand
,-2,0,noPreloadGetKeys
,1,-1,1,0,0},
79 {"exists",existsCommand
,2,0,NULL
,1,1,1,0,0},
80 {"setbit",setbitCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
81 {"getbit",getbitCommand
,3,0,NULL
,1,1,1,0,0},
82 {"setrange",setrangeCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
83 {"getrange",getrangeCommand
,4,0,NULL
,1,1,1,0,0},
84 {"substr",getrangeCommand
,4,0,NULL
,1,1,1,0,0},
85 {"incr",incrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
86 {"decr",decrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
87 {"mget",mgetCommand
,-2,0,NULL
,1,-1,1,0,0},
88 {"rpush",rpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
89 {"lpush",lpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
90 {"rpushx",rpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
91 {"lpushx",lpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
92 {"linsert",linsertCommand
,5,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
93 {"rpop",rpopCommand
,2,0,NULL
,1,1,1,0,0},
94 {"lpop",lpopCommand
,2,0,NULL
,1,1,1,0,0},
95 {"brpop",brpopCommand
,-3,0,NULL
,1,1,1,0,0},
96 {"brpoplpush",brpoplpushCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,2,1,0,0},
97 {"blpop",blpopCommand
,-3,0,NULL
,1,-2,1,0,0},
98 {"llen",llenCommand
,2,0,NULL
,1,1,1,0,0},
99 {"lindex",lindexCommand
,3,0,NULL
,1,1,1,0,0},
100 {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
101 {"lrange",lrangeCommand
,4,0,NULL
,1,1,1,0,0},
102 {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1,0,0},
103 {"lrem",lremCommand
,4,0,NULL
,1,1,1,0,0},
104 {"rpoplpush",rpoplpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1,0,0},
105 {"sadd",saddCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
106 {"srem",sremCommand
,3,0,NULL
,1,1,1,0,0},
107 {"smove",smoveCommand
,4,0,NULL
,1,2,1,0,0},
108 {"sismember",sismemberCommand
,3,0,NULL
,1,1,1,0,0},
109 {"scard",scardCommand
,2,0,NULL
,1,1,1,0,0},
110 {"spop",spopCommand
,2,0,NULL
,1,1,1,0,0},
111 {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1,0,0},
112 {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
113 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
114 {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
115 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
116 {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
117 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
118 {"smembers",sinterCommand
,2,0,NULL
,1,1,1,0,0},
119 {"zadd",zaddCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
120 {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
121 {"zrem",zremCommand
,3,0,NULL
,1,1,1,0,0},
122 {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1,0,0},
123 {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1,0,0},
124 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
125 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
126 {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1,0,0},
127 {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1,0,0},
128 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1,0,0},
129 {"zcount",zcountCommand
,4,0,NULL
,1,1,1,0,0},
130 {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1,0,0},
131 {"zcard",zcardCommand
,2,0,NULL
,1,1,1,0,0},
132 {"zscore",zscoreCommand
,3,0,NULL
,1,1,1,0,0},
133 {"zrank",zrankCommand
,3,0,NULL
,1,1,1,0,0},
134 {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1,0,0},
135 {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
136 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
137 {"hget",hgetCommand
,3,0,NULL
,1,1,1,0,0},
138 {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
139 {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1,0,0},
140 {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
141 {"hdel",hdelCommand
,3,0,NULL
,1,1,1,0,0},
142 {"hlen",hlenCommand
,2,0,NULL
,1,1,1,0,0},
143 {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1,0,0},
144 {"hvals",hvalsCommand
,2,0,NULL
,1,1,1,0,0},
145 {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1,0,0},
146 {"hexists",hexistsCommand
,3,0,NULL
,1,1,1,0,0},
147 {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
148 {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
149 {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
150 {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2,0,0},
151 {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2,0,0},
152 {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0,0,0},
153 {"select",selectCommand
,2,0,NULL
,0,0,0,0,0},
154 {"move",moveCommand
,3,0,NULL
,1,1,1,0,0},
155 {"rename",renameCommand
,3,0,renameGetKeys
,1,2,1,0,0},
156 {"renamenx",renamenxCommand
,3,0,renameGetKeys
,1,2,1,0,0},
157 {"expire",expireCommand
,3,0,NULL
,1,1,1,0,0},
158 {"expireat",expireatCommand
,3,0,NULL
,1,1,1,0,0},
159 {"keys",keysCommand
,2,0,NULL
,0,0,0,0,0},
160 {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0,0,0},
161 {"auth",authCommand
,2,0,NULL
,0,0,0,0,0},
162 {"ping",pingCommand
,1,0,NULL
,0,0,0,0,0},
163 {"echo",echoCommand
,2,0,NULL
,0,0,0,0,0},
164 {"save",saveCommand
,1,0,NULL
,0,0,0,0,0},
165 {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0,0,0},
166 {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0,0,0},
167 {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0,0,0},
168 {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0,0,0},
169 {"type",typeCommand
,2,0,NULL
,1,1,1,0,0},
170 {"multi",multiCommand
,1,0,NULL
,0,0,0,0,0},
171 {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,NULL
,0,0,0,0,0},
172 {"discard",discardCommand
,1,0,NULL
,0,0,0,0,0},
173 {"sync",syncCommand
,1,0,NULL
,0,0,0,0,0},
174 {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0,0,0},
175 {"flushall",flushallCommand
,1,0,NULL
,0,0,0,0,0},
176 {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
177 {"info",infoCommand
,-1,0,NULL
,0,0,0,0,0},
178 {"monitor",monitorCommand
,1,0,NULL
,0,0,0,0,0},
179 {"ttl",ttlCommand
,2,0,NULL
,1,1,1,0,0},
180 {"persist",persistCommand
,2,0,NULL
,1,1,1,0,0},
181 {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0,0,0},
182 {"debug",debugCommand
,-2,0,NULL
,0,0,0,0,0},
183 {"config",configCommand
,-2,0,NULL
,0,0,0,0,0},
184 {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0,0,0},
185 {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0,0,0},
186 {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0,0,0},
187 {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0,0,0},
188 {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0,0,0},
189 {"watch",watchCommand
,-2,0,noPreloadGetKeys
,1,-1,1,0,0},
190 {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0,0,0},
191 {"cluster",clusterCommand
,-2,0,NULL
,0,0,0,0,0},
192 {"restore",restoreCommand
,4,0,NULL
,0,0,0,0,0},
193 {"migrate",migrateCommand
,6,0,NULL
,0,0,0,0,0},
194 {"dump",dumpCommand
,2,0,NULL
,0,0,0,0,0},
195 {"object",objectCommand
,-2,0,NULL
,0,0,0,0,0}
198 /*============================ Utility functions ============================ */
200 /* Low level logging. To use only for very big messages, otherwise
201 * redisLog() is to prefer. */
202 void redisLogRaw(int level
, const char *msg
) {
203 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
204 const char *c
= ".-*#";
205 time_t now
= time(NULL
);
209 if (level
< server
.verbosity
) return;
211 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
214 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
215 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
218 if (server
.logfile
) fclose(fp
);
220 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
223 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
224 * is used across the code. The raw version is only used in order to dump
225 * the INFO output on crash. */
226 void redisLog(int level
, const char *fmt
, ...) {
228 char msg
[REDIS_MAX_LOGMSG_LEN
];
230 if (level
< server
.verbosity
) return;
233 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
236 redisLogRaw(level
,msg
);
239 /* Redis generally does not try to recover from out of memory conditions
240 * when allocating objects or strings, it is not clear if it will be possible
241 * to report this condition to the client since the networking layer itself
242 * is based on heap allocation for send buffers, so we simply abort.
243 * At least the code will be simpler to read... */
244 void oom(const char *msg
) {
245 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
250 /* Return the UNIX time in microseconds */
251 long long ustime(void) {
255 gettimeofday(&tv
, NULL
);
256 ust
= ((long long)tv
.tv_sec
)*1000000;
261 /*====================== Hash table type implementation ==================== */
263 /* This is an hash table type that uses the SDS dynamic strings libary as
264 * keys and radis objects as values (objects can hold SDS strings,
267 void dictVanillaFree(void *privdata
, void *val
)
269 DICT_NOTUSED(privdata
);
273 void dictListDestructor(void *privdata
, void *val
)
275 DICT_NOTUSED(privdata
);
276 listRelease((list
*)val
);
279 int dictSdsKeyCompare(void *privdata
, const void *key1
,
283 DICT_NOTUSED(privdata
);
285 l1
= sdslen((sds
)key1
);
286 l2
= sdslen((sds
)key2
);
287 if (l1
!= l2
) return 0;
288 return memcmp(key1
, key2
, l1
) == 0;
291 /* A case insensitive version used for the command lookup table. */
292 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
295 DICT_NOTUSED(privdata
);
297 return strcasecmp(key1
, key2
) == 0;
300 void dictRedisObjectDestructor(void *privdata
, void *val
)
302 DICT_NOTUSED(privdata
);
304 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
308 void dictSdsDestructor(void *privdata
, void *val
)
310 DICT_NOTUSED(privdata
);
315 int dictObjKeyCompare(void *privdata
, const void *key1
,
318 const robj
*o1
= key1
, *o2
= key2
;
319 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
322 unsigned int dictObjHash(const void *key
) {
324 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
327 unsigned int dictSdsHash(const void *key
) {
328 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
331 unsigned int dictSdsCaseHash(const void *key
) {
332 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
335 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
338 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
341 if (o1
->encoding
== REDIS_ENCODING_INT
&&
342 o2
->encoding
== REDIS_ENCODING_INT
)
343 return o1
->ptr
== o2
->ptr
;
345 o1
= getDecodedObject(o1
);
346 o2
= getDecodedObject(o2
);
347 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
353 unsigned int dictEncObjHash(const void *key
) {
354 robj
*o
= (robj
*) key
;
356 if (o
->encoding
== REDIS_ENCODING_RAW
) {
357 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
359 if (o
->encoding
== REDIS_ENCODING_INT
) {
363 len
= ll2string(buf
,32,(long)o
->ptr
);
364 return dictGenHashFunction((unsigned char*)buf
, len
);
368 o
= getDecodedObject(o
);
369 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
376 /* Sets type and diskstore negative caching hash table */
377 dictType setDictType
= {
378 dictEncObjHash
, /* hash function */
381 dictEncObjKeyCompare
, /* key compare */
382 dictRedisObjectDestructor
, /* key destructor */
383 NULL
/* val destructor */
386 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
387 dictType zsetDictType
= {
388 dictEncObjHash
, /* hash function */
391 dictEncObjKeyCompare
, /* key compare */
392 dictRedisObjectDestructor
, /* key destructor */
393 NULL
/* val destructor */
396 /* Db->dict, keys are sds strings, vals are Redis objects. */
397 dictType dbDictType
= {
398 dictSdsHash
, /* hash function */
401 dictSdsKeyCompare
, /* key compare */
402 dictSdsDestructor
, /* key destructor */
403 dictRedisObjectDestructor
/* val destructor */
407 dictType keyptrDictType
= {
408 dictSdsHash
, /* hash function */
411 dictSdsKeyCompare
, /* key compare */
412 NULL
, /* key destructor */
413 NULL
/* val destructor */
416 /* Command table. sds string -> command struct pointer. */
417 dictType commandTableDictType
= {
418 dictSdsCaseHash
, /* hash function */
421 dictSdsKeyCaseCompare
, /* key compare */
422 dictSdsDestructor
, /* key destructor */
423 NULL
/* val destructor */
426 /* Hash type hash table (note that small hashes are represented with zimpaps) */
427 dictType hashDictType
= {
428 dictEncObjHash
, /* hash function */
431 dictEncObjKeyCompare
, /* key compare */
432 dictRedisObjectDestructor
, /* key destructor */
433 dictRedisObjectDestructor
/* val destructor */
436 /* Keylist hash table type has unencoded redis objects as keys and
437 * lists as values. It's used for blocking operations (BLPOP) and to
438 * map swapped keys to a list of clients waiting for this keys to be loaded. */
439 dictType keylistDictType
= {
440 dictObjHash
, /* hash function */
443 dictObjKeyCompare
, /* key compare */
444 dictRedisObjectDestructor
, /* key destructor */
445 dictListDestructor
/* val destructor */
448 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
449 * clusterNode structures. */
450 dictType clusterNodesDictType
= {
451 dictSdsHash
, /* hash function */
454 dictSdsKeyCompare
, /* key compare */
455 dictSdsDestructor
, /* key destructor */
456 NULL
/* val destructor */
459 int htNeedsResize(dict
*dict
) {
460 long long size
, used
;
462 size
= dictSlots(dict
);
463 used
= dictSize(dict
);
464 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
465 (used
*100/size
< REDIS_HT_MINFILL
));
468 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
469 * we resize the hash table to save memory */
470 void tryResizeHashTables(void) {
473 for (j
= 0; j
< server
.dbnum
; j
++) {
474 if (htNeedsResize(server
.db
[j
].dict
))
475 dictResize(server
.db
[j
].dict
);
476 if (htNeedsResize(server
.db
[j
].expires
))
477 dictResize(server
.db
[j
].expires
);
481 /* Our hash table implementation performs rehashing incrementally while
482 * we write/read from the hash table. Still if the server is idle, the hash
483 * table will use two tables for a long time. So we try to use 1 millisecond
484 * of CPU time at every serverCron() loop in order to rehash some key. */
485 void incrementallyRehash(void) {
488 for (j
= 0; j
< server
.dbnum
; j
++) {
489 if (dictIsRehashing(server
.db
[j
].dict
)) {
490 dictRehashMilliseconds(server
.db
[j
].dict
,1);
491 break; /* already used our millisecond for this loop... */
496 /* This function is called once a background process of some kind terminates,
497 * as we want to avoid resizing the hash tables when there is a child in order
498 * to play well with copy-on-write (otherwise when a resize happens lots of
499 * memory pages are copied). The goal of this function is to update the ability
500 * for dict.c to resize the hash tables accordingly to the fact we have o not
502 void updateDictResizePolicy(void) {
503 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
509 /* ======================= Cron: called every 100 ms ======================== */
511 /* Try to expire a few timed out keys. The algorithm used is adaptive and
512 * will use few CPU cycles if there are few expiring keys, otherwise
513 * it will get more aggressive to avoid that too much memory is used by
514 * keys that can be removed from the keyspace. */
515 void activeExpireCycle(void) {
518 for (j
= 0; j
< server
.dbnum
; j
++) {
520 redisDb
*db
= server
.db
+j
;
522 /* Continue to expire if at the end of the cycle more than 25%
523 * of the keys were expired. */
525 long num
= dictSize(db
->expires
);
526 time_t now
= time(NULL
);
529 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
530 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
535 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
536 t
= (time_t) dictGetEntryVal(de
);
538 sds key
= dictGetEntryKey(de
);
539 robj
*keyobj
= createStringObject(key
,sdslen(key
));
541 propagateExpire(db
,keyobj
);
543 decrRefCount(keyobj
);
545 server
.stat_expiredkeys
++;
548 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
552 void updateLRUClock(void) {
553 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
557 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
558 int j
, loops
= server
.cronloops
;
559 REDIS_NOTUSED(eventLoop
);
561 REDIS_NOTUSED(clientData
);
563 /* We take a cached value of the unix time in the global state because
564 * with virtual memory and aging there is to store the current time
565 * in objects at every object access, and accuracy is not needed.
566 * To access a global var is faster than calling time(NULL) */
567 server
.unixtime
= time(NULL
);
568 /* We have just 22 bits per object for LRU information.
569 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
570 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
572 * Note that even if this will wrap after 1.5 years it's not a problem,
573 * everything will still work but just some object will appear younger
574 * to Redis. But for this to happen a given object should never be touched
577 * Note that you can change the resolution altering the
578 * REDIS_LRU_CLOCK_RESOLUTION define.
582 /* We received a SIGTERM, shutting down here in a safe way, as it is
583 * not ok doing so inside the signal handler. */
584 if (server
.shutdown_asap
) {
585 if (prepareForShutdown() == REDIS_OK
) exit(0);
586 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
589 /* Show some info about non-empty databases */
590 for (j
= 0; j
< server
.dbnum
; j
++) {
591 long long size
, used
, vkeys
;
593 size
= dictSlots(server
.db
[j
].dict
);
594 used
= dictSize(server
.db
[j
].dict
);
595 vkeys
= dictSize(server
.db
[j
].expires
);
596 if (!(loops
% 50) && (used
|| vkeys
)) {
597 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
598 /* dictPrintStats(server.dict); */
602 /* We don't want to resize the hash tables while a bacground saving
603 * is in progress: the saving child is created using fork() that is
604 * implemented with a copy-on-write semantic in most modern systems, so
605 * if we resize the HT while there is the saving child at work actually
606 * a lot of memory movements in the parent will cause a lot of pages
608 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
609 if (!(loops
% 10)) tryResizeHashTables();
610 if (server
.activerehashing
) incrementallyRehash();
613 /* Show information about connected clients */
615 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
616 listLength(server
.clients
)-listLength(server
.slaves
),
617 listLength(server
.slaves
),
618 zmalloc_used_memory());
621 /* Close connections of timedout clients */
622 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
623 closeTimedoutClients();
625 /* Check if a background saving or AOF rewrite in progress terminated. */
626 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
630 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
631 int exitcode
= WEXITSTATUS(statloc
);
634 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
636 if (pid
== server
.bgsavechildpid
) {
637 backgroundSaveDoneHandler(exitcode
,bysignal
);
639 backgroundRewriteDoneHandler(exitcode
,bysignal
);
641 updateDictResizePolicy();
643 } else if (server
.bgsavethread
!= (pthread_t
) -1) {
644 if (server
.bgsavethread
!= (pthread_t
) -1) {
647 pthread_mutex_lock(&server
.bgsavethread_mutex
);
648 state
= server
.bgsavethread_state
;
649 pthread_mutex_unlock(&server
.bgsavethread_mutex
);
651 if (state
== REDIS_BGSAVE_THREAD_DONE_OK
||
652 state
== REDIS_BGSAVE_THREAD_DONE_ERR
)
654 backgroundSaveDoneHandler(
655 (state
== REDIS_BGSAVE_THREAD_DONE_OK
) ? 0 : 1, 0);
658 } else if (!server
.ds_enabled
) {
659 /* If there is not a background saving in progress check if
660 * we have to save now */
661 time_t now
= time(NULL
);
662 for (j
= 0; j
< server
.saveparamslen
; j
++) {
663 struct saveparam
*sp
= server
.saveparams
+j
;
665 if (server
.dirty
>= sp
->changes
&&
666 now
-server
.lastsave
> sp
->seconds
) {
667 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
668 sp
->changes
, sp
->seconds
);
669 rdbSaveBackground(server
.dbfilename
);
675 /* Expire a few keys per cycle, only if this is a master.
676 * On slaves we wait for DEL operations synthesized by the master
677 * in order to guarantee a strict consistency. */
678 if (server
.masterhost
== NULL
) activeExpireCycle();
680 /* Remove a few cached objects from memory if we are over the
681 * configured memory limit */
682 if (server
.ds_enabled
) cacheCron();
684 /* Replication cron function -- used to reconnect to master and
685 * to detect transfer failures. */
686 if (!(loops
% 10)) replicationCron();
688 /* Run other sub-systems specific cron jobs */
689 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
695 /* This function gets called every time Redis is entering the
696 * main loop of the event driven library, that is, before to sleep
697 * for ready file descriptors. */
698 void beforeSleep(struct aeEventLoop
*eventLoop
) {
699 REDIS_NOTUSED(eventLoop
);
703 /* Awake clients that got all the on disk keys they requested */
704 if (server
.ds_enabled
&& listLength(server
.io_ready_clients
)) {
707 listRewind(server
.io_ready_clients
,&li
);
708 while((ln
= listNext(&li
))) {
710 struct redisCommand
*cmd
;
712 /* Resume the client. */
713 listDelNode(server
.io_ready_clients
,ln
);
714 c
->flags
&= (~REDIS_IO_WAIT
);
715 server
.cache_blocked_clients
--;
716 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
717 readQueryFromClient
, c
);
718 cmd
= lookupCommand(c
->argv
[0]->ptr
);
719 redisAssert(cmd
!= NULL
);
722 /* There may be more data to process in the input buffer. */
723 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
724 processInputBuffer(c
);
728 /* Try to process pending commands for clients that were just unblocked. */
729 while (listLength(server
.unblocked_clients
)) {
730 ln
= listFirst(server
.unblocked_clients
);
731 redisAssert(ln
!= NULL
);
733 listDelNode(server
.unblocked_clients
,ln
);
734 c
->flags
&= ~REDIS_UNBLOCKED
;
736 /* Process remaining data in the input buffer. */
737 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
738 processInputBuffer(c
);
741 /* Write the AOF buffer on disk */
742 flushAppendOnlyFile();
745 /* =========================== Server initialization ======================== */
747 void createSharedObjects(void) {
750 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
751 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
752 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
753 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
754 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
755 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
756 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
757 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
758 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
759 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
760 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
761 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
762 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
763 "-ERR Operation against a key holding the wrong kind of value\r\n"));
764 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
765 "-ERR no such key\r\n"));
766 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
767 "-ERR syntax error\r\n"));
768 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
769 "-ERR source and destination objects are the same\r\n"));
770 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
771 "-ERR index out of range\r\n"));
772 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
773 "-LOADING Redis is loading the dataset in memory\r\n"));
774 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
775 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
776 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
777 shared
.select0
= createStringObject("select 0\r\n",10);
778 shared
.select1
= createStringObject("select 1\r\n",10);
779 shared
.select2
= createStringObject("select 2\r\n",10);
780 shared
.select3
= createStringObject("select 3\r\n",10);
781 shared
.select4
= createStringObject("select 4\r\n",10);
782 shared
.select5
= createStringObject("select 5\r\n",10);
783 shared
.select6
= createStringObject("select 6\r\n",10);
784 shared
.select7
= createStringObject("select 7\r\n",10);
785 shared
.select8
= createStringObject("select 8\r\n",10);
786 shared
.select9
= createStringObject("select 9\r\n",10);
787 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
788 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
789 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
790 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
791 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
792 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
793 shared
.mbulk3
= createStringObject("*3\r\n",4);
794 shared
.mbulk4
= createStringObject("*4\r\n",4);
795 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
796 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
797 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
801 void initServerConfig() {
802 server
.port
= REDIS_SERVERPORT
;
803 server
.bindaddr
= NULL
;
804 server
.unixsocket
= NULL
;
807 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
808 server
.verbosity
= REDIS_VERBOSE
;
809 server
.maxidletime
= REDIS_MAXIDLETIME
;
810 server
.saveparams
= NULL
;
812 server
.logfile
= NULL
; /* NULL = log on standard output */
813 server
.syslog_enabled
= 0;
814 server
.syslog_ident
= zstrdup("redis");
815 server
.syslog_facility
= LOG_LOCAL0
;
816 server
.daemonize
= 0;
817 server
.appendonly
= 0;
818 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
819 server
.no_appendfsync_on_rewrite
= 0;
820 server
.lastfsync
= time(NULL
);
821 server
.appendfd
= -1;
822 server
.appendseldb
= -1; /* Make sure the first time will not match */
823 server
.pidfile
= zstrdup("/var/run/redis.pid");
824 server
.dbfilename
= zstrdup("dump.rdb");
825 server
.appendfilename
= zstrdup("appendonly.aof");
826 server
.requirepass
= NULL
;
827 server
.rdbcompression
= 1;
828 server
.activerehashing
= 1;
829 server
.maxclients
= 0;
830 server
.bpop_blocked_clients
= 0;
831 server
.maxmemory
= 0;
832 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
833 server
.maxmemory_samples
= 3;
834 server
.ds_enabled
= 0;
835 server
.ds_path
= sdsnew("/tmp/redis.ds");
836 server
.cache_max_memory
= 64LL*1024*1024; /* 64 MB of RAM */
837 server
.cache_blocked_clients
= 0;
838 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
839 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
840 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
841 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
842 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
843 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
844 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
845 server
.shutdown_asap
= 0;
846 server
.cache_flush_delay
= 0;
847 server
.cluster_enabled
= 0;
848 server
.cluster
.configfile
= zstrdup("nodes.conf");
851 resetServerSaveParams();
853 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
854 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
855 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
856 /* Replication related */
858 server
.masterauth
= NULL
;
859 server
.masterhost
= NULL
;
860 server
.masterport
= 6379;
861 server
.master
= NULL
;
862 server
.replstate
= REDIS_REPL_NONE
;
863 server
.repl_serve_stale_data
= 1;
865 /* Double constants initialization */
867 R_PosInf
= 1.0/R_Zero
;
868 R_NegInf
= -1.0/R_Zero
;
869 R_Nan
= R_Zero
/R_Zero
;
871 /* Command table -- we intiialize it here as it is part of the
872 * initial configuration, since command names may be changed via
873 * redis.conf using the rename-command directive. */
874 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
875 populateCommandTable();
876 server
.delCommand
= lookupCommandByCString("del");
877 server
.multiCommand
= lookupCommandByCString("multi");
883 signal(SIGHUP
, SIG_IGN
);
884 signal(SIGPIPE
, SIG_IGN
);
885 setupSignalHandlers();
887 if (server
.syslog_enabled
) {
888 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
889 server
.syslog_facility
);
892 server
.mainthread
= pthread_self();
893 server
.clients
= listCreate();
894 server
.slaves
= listCreate();
895 server
.monitors
= listCreate();
896 server
.unblocked_clients
= listCreate();
897 server
.cache_io_queue
= listCreate();
899 createSharedObjects();
900 server
.el
= aeCreateEventLoop();
901 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
903 if (server
.port
!= 0) {
904 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
905 if (server
.ipfd
== ANET_ERR
) {
906 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
910 if (server
.unixsocket
!= NULL
) {
911 unlink(server
.unixsocket
); /* don't care if this fails */
912 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
913 if (server
.sofd
== ANET_ERR
) {
914 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
918 if (server
.ipfd
< 0 && server
.sofd
< 0) {
919 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
922 for (j
= 0; j
< server
.dbnum
; j
++) {
923 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
924 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
925 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
926 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
927 if (server
.ds_enabled
) {
928 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
929 server
.db
[j
].io_negcache
= dictCreate(&setDictType
,NULL
);
930 server
.db
[j
].io_queued
= dictCreate(&setDictType
,NULL
);
934 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
935 server
.pubsub_patterns
= listCreate();
936 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
937 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
938 server
.cronloops
= 0;
939 server
.bgsavechildpid
= -1;
940 server
.bgrewritechildpid
= -1;
941 server
.bgsavethread_state
= REDIS_BGSAVE_THREAD_UNACTIVE
;
942 server
.bgsavethread
= (pthread_t
) -1;
943 server
.bgrewritebuf
= sdsempty();
944 server
.aofbuf
= sdsempty();
945 server
.lastsave
= time(NULL
);
947 server
.stat_numcommands
= 0;
948 server
.stat_numconnections
= 0;
949 server
.stat_expiredkeys
= 0;
950 server
.stat_evictedkeys
= 0;
951 server
.stat_starttime
= time(NULL
);
952 server
.stat_keyspace_misses
= 0;
953 server
.stat_keyspace_hits
= 0;
954 server
.unixtime
= time(NULL
);
955 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
956 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
957 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
958 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
959 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
961 if (server
.appendonly
) {
962 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
963 if (server
.appendfd
== -1) {
964 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
970 if (server
.ds_enabled
) dsInit();
971 if (server
.cluster_enabled
) clusterInit();
972 srand(time(NULL
)^getpid());
975 /* Populates the Redis Command Table starting from the hard coded list
976 * we have on top of redis.c file. */
977 void populateCommandTable(void) {
979 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
981 for (j
= 0; j
< numcommands
; j
++) {
982 struct redisCommand
*c
= redisCommandTable
+j
;
985 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
986 assert(retval
== DICT_OK
);
990 void resetCommandTableStats(void) {
991 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
994 for (j
= 0; j
< numcommands
; j
++) {
995 struct redisCommand
*c
= redisCommandTable
+j
;
1002 /* ====================== Commands lookup and execution ===================== */
1004 struct redisCommand
*lookupCommand(sds name
) {
1005 return dictFetchValue(server
.commands
, name
);
1008 struct redisCommand
*lookupCommandByCString(char *s
) {
1009 struct redisCommand
*cmd
;
1010 sds name
= sdsnew(s
);
1012 cmd
= dictFetchValue(server
.commands
, name
);
1017 /* Call() is the core of Redis execution of a command */
1018 void call(redisClient
*c
, struct redisCommand
*cmd
) {
1019 long long dirty
, start
= ustime();
1021 dirty
= server
.dirty
;
1023 dirty
= server
.dirty
-dirty
;
1024 cmd
->microseconds
+= ustime()-start
;
1027 if (server
.appendonly
&& dirty
)
1028 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1029 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1030 listLength(server
.slaves
))
1031 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1032 if (listLength(server
.monitors
))
1033 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1034 server
.stat_numcommands
++;
1037 /* If this function gets called we already read a whole
1038 * command, argments are in the client argv/argc fields.
1039 * processCommand() execute the command or prepare the
1040 * server for a bulk read from the client.
1042 * If 1 is returned the client is still alive and valid and
1043 * and other operations can be performed by the caller. Otherwise
1044 * if 0 is returned the client was destroied (i.e. after QUIT). */
1045 int processCommand(redisClient
*c
) {
1046 struct redisCommand
*cmd
;
1048 /* The QUIT command is handled separately. Normal command procs will
1049 * go through checking for replication and QUIT will cause trouble
1050 * when FORCE_REPLICATION is enabled and would be implemented in
1051 * a regular command proc. */
1052 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1053 addReply(c
,shared
.ok
);
1054 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1058 /* Now lookup the command and check ASAP about trivial error conditions
1059 * such wrong arity, bad command name and so forth. */
1060 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1062 addReplyErrorFormat(c
,"unknown command '%s'",
1063 (char*)c
->argv
[0]->ptr
);
1065 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1066 (c
->argc
< -cmd
->arity
)) {
1067 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1072 /* Check if the user is authenticated */
1073 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1074 addReplyError(c
,"operation not permitted");
1078 /* If cluster is enabled, redirect here */
1079 if (server
.cluster_enabled
&&
1080 !(cmd
->getkeys_proc
== NULL
&& cmd
->firstkey
== 0)) {
1083 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1084 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1087 clusterNode
*n
= getNodeByQuery(c
,cmd
,c
->argv
,c
->argc
,&hashslot
);
1089 addReplyError(c
,"Invalid cross-node request");
1091 } else if (n
!= server
.cluster
.myself
) {
1092 addReplySds(c
,sdscatprintf(sdsempty(),
1093 "-MOVED %d %s:%d\r\n",hashslot
,n
->ip
,n
->port
));
1099 /* Handle the maxmemory directive.
1101 * First we try to free some memory if possible (if there are volatile
1102 * keys in the dataset). If there are not the only thing we can do
1103 * is returning an error. */
1104 if (server
.maxmemory
) freeMemoryIfNeeded();
1105 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1106 zmalloc_used_memory() > server
.maxmemory
)
1108 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1112 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1113 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1115 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
1116 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
1117 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1121 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1122 * we are a slave with a broken link with master. */
1123 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1124 server
.repl_serve_stale_data
== 0 &&
1125 cmd
->proc
!= infoCommand
&& cmd
->proc
!= slaveofCommand
)
1128 "link with MASTER is down and slave-serve-stale-data is set to no");
1132 /* Loading DB? Return an error if the command is not INFO */
1133 if (server
.loading
&& cmd
->proc
!= infoCommand
) {
1134 addReply(c
, shared
.loadingerr
);
1138 /* Exec the command */
1139 if (c
->flags
& REDIS_MULTI
&&
1140 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
1141 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
1143 queueMultiCommand(c
,cmd
);
1144 addReply(c
,shared
.queued
);
1146 if (server
.ds_enabled
&& blockClientOnSwappedKeys(c
,cmd
))
1153 /*================================== Shutdown =============================== */
1155 int prepareForShutdown() {
1156 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1157 /* Kill the saving child if there is a background saving in progress.
1158 We want to avoid race conditions, for instance our saving child may
1159 overwrite the synchronous saving did by SHUTDOWN. */
1160 if (server
.bgsavechildpid
!= -1) {
1161 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
1162 kill(server
.bgsavechildpid
,SIGKILL
);
1163 rdbRemoveTempFile(server
.bgsavechildpid
);
1165 if (server
.ds_enabled
) {
1166 /* FIXME: flush all objects on disk */
1167 } else if (server
.appendonly
) {
1168 /* Append only file: fsync() the AOF and exit */
1169 aof_fsync(server
.appendfd
);
1170 } else if (server
.saveparamslen
> 0) {
1171 /* Snapshotting. Perform a SYNC SAVE and exit */
1172 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1173 /* Ooops.. error saving! The best we can do is to continue
1174 * operating. Note that if there was a background saving process,
1175 * in the next cron() Redis will be notified that the background
1176 * saving aborted, handling special stuff like slaves pending for
1177 * synchronization... */
1178 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1182 redisLog(REDIS_WARNING
,"Not saving DB.");
1184 if (server
.daemonize
) unlink(server
.pidfile
);
1185 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1189 /*================================== Commands =============================== */
1191 void authCommand(redisClient
*c
) {
1192 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1193 c
->authenticated
= 1;
1194 addReply(c
,shared
.ok
);
1196 c
->authenticated
= 0;
1197 addReplyError(c
,"invalid password");
1201 void pingCommand(redisClient
*c
) {
1202 addReply(c
,shared
.pong
);
1205 void echoCommand(redisClient
*c
) {
1206 addReplyBulk(c
,c
->argv
[1]);
1209 /* Convert an amount of bytes into a human readable string in the form
1210 * of 100B, 2G, 100M, 4K, and so forth. */
1211 void bytesToHuman(char *s
, unsigned long long n
) {
1216 sprintf(s
,"%lluB",n
);
1218 } else if (n
< (1024*1024)) {
1219 d
= (double)n
/(1024);
1220 sprintf(s
,"%.2fK",d
);
1221 } else if (n
< (1024LL*1024*1024)) {
1222 d
= (double)n
/(1024*1024);
1223 sprintf(s
,"%.2fM",d
);
1224 } else if (n
< (1024LL*1024*1024*1024)) {
1225 d
= (double)n
/(1024LL*1024*1024);
1226 sprintf(s
,"%.2fG",d
);
1230 /* Create the string returned by the INFO command. This is decoupled
1231 * by the INFO command itself as we need to report the same information
1232 * on memory corruption problems. */
1233 sds
genRedisInfoString(char *section
) {
1234 sds info
= sdsempty();
1235 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1238 struct rusage self_ru
, c_ru
;
1239 unsigned long lol
, bib
;
1240 int allsections
= 0, defsections
= 0;
1244 allsections
= strcasecmp(section
,"all") == 0;
1245 defsections
= strcasecmp(section
,"default") == 0;
1248 getrusage(RUSAGE_SELF
, &self_ru
);
1249 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1250 getClientsMaxBuffers(&lol
,&bib
);
1251 bytesToHuman(hmem
,zmalloc_used_memory());
1254 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1255 if (sections
++) info
= sdscat(info
,"\r\n");
1256 info
= sdscatprintf(info
,
1258 "redis_version:%s\r\n"
1259 "redis_git_sha1:%s\r\n"
1260 "redis_git_dirty:%d\r\n"
1262 "multiplexing_api:%s\r\n"
1263 "process_id:%ld\r\n"
1265 "uptime_in_seconds:%ld\r\n"
1266 "uptime_in_days:%ld\r\n"
1267 "lru_clock:%ld\r\n",
1270 strtol(redisGitDirty(),NULL
,10) > 0,
1271 (sizeof(long) == 8) ? "64" : "32",
1277 (unsigned long) server
.lruclock
);
1281 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1282 if (sections
++) info
= sdscat(info
,"\r\n");
1283 info
= sdscatprintf(info
,
1285 "connected_clients:%d\r\n"
1286 "client_longest_output_list:%lu\r\n"
1287 "client_biggest_input_buf:%lu\r\n"
1288 "blocked_clients:%d\r\n",
1289 listLength(server
.clients
)-listLength(server
.slaves
),
1291 server
.bpop_blocked_clients
);
1295 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1296 if (sections
++) info
= sdscat(info
,"\r\n");
1297 info
= sdscatprintf(info
,
1299 "used_memory:%zu\r\n"
1300 "used_memory_human:%s\r\n"
1301 "used_memory_rss:%zu\r\n"
1302 "mem_fragmentation_ratio:%.2f\r\n"
1303 "use_tcmalloc:%d\r\n",
1304 zmalloc_used_memory(),
1307 zmalloc_get_fragmentation_ratio(),
1316 /* Allocation statistics */
1317 if (allsections
|| !strcasecmp(section
,"allocstats")) {
1318 if (sections
++) info
= sdscat(info
,"\r\n");
1319 info
= sdscat(info
, "# Allocstats\r\nallocation_stats:");
1320 for (j
= 0; j
<= ZMALLOC_MAX_ALLOC_STAT
; j
++) {
1321 size_t count
= zmalloc_allocations_for_size(j
);
1323 if (info
[sdslen(info
)-1] != ':') info
= sdscatlen(info
,",",1);
1324 info
= sdscatprintf(info
,"%s%d=%zu",
1325 (j
== ZMALLOC_MAX_ALLOC_STAT
) ? ">=" : "",
1329 info
= sdscat(info
,"\r\n");
1333 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1334 if (sections
++) info
= sdscat(info
,"\r\n");
1335 info
= sdscatprintf(info
,
1338 "aof_enabled:%d\r\n"
1339 "changes_since_last_save:%lld\r\n"
1340 "bgsave_in_progress:%d\r\n"
1341 "last_save_time:%ld\r\n"
1342 "bgrewriteaof_in_progress:%d\r\n",
1346 server
.bgsavechildpid
!= -1 ||
1347 server
.bgsavethread
!= (pthread_t
) -1,
1349 server
.bgrewritechildpid
!= -1);
1351 if (server
.loading
) {
1353 time_t eta
, elapsed
;
1354 off_t remaining_bytes
= server
.loading_total_bytes
-
1355 server
.loading_loaded_bytes
;
1357 perc
= ((double)server
.loading_loaded_bytes
/
1358 server
.loading_total_bytes
) * 100;
1360 elapsed
= time(NULL
)-server
.loading_start_time
;
1362 eta
= 1; /* A fake 1 second figure if we don't have
1365 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1368 info
= sdscatprintf(info
,
1369 "loading_start_time:%ld\r\n"
1370 "loading_total_bytes:%llu\r\n"
1371 "loading_loaded_bytes:%llu\r\n"
1372 "loading_loaded_perc:%.2f\r\n"
1373 "loading_eta_seconds:%ld\r\n"
1374 ,(unsigned long) server
.loading_start_time
,
1375 (unsigned long long) server
.loading_total_bytes
,
1376 (unsigned long long) server
.loading_loaded_bytes
,
1384 if (allsections
|| defsections
|| !strcasecmp(section
,"diskstore")) {
1385 if (sections
++) info
= sdscat(info
,"\r\n");
1386 info
= sdscatprintf(info
,
1388 "ds_enabled:%d\r\n",
1389 server
.ds_enabled
!= 0);
1390 if (server
.ds_enabled
) {
1392 info
= sdscatprintf(info
,
1393 "cache_max_memory:%llu\r\n"
1394 "cache_blocked_clients:%lu\r\n"
1395 "cache_io_queue_len:%lu\r\n"
1396 "cache_io_jobs_new:%lu\r\n"
1397 "cache_io_jobs_processing:%lu\r\n"
1398 "cache_io_jobs_processed:%lu\r\n"
1399 "cache_io_ready_clients:%lu\r\n"
1400 ,(unsigned long long) server
.cache_max_memory
,
1401 (unsigned long) server
.cache_blocked_clients
,
1402 (unsigned long) listLength(server
.cache_io_queue
),
1403 (unsigned long) listLength(server
.io_newjobs
),
1404 (unsigned long) listLength(server
.io_processing
),
1405 (unsigned long) listLength(server
.io_processed
),
1406 (unsigned long) listLength(server
.io_ready_clients
)
1413 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1414 if (sections
++) info
= sdscat(info
,"\r\n");
1415 info
= sdscatprintf(info
,
1417 "total_connections_received:%lld\r\n"
1418 "total_commands_processed:%lld\r\n"
1419 "expired_keys:%lld\r\n"
1420 "evicted_keys:%lld\r\n"
1421 "keyspace_hits:%lld\r\n"
1422 "keyspace_misses:%lld\r\n"
1423 "pubsub_channels:%ld\r\n"
1424 "pubsub_patterns:%u\r\n",
1425 server
.stat_numconnections
,
1426 server
.stat_numcommands
,
1427 server
.stat_expiredkeys
,
1428 server
.stat_evictedkeys
,
1429 server
.stat_keyspace_hits
,
1430 server
.stat_keyspace_misses
,
1431 dictSize(server
.pubsub_channels
),
1432 listLength(server
.pubsub_patterns
));
1436 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1437 if (sections
++) info
= sdscat(info
,"\r\n");
1438 info
= sdscatprintf(info
,
1441 server
.masterhost
== NULL
? "master" : "slave");
1442 if (server
.masterhost
) {
1443 info
= sdscatprintf(info
,
1444 "master_host:%s\r\n"
1445 "master_port:%d\r\n"
1446 "master_link_status:%s\r\n"
1447 "master_last_io_seconds_ago:%d\r\n"
1448 "master_sync_in_progress:%d\r\n"
1451 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1454 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1455 server
.replstate
== REDIS_REPL_TRANSFER
1458 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1459 info
= sdscatprintf(info
,
1460 "master_sync_left_bytes:%ld\r\n"
1461 "master_sync_last_io_seconds_ago:%d\r\n"
1462 ,(long)server
.repl_transfer_left
,
1463 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1467 info
= sdscatprintf(info
,
1468 "connected_slaves:%d\r\n",
1469 listLength(server
.slaves
));
1473 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1474 if (sections
++) info
= sdscat(info
,"\r\n");
1475 info
= sdscatprintf(info
,
1477 "used_cpu_sys:%.2f\r\n"
1478 "used_cpu_user:%.2f\r\n"
1479 "used_cpu_sys_childrens:%.2f\r\n"
1480 "used_cpu_user_childrens:%.2f\r\n",
1481 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1482 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1483 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1484 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000);
1488 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1489 if (sections
++) info
= sdscat(info
,"\r\n");
1490 info
= sdscatprintf(info
, "# Commandstats\r\n");
1491 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1492 for (j
= 0; j
< numcommands
; j
++) {
1493 struct redisCommand
*c
= redisCommandTable
+j
;
1495 if (!c
->calls
) continue;
1496 info
= sdscatprintf(info
,
1497 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1498 c
->name
, c
->calls
, c
->microseconds
,
1499 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1504 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1505 if (sections
++) info
= sdscat(info
,"\r\n");
1506 info
= sdscatprintf(info
, "# Keyspace\r\n");
1507 for (j
= 0; j
< server
.dbnum
; j
++) {
1508 long long keys
, vkeys
;
1510 keys
= dictSize(server
.db
[j
].dict
);
1511 vkeys
= dictSize(server
.db
[j
].expires
);
1512 if (keys
|| vkeys
) {
1513 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1521 void infoCommand(redisClient
*c
) {
1522 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1525 addReply(c
,shared
.syntaxerr
);
1528 sds info
= genRedisInfoString(section
);
1529 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1530 (unsigned long)sdslen(info
)));
1531 addReplySds(c
,info
);
1532 addReply(c
,shared
.crlf
);
1535 void monitorCommand(redisClient
*c
) {
1536 /* ignore MONITOR if aleady slave or in monitor mode */
1537 if (c
->flags
& REDIS_SLAVE
) return;
1539 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1541 listAddNodeTail(server
.monitors
,c
);
1542 addReply(c
,shared
.ok
);
1545 /* ============================ Maxmemory directive ======================== */
1547 /* This function gets called when 'maxmemory' is set on the config file to limit
1548 * the max memory used by the server, and we are out of memory.
1549 * This function will try to, in order:
1551 * - Free objects from the free list
1552 * - Try to remove keys with an EXPIRE set
1554 * It is not possible to free enough memory to reach used-memory < maxmemory
1555 * the server will start refusing commands that will enlarge even more the
1558 void freeMemoryIfNeeded(void) {
1559 /* Remove keys accordingly to the active policy as long as we are
1560 * over the memory limit. */
1561 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1563 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1564 int j
, k
, freed
= 0;
1566 for (j
= 0; j
< server
.dbnum
; j
++) {
1567 long bestval
= 0; /* just to prevent warning */
1569 struct dictEntry
*de
;
1570 redisDb
*db
= server
.db
+j
;
1573 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1574 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1576 dict
= server
.db
[j
].dict
;
1578 dict
= server
.db
[j
].expires
;
1580 if (dictSize(dict
) == 0) continue;
1582 /* volatile-random and allkeys-random policy */
1583 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1584 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1586 de
= dictGetRandomKey(dict
);
1587 bestkey
= dictGetEntryKey(de
);
1590 /* volatile-lru and allkeys-lru policy */
1591 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1592 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1594 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1599 de
= dictGetRandomKey(dict
);
1600 thiskey
= dictGetEntryKey(de
);
1601 /* When policy is volatile-lru we need an additonal lookup
1602 * to locate the real key, as dict is set to db->expires. */
1603 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1604 de
= dictFind(db
->dict
, thiskey
);
1605 o
= dictGetEntryVal(de
);
1606 thisval
= estimateObjectIdleTime(o
);
1608 /* Higher idle time is better candidate for deletion */
1609 if (bestkey
== NULL
|| thisval
> bestval
) {
1617 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1618 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1622 de
= dictGetRandomKey(dict
);
1623 thiskey
= dictGetEntryKey(de
);
1624 thisval
= (long) dictGetEntryVal(de
);
1626 /* Expire sooner (minor expire unix timestamp) is better
1627 * candidate for deletion */
1628 if (bestkey
== NULL
|| thisval
< bestval
) {
1635 /* Finally remove the selected key. */
1637 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1638 propagateExpire(db
,keyobj
);
1639 dbDelete(db
,keyobj
);
1640 server
.stat_evictedkeys
++;
1641 decrRefCount(keyobj
);
1645 if (!freed
) return; /* nothing to free... */
1649 /* =================================== Main! ================================ */
1652 int linuxOvercommitMemoryValue(void) {
1653 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1657 if (fgets(buf
,64,fp
) == NULL
) {
1666 void linuxOvercommitMemoryWarning(void) {
1667 if (linuxOvercommitMemoryValue() == 0) {
1668 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.");
1671 #endif /* __linux__ */
1673 void createPidFile(void) {
1674 /* Try to write the pid file in a best-effort way. */
1675 FILE *fp
= fopen(server
.pidfile
,"w");
1677 fprintf(fp
,"%d\n",(int)getpid());
1682 void daemonize(void) {
1685 if (fork() != 0) exit(0); /* parent exits */
1686 setsid(); /* create a new session */
1688 /* Every output goes to /dev/null. If Redis is daemonized but
1689 * the 'logfile' is set to 'stdout' in the configuration file
1690 * it will not log at all. */
1691 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1692 dup2(fd
, STDIN_FILENO
);
1693 dup2(fd
, STDOUT_FILENO
);
1694 dup2(fd
, STDERR_FILENO
);
1695 if (fd
> STDERR_FILENO
) close(fd
);
1700 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1701 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1706 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1707 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1711 int main(int argc
, char **argv
) {
1716 if (strcmp(argv
[1], "-v") == 0 ||
1717 strcmp(argv
[1], "--version") == 0) version();
1718 if (strcmp(argv
[1], "--help") == 0) usage();
1719 resetServerSaveParams();
1720 loadServerConfig(argv
[1]);
1721 } else if ((argc
> 2)) {
1724 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'");
1726 if (server
.daemonize
) daemonize();
1728 if (server
.daemonize
) createPidFile();
1729 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1731 linuxOvercommitMemoryWarning();
1734 if (server
.ds_enabled
) {
1735 redisLog(REDIS_NOTICE
,"DB not loaded (running with disk back end)");
1736 } else if (server
.appendonly
) {
1737 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1738 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1740 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1741 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",(float)(ustime()-start
)/1000000);
1743 if (server
.ipfd
> 0)
1744 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1745 if (server
.sofd
> 0)
1746 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1747 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1749 aeDeleteEventLoop(server
.el
);
1753 #ifdef HAVE_BACKTRACE
1754 static void *getMcontextEip(ucontext_t
*uc
) {
1755 #if defined(__FreeBSD__)
1756 return (void*) uc
->uc_mcontext
.mc_eip
;
1757 #elif defined(__dietlibc__)
1758 return (void*) uc
->uc_mcontext
.eip
;
1759 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1761 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1763 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1765 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1766 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1767 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1769 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1771 #elif defined(__i386__)
1772 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1773 #elif defined(__X86_64__) || defined(__x86_64__)
1774 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1775 #elif defined(__ia64__) /* Linux IA64 */
1776 return (void*) uc
->uc_mcontext
.sc_ip
;
1782 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1784 char **messages
= NULL
;
1785 int i
, trace_size
= 0;
1786 ucontext_t
*uc
= (ucontext_t
*) secret
;
1788 struct sigaction act
;
1789 REDIS_NOTUSED(info
);
1791 redisLog(REDIS_WARNING
,
1792 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1793 infostring
= genRedisInfoString("all");
1794 redisLogRaw(REDIS_WARNING
, infostring
);
1795 /* It's not safe to sdsfree() the returned string under memory
1796 * corruption conditions. Let it leak as we are going to abort */
1798 trace_size
= backtrace(trace
, 100);
1799 /* overwrite sigaction with caller's address */
1800 if (getMcontextEip(uc
) != NULL
) {
1801 trace
[1] = getMcontextEip(uc
);
1803 messages
= backtrace_symbols(trace
, trace_size
);
1805 for (i
=1; i
<trace_size
; ++i
)
1806 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1808 /* free(messages); Don't call free() with possibly corrupted memory. */
1809 if (server
.daemonize
) unlink(server
.pidfile
);
1811 /* Make sure we exit with the right signal at the end. So for instance
1812 * the core will be dumped if enabled. */
1813 sigemptyset (&act
.sa_mask
);
1814 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1815 * is used. Otherwise, sa_handler is used */
1816 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1817 act
.sa_handler
= SIG_DFL
;
1818 sigaction (sig
, &act
, NULL
);
1821 #endif /* HAVE_BACKTRACE */
1823 static void sigtermHandler(int sig
) {
1826 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1827 server
.shutdown_asap
= 1;
1830 void setupSignalHandlers(void) {
1831 struct sigaction act
;
1833 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1834 * Otherwise, sa_handler is used. */
1835 sigemptyset(&act
.sa_mask
);
1836 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1837 act
.sa_handler
= sigtermHandler
;
1838 sigaction(SIGTERM
, &act
, NULL
);
1840 #ifdef HAVE_BACKTRACE
1841 sigemptyset(&act
.sa_mask
);
1842 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1843 act
.sa_sigaction
= sigsegvHandler
;
1844 sigaction(SIGSEGV
, &act
, NULL
);
1845 sigaction(SIGBUS
, &act
, NULL
);
1846 sigaction(SIGFPE
, &act
, NULL
);
1847 sigaction(SIGILL
, &act
, NULL
);