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.
36 #endif /* HAVE_BACKTRACE */
45 #include <arpa/inet.h>
49 #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},
196 {"client",clientCommand
,-2,0,NULL
,0,0,0,0,0},
197 {"slowlog",slowlogCommand
,-2,0,NULL
,0,0,0,0,0}
200 /*============================ Utility functions ============================ */
202 /* Low level logging. To use only for very big messages, otherwise
203 * redisLog() is to prefer. */
204 void redisLogRaw(int level
, const char *msg
) {
205 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
206 const char *c
= ".-*#";
207 time_t now
= time(NULL
);
210 int rawmode
= (level
& REDIS_LOG_RAW
);
212 level
&= 0xff; /* clear flags */
213 if (level
< server
.verbosity
) return;
215 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
219 fprintf(fp
,"%s",msg
);
221 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
222 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
226 if (server
.logfile
) fclose(fp
);
228 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
231 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
232 * is used across the code. The raw version is only used in order to dump
233 * the INFO output on crash. */
234 void redisLog(int level
, const char *fmt
, ...) {
236 char msg
[REDIS_MAX_LOGMSG_LEN
];
238 if ((level
&0xff) < server
.verbosity
) return;
241 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
244 redisLogRaw(level
,msg
);
247 /* Redis generally does not try to recover from out of memory conditions
248 * when allocating objects or strings, it is not clear if it will be possible
249 * to report this condition to the client since the networking layer itself
250 * is based on heap allocation for send buffers, so we simply abort.
251 * At least the code will be simpler to read... */
252 void oom(const char *msg
) {
253 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
258 /* Return the UNIX time in microseconds */
259 long long ustime(void) {
263 gettimeofday(&tv
, NULL
);
264 ust
= ((long long)tv
.tv_sec
)*1000000;
269 /*====================== Hash table type implementation ==================== */
271 /* This is an hash table type that uses the SDS dynamic strings libary as
272 * keys and radis objects as values (objects can hold SDS strings,
275 void dictVanillaFree(void *privdata
, void *val
)
277 DICT_NOTUSED(privdata
);
281 void dictListDestructor(void *privdata
, void *val
)
283 DICT_NOTUSED(privdata
);
284 listRelease((list
*)val
);
287 int dictSdsKeyCompare(void *privdata
, const void *key1
,
291 DICT_NOTUSED(privdata
);
293 l1
= sdslen((sds
)key1
);
294 l2
= sdslen((sds
)key2
);
295 if (l1
!= l2
) return 0;
296 return memcmp(key1
, key2
, l1
) == 0;
299 /* A case insensitive version used for the command lookup table. */
300 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
303 DICT_NOTUSED(privdata
);
305 return strcasecmp(key1
, key2
) == 0;
308 void dictRedisObjectDestructor(void *privdata
, void *val
)
310 DICT_NOTUSED(privdata
);
312 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
316 void dictSdsDestructor(void *privdata
, void *val
)
318 DICT_NOTUSED(privdata
);
323 int dictObjKeyCompare(void *privdata
, const void *key1
,
326 const robj
*o1
= key1
, *o2
= key2
;
327 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
330 unsigned int dictObjHash(const void *key
) {
332 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
335 unsigned int dictSdsHash(const void *key
) {
336 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
339 unsigned int dictSdsCaseHash(const void *key
) {
340 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
343 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
346 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
349 if (o1
->encoding
== REDIS_ENCODING_INT
&&
350 o2
->encoding
== REDIS_ENCODING_INT
)
351 return o1
->ptr
== o2
->ptr
;
353 o1
= getDecodedObject(o1
);
354 o2
= getDecodedObject(o2
);
355 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
361 unsigned int dictEncObjHash(const void *key
) {
362 robj
*o
= (robj
*) key
;
364 if (o
->encoding
== REDIS_ENCODING_RAW
) {
365 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
367 if (o
->encoding
== REDIS_ENCODING_INT
) {
371 len
= ll2string(buf
,32,(long)o
->ptr
);
372 return dictGenHashFunction((unsigned char*)buf
, len
);
376 o
= getDecodedObject(o
);
377 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
384 /* Sets type and diskstore negative caching hash table */
385 dictType setDictType
= {
386 dictEncObjHash
, /* hash function */
389 dictEncObjKeyCompare
, /* key compare */
390 dictRedisObjectDestructor
, /* key destructor */
391 NULL
/* val destructor */
394 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
395 dictType zsetDictType
= {
396 dictEncObjHash
, /* hash function */
399 dictEncObjKeyCompare
, /* key compare */
400 dictRedisObjectDestructor
, /* key destructor */
401 NULL
/* val destructor */
404 /* Db->dict, keys are sds strings, vals are Redis objects. */
405 dictType dbDictType
= {
406 dictSdsHash
, /* hash function */
409 dictSdsKeyCompare
, /* key compare */
410 dictSdsDestructor
, /* key destructor */
411 dictRedisObjectDestructor
/* val destructor */
415 dictType keyptrDictType
= {
416 dictSdsHash
, /* hash function */
419 dictSdsKeyCompare
, /* key compare */
420 NULL
, /* key destructor */
421 NULL
/* val destructor */
424 /* Command table. sds string -> command struct pointer. */
425 dictType commandTableDictType
= {
426 dictSdsCaseHash
, /* hash function */
429 dictSdsKeyCaseCompare
, /* key compare */
430 dictSdsDestructor
, /* key destructor */
431 NULL
/* val destructor */
434 /* Hash type hash table (note that small hashes are represented with zimpaps) */
435 dictType hashDictType
= {
436 dictEncObjHash
, /* hash function */
439 dictEncObjKeyCompare
, /* key compare */
440 dictRedisObjectDestructor
, /* key destructor */
441 dictRedisObjectDestructor
/* val destructor */
444 /* Keylist hash table type has unencoded redis objects as keys and
445 * lists as values. It's used for blocking operations (BLPOP) and to
446 * map swapped keys to a list of clients waiting for this keys to be loaded. */
447 dictType keylistDictType
= {
448 dictObjHash
, /* hash function */
451 dictObjKeyCompare
, /* key compare */
452 dictRedisObjectDestructor
, /* key destructor */
453 dictListDestructor
/* val destructor */
456 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
457 * clusterNode structures. */
458 dictType clusterNodesDictType
= {
459 dictSdsHash
, /* hash function */
462 dictSdsKeyCompare
, /* key compare */
463 dictSdsDestructor
, /* key destructor */
464 NULL
/* val destructor */
467 int htNeedsResize(dict
*dict
) {
468 long long size
, used
;
470 size
= dictSlots(dict
);
471 used
= dictSize(dict
);
472 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
473 (used
*100/size
< REDIS_HT_MINFILL
));
476 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
477 * we resize the hash table to save memory */
478 void tryResizeHashTables(void) {
481 for (j
= 0; j
< server
.dbnum
; j
++) {
482 if (htNeedsResize(server
.db
[j
].dict
))
483 dictResize(server
.db
[j
].dict
);
484 if (htNeedsResize(server
.db
[j
].expires
))
485 dictResize(server
.db
[j
].expires
);
489 /* Our hash table implementation performs rehashing incrementally while
490 * we write/read from the hash table. Still if the server is idle, the hash
491 * table will use two tables for a long time. So we try to use 1 millisecond
492 * of CPU time at every serverCron() loop in order to rehash some key. */
493 void incrementallyRehash(void) {
496 for (j
= 0; j
< server
.dbnum
; j
++) {
497 if (dictIsRehashing(server
.db
[j
].dict
)) {
498 dictRehashMilliseconds(server
.db
[j
].dict
,1);
499 break; /* already used our millisecond for this loop... */
504 /* This function is called once a background process of some kind terminates,
505 * as we want to avoid resizing the hash tables when there is a child in order
506 * to play well with copy-on-write (otherwise when a resize happens lots of
507 * memory pages are copied). The goal of this function is to update the ability
508 * for dict.c to resize the hash tables accordingly to the fact we have o not
510 void updateDictResizePolicy(void) {
511 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
517 /* ======================= Cron: called every 100 ms ======================== */
519 /* Try to expire a few timed out keys. The algorithm used is adaptive and
520 * will use few CPU cycles if there are few expiring keys, otherwise
521 * it will get more aggressive to avoid that too much memory is used by
522 * keys that can be removed from the keyspace. */
523 void activeExpireCycle(void) {
526 for (j
= 0; j
< server
.dbnum
; j
++) {
528 redisDb
*db
= server
.db
+j
;
530 /* Continue to expire if at the end of the cycle more than 25%
531 * of the keys were expired. */
533 long num
= dictSize(db
->expires
);
534 time_t now
= time(NULL
);
537 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
538 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
543 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
544 t
= (time_t) dictGetEntryVal(de
);
546 sds key
= dictGetEntryKey(de
);
547 robj
*keyobj
= createStringObject(key
,sdslen(key
));
549 propagateExpire(db
,keyobj
);
551 decrRefCount(keyobj
);
553 server
.stat_expiredkeys
++;
556 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
560 void updateLRUClock(void) {
561 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
565 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
566 int j
, loops
= server
.cronloops
;
567 REDIS_NOTUSED(eventLoop
);
569 REDIS_NOTUSED(clientData
);
571 /* We take a cached value of the unix time in the global state because
572 * with virtual memory and aging there is to store the current time
573 * in objects at every object access, and accuracy is not needed.
574 * To access a global var is faster than calling time(NULL) */
575 server
.unixtime
= time(NULL
);
576 /* We have just 22 bits per object for LRU information.
577 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
578 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
580 * Note that even if this will wrap after 1.5 years it's not a problem,
581 * everything will still work but just some object will appear younger
582 * to Redis. But for this to happen a given object should never be touched
585 * Note that you can change the resolution altering the
586 * REDIS_LRU_CLOCK_RESOLUTION define.
590 /* Record the max memory used since the server was started. */
591 if (zmalloc_used_memory() > server
.stat_peak_memory
)
592 server
.stat_peak_memory
= zmalloc_used_memory();
594 /* We received a SIGTERM, shutting down here in a safe way, as it is
595 * not ok doing so inside the signal handler. */
596 if (server
.shutdown_asap
) {
597 if (prepareForShutdown() == REDIS_OK
) exit(0);
598 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
601 /* Show some info about non-empty databases */
602 for (j
= 0; j
< server
.dbnum
; j
++) {
603 long long size
, used
, vkeys
;
605 size
= dictSlots(server
.db
[j
].dict
);
606 used
= dictSize(server
.db
[j
].dict
);
607 vkeys
= dictSize(server
.db
[j
].expires
);
608 if (!(loops
% 50) && (used
|| vkeys
)) {
609 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
610 /* dictPrintStats(server.dict); */
614 /* We don't want to resize the hash tables while a bacground saving
615 * is in progress: the saving child is created using fork() that is
616 * implemented with a copy-on-write semantic in most modern systems, so
617 * if we resize the HT while there is the saving child at work actually
618 * a lot of memory movements in the parent will cause a lot of pages
620 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
621 if (!(loops
% 10)) tryResizeHashTables();
622 if (server
.activerehashing
) incrementallyRehash();
625 /* Show information about connected clients */
627 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
628 listLength(server
.clients
)-listLength(server
.slaves
),
629 listLength(server
.slaves
),
630 zmalloc_used_memory());
633 /* Close connections of timedout clients */
634 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
635 closeTimedoutClients();
637 /* Start a scheduled AOF rewrite if this was requested by the user while
638 * a BGSAVE was in progress. */
639 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1 &&
640 server
.aofrewrite_scheduled
)
642 rewriteAppendOnlyFileBackground();
645 /* Check if a background saving or AOF rewrite in progress terminated. */
646 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
650 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
651 int exitcode
= WEXITSTATUS(statloc
);
654 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
656 if (pid
== server
.bgsavechildpid
) {
657 backgroundSaveDoneHandler(exitcode
,bysignal
);
659 backgroundRewriteDoneHandler(exitcode
,bysignal
);
661 updateDictResizePolicy();
664 time_t now
= time(NULL
);
666 /* If there is not a background saving/rewrite in progress check if
667 * we have to save/rewrite now */
668 for (j
= 0; j
< server
.saveparamslen
; j
++) {
669 struct saveparam
*sp
= server
.saveparams
+j
;
671 if (server
.dirty
>= sp
->changes
&&
672 now
-server
.lastsave
> sp
->seconds
) {
673 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
674 sp
->changes
, sp
->seconds
);
675 rdbSaveBackground(server
.dbfilename
);
680 /* Trigger an AOF rewrite if needed */
681 if (server
.bgsavechildpid
== -1 &&
682 server
.bgrewritechildpid
== -1 &&
683 server
.auto_aofrewrite_perc
&&
684 server
.appendonly_current_size
> server
.auto_aofrewrite_min_size
)
686 int base
= server
.auto_aofrewrite_base_size
?
687 server
.auto_aofrewrite_base_size
: 1;
688 long long growth
= (server
.appendonly_current_size
*100/base
) - 100;
689 if (growth
>= server
.auto_aofrewrite_perc
) {
690 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
691 rewriteAppendOnlyFileBackground();
696 /* Expire a few keys per cycle, only if this is a master.
697 * On slaves we wait for DEL operations synthesized by the master
698 * in order to guarantee a strict consistency. */
699 if (server
.masterhost
== NULL
) activeExpireCycle();
701 /* Replication cron function -- used to reconnect to master and
702 * to detect transfer failures. */
703 if (!(loops
% 10)) replicationCron();
705 /* Run other sub-systems specific cron jobs */
706 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
712 /* This function gets called every time Redis is entering the
713 * main loop of the event driven library, that is, before to sleep
714 * for ready file descriptors. */
715 void beforeSleep(struct aeEventLoop
*eventLoop
) {
716 REDIS_NOTUSED(eventLoop
);
720 /* Try to process pending commands for clients that were just unblocked. */
721 while (listLength(server
.unblocked_clients
)) {
722 ln
= listFirst(server
.unblocked_clients
);
723 redisAssert(ln
!= NULL
);
725 listDelNode(server
.unblocked_clients
,ln
);
726 c
->flags
&= ~REDIS_UNBLOCKED
;
728 /* Process remaining data in the input buffer. */
729 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
730 processInputBuffer(c
);
733 /* Write the AOF buffer on disk */
734 flushAppendOnlyFile();
737 /* =========================== Server initialization ======================== */
739 void createSharedObjects(void) {
742 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
743 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
744 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
745 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
746 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
747 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
748 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
749 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
750 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
751 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
752 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
753 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
754 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
755 "-ERR Operation against a key holding the wrong kind of value\r\n"));
756 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
757 "-ERR no such key\r\n"));
758 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
759 "-ERR syntax error\r\n"));
760 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
761 "-ERR source and destination objects are the same\r\n"));
762 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
763 "-ERR index out of range\r\n"));
764 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
765 "-LOADING Redis is loading the dataset in memory\r\n"));
766 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
767 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
768 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
769 shared
.select0
= createStringObject("select 0\r\n",10);
770 shared
.select1
= createStringObject("select 1\r\n",10);
771 shared
.select2
= createStringObject("select 2\r\n",10);
772 shared
.select3
= createStringObject("select 3\r\n",10);
773 shared
.select4
= createStringObject("select 4\r\n",10);
774 shared
.select5
= createStringObject("select 5\r\n",10);
775 shared
.select6
= createStringObject("select 6\r\n",10);
776 shared
.select7
= createStringObject("select 7\r\n",10);
777 shared
.select8
= createStringObject("select 8\r\n",10);
778 shared
.select9
= createStringObject("select 9\r\n",10);
779 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
780 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
781 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
782 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
783 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
784 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
785 shared
.mbulk3
= createStringObject("*3\r\n",4);
786 shared
.mbulk4
= createStringObject("*4\r\n",4);
787 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
788 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
789 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
793 void initServerConfig() {
794 server
.port
= REDIS_SERVERPORT
;
795 server
.bindaddr
= NULL
;
796 server
.unixsocket
= NULL
;
799 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
800 server
.verbosity
= REDIS_VERBOSE
;
801 server
.maxidletime
= REDIS_MAXIDLETIME
;
802 server
.saveparams
= NULL
;
804 server
.logfile
= NULL
; /* NULL = log on standard output */
805 server
.syslog_enabled
= 0;
806 server
.syslog_ident
= zstrdup("redis");
807 server
.syslog_facility
= LOG_LOCAL0
;
808 server
.daemonize
= 0;
809 server
.appendonly
= 0;
810 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
811 server
.no_appendfsync_on_rewrite
= 0;
812 server
.auto_aofrewrite_perc
= REDIS_AUTO_AOFREWRITE_PERC
;
813 server
.auto_aofrewrite_min_size
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
;
814 server
.auto_aofrewrite_base_size
= 0;
815 server
.aofrewrite_scheduled
= 0;
816 server
.lastfsync
= time(NULL
);
817 server
.appendfd
= -1;
818 server
.appendseldb
= -1; /* Make sure the first time will not match */
819 server
.pidfile
= zstrdup("/var/run/redis.pid");
820 server
.dbfilename
= zstrdup("dump.rdb");
821 server
.appendfilename
= zstrdup("appendonly.aof");
822 server
.requirepass
= NULL
;
823 server
.rdbcompression
= 1;
824 server
.activerehashing
= 1;
825 server
.maxclients
= 0;
826 server
.bpop_blocked_clients
= 0;
827 server
.maxmemory
= 0;
828 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
829 server
.maxmemory_samples
= 3;
830 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
831 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
832 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
833 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
834 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
835 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
836 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
837 server
.shutdown_asap
= 0;
838 server
.cluster_enabled
= 0;
839 server
.cluster
.configfile
= zstrdup("nodes.conf");
842 resetServerSaveParams();
844 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
845 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
846 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
847 /* Replication related */
849 server
.masterauth
= NULL
;
850 server
.masterhost
= NULL
;
851 server
.masterport
= 6379;
852 server
.master
= NULL
;
853 server
.replstate
= REDIS_REPL_NONE
;
854 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
855 server
.repl_serve_stale_data
= 1;
856 server
.repl_down_since
= -1;
858 /* Double constants initialization */
860 R_PosInf
= 1.0/R_Zero
;
861 R_NegInf
= -1.0/R_Zero
;
862 R_Nan
= R_Zero
/R_Zero
;
864 /* Command table -- we intiialize it here as it is part of the
865 * initial configuration, since command names may be changed via
866 * redis.conf using the rename-command directive. */
867 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
868 populateCommandTable();
869 server
.delCommand
= lookupCommandByCString("del");
870 server
.multiCommand
= lookupCommandByCString("multi");
873 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
874 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
880 signal(SIGHUP
, SIG_IGN
);
881 signal(SIGPIPE
, SIG_IGN
);
882 setupSignalHandlers();
884 if (server
.syslog_enabled
) {
885 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
886 server
.syslog_facility
);
889 server
.clients
= listCreate();
890 server
.slaves
= listCreate();
891 server
.monitors
= listCreate();
892 server
.unblocked_clients
= listCreate();
894 createSharedObjects();
895 server
.el
= aeCreateEventLoop();
896 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
898 if (server
.port
!= 0) {
899 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
900 if (server
.ipfd
== ANET_ERR
) {
901 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
905 if (server
.unixsocket
!= NULL
) {
906 unlink(server
.unixsocket
); /* don't care if this fails */
907 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
908 if (server
.sofd
== ANET_ERR
) {
909 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
913 if (server
.ipfd
< 0 && server
.sofd
< 0) {
914 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
917 for (j
= 0; j
< server
.dbnum
; j
++) {
918 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
919 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
920 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
921 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
924 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
925 server
.pubsub_patterns
= listCreate();
926 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
927 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
928 server
.cronloops
= 0;
929 server
.bgsavechildpid
= -1;
930 server
.bgrewritechildpid
= -1;
931 server
.bgrewritebuf
= sdsempty();
932 server
.aofbuf
= sdsempty();
933 server
.lastsave
= time(NULL
);
935 server
.stat_numcommands
= 0;
936 server
.stat_numconnections
= 0;
937 server
.stat_expiredkeys
= 0;
938 server
.stat_evictedkeys
= 0;
939 server
.stat_starttime
= time(NULL
);
940 server
.stat_keyspace_misses
= 0;
941 server
.stat_keyspace_hits
= 0;
942 server
.stat_peak_memory
= 0;
943 server
.stat_fork_time
= 0;
944 server
.unixtime
= time(NULL
);
945 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
946 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
947 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
948 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
949 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
951 if (server
.appendonly
) {
952 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
953 if (server
.appendfd
== -1) {
954 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
960 if (server
.cluster_enabled
) clusterInit();
962 srand(time(NULL
)^getpid());
965 /* Populates the Redis Command Table starting from the hard coded list
966 * we have on top of redis.c file. */
967 void populateCommandTable(void) {
969 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
971 for (j
= 0; j
< numcommands
; j
++) {
972 struct redisCommand
*c
= redisCommandTable
+j
;
975 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
976 assert(retval
== DICT_OK
);
980 void resetCommandTableStats(void) {
981 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
984 for (j
= 0; j
< numcommands
; j
++) {
985 struct redisCommand
*c
= redisCommandTable
+j
;
992 /* ====================== Commands lookup and execution ===================== */
994 struct redisCommand
*lookupCommand(sds name
) {
995 return dictFetchValue(server
.commands
, name
);
998 struct redisCommand
*lookupCommandByCString(char *s
) {
999 struct redisCommand
*cmd
;
1000 sds name
= sdsnew(s
);
1002 cmd
= dictFetchValue(server
.commands
, name
);
1007 /* Call() is the core of Redis execution of a command */
1008 void call(redisClient
*c
, struct redisCommand
*cmd
) {
1009 long long dirty
, start
= ustime(), duration
;
1011 dirty
= server
.dirty
;
1013 dirty
= server
.dirty
-dirty
;
1014 duration
= ustime()-start
;
1015 cmd
->microseconds
+= duration
;
1016 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1019 if (server
.appendonly
&& dirty
)
1020 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1021 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1022 listLength(server
.slaves
))
1023 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1024 if (listLength(server
.monitors
))
1025 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1026 server
.stat_numcommands
++;
1029 /* If this function gets called we already read a whole
1030 * command, argments are in the client argv/argc fields.
1031 * processCommand() execute the command or prepare the
1032 * server for a bulk read from the client.
1034 * If 1 is returned the client is still alive and valid and
1035 * and other operations can be performed by the caller. Otherwise
1036 * if 0 is returned the client was destroied (i.e. after QUIT). */
1037 int processCommand(redisClient
*c
) {
1038 struct redisCommand
*cmd
;
1040 /* The QUIT command is handled separately. Normal command procs will
1041 * go through checking for replication and QUIT will cause trouble
1042 * when FORCE_REPLICATION is enabled and would be implemented in
1043 * a regular command proc. */
1044 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1045 addReply(c
,shared
.ok
);
1046 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1050 /* Now lookup the command and check ASAP about trivial error conditions
1051 * such wrong arity, bad command name and so forth. */
1052 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1054 addReplyErrorFormat(c
,"unknown command '%s'",
1055 (char*)c
->argv
[0]->ptr
);
1057 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1058 (c
->argc
< -cmd
->arity
)) {
1059 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1064 /* Check if the user is authenticated */
1065 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1066 addReplyError(c
,"operation not permitted");
1070 /* If cluster is enabled, redirect here */
1071 if (server
.cluster_enabled
&&
1072 !(cmd
->getkeys_proc
== NULL
&& cmd
->firstkey
== 0)) {
1075 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1076 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1080 clusterNode
*n
= getNodeByQuery(c
,cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1082 addReplyError(c
,"Multi keys request invalid in cluster");
1084 } else if (n
!= server
.cluster
.myself
) {
1085 addReplySds(c
,sdscatprintf(sdsempty(),
1086 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1087 hashslot
,n
->ip
,n
->port
));
1093 /* Handle the maxmemory directive.
1095 * First we try to free some memory if possible (if there are volatile
1096 * keys in the dataset). If there are not the only thing we can do
1097 * is returning an error. */
1098 if (server
.maxmemory
) freeMemoryIfNeeded();
1099 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1100 zmalloc_used_memory() > server
.maxmemory
)
1102 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1106 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1107 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1109 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
1110 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
1111 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1115 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1116 * we are a slave with a broken link with master. */
1117 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1118 server
.repl_serve_stale_data
== 0 &&
1119 cmd
->proc
!= infoCommand
&& cmd
->proc
!= slaveofCommand
)
1122 "link with MASTER is down and slave-serve-stale-data is set to no");
1126 /* Loading DB? Return an error if the command is not INFO */
1127 if (server
.loading
&& cmd
->proc
!= infoCommand
) {
1128 addReply(c
, shared
.loadingerr
);
1132 /* Exec the command */
1133 if (c
->flags
& REDIS_MULTI
&&
1134 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
1135 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
1137 queueMultiCommand(c
,cmd
);
1138 addReply(c
,shared
.queued
);
1145 /*================================== Shutdown =============================== */
1147 int prepareForShutdown() {
1148 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1149 /* Kill the saving child if there is a background saving in progress.
1150 We want to avoid race conditions, for instance our saving child may
1151 overwrite the synchronous saving did by SHUTDOWN. */
1152 if (server
.bgsavechildpid
!= -1) {
1153 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
1154 kill(server
.bgsavechildpid
,SIGKILL
);
1155 rdbRemoveTempFile(server
.bgsavechildpid
);
1157 if (server
.appendonly
) {
1158 /* Append only file: fsync() the AOF and exit */
1159 aof_fsync(server
.appendfd
);
1160 } else if (server
.saveparamslen
> 0) {
1161 /* Snapshotting. Perform a SYNC SAVE and exit */
1162 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1163 /* Ooops.. error saving! The best we can do is to continue
1164 * operating. Note that if there was a background saving process,
1165 * in the next cron() Redis will be notified that the background
1166 * saving aborted, handling special stuff like slaves pending for
1167 * synchronization... */
1168 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1172 redisLog(REDIS_WARNING
,"Not saving DB.");
1174 if (server
.daemonize
) unlink(server
.pidfile
);
1175 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1179 /*================================== Commands =============================== */
1181 void authCommand(redisClient
*c
) {
1182 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1183 c
->authenticated
= 1;
1184 addReply(c
,shared
.ok
);
1186 c
->authenticated
= 0;
1187 addReplyError(c
,"invalid password");
1191 void pingCommand(redisClient
*c
) {
1192 addReply(c
,shared
.pong
);
1195 void echoCommand(redisClient
*c
) {
1196 addReplyBulk(c
,c
->argv
[1]);
1199 /* Convert an amount of bytes into a human readable string in the form
1200 * of 100B, 2G, 100M, 4K, and so forth. */
1201 void bytesToHuman(char *s
, unsigned long long n
) {
1206 sprintf(s
,"%lluB",n
);
1208 } else if (n
< (1024*1024)) {
1209 d
= (double)n
/(1024);
1210 sprintf(s
,"%.2fK",d
);
1211 } else if (n
< (1024LL*1024*1024)) {
1212 d
= (double)n
/(1024*1024);
1213 sprintf(s
,"%.2fM",d
);
1214 } else if (n
< (1024LL*1024*1024*1024)) {
1215 d
= (double)n
/(1024LL*1024*1024);
1216 sprintf(s
,"%.2fG",d
);
1220 /* Create the string returned by the INFO command. This is decoupled
1221 * by the INFO command itself as we need to report the same information
1222 * on memory corruption problems. */
1223 sds
genRedisInfoString(char *section
) {
1224 sds info
= sdsempty();
1225 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1227 struct rusage self_ru
, c_ru
;
1228 unsigned long lol
, bib
;
1229 int allsections
= 0, defsections
= 0;
1233 allsections
= strcasecmp(section
,"all") == 0;
1234 defsections
= strcasecmp(section
,"default") == 0;
1237 getrusage(RUSAGE_SELF
, &self_ru
);
1238 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1239 getClientsMaxBuffers(&lol
,&bib
);
1242 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1243 if (sections
++) info
= sdscat(info
,"\r\n");
1244 info
= sdscatprintf(info
,
1246 "redis_version:%s\r\n"
1247 "redis_git_sha1:%s\r\n"
1248 "redis_git_dirty:%d\r\n"
1250 "multiplexing_api:%s\r\n"
1251 "process_id:%ld\r\n"
1253 "uptime_in_seconds:%ld\r\n"
1254 "uptime_in_days:%ld\r\n"
1255 "lru_clock:%ld\r\n",
1258 strtol(redisGitDirty(),NULL
,10) > 0,
1259 (sizeof(long) == 8) ? "64" : "32",
1265 (unsigned long) server
.lruclock
);
1269 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1270 if (sections
++) info
= sdscat(info
,"\r\n");
1271 info
= sdscatprintf(info
,
1273 "connected_clients:%d\r\n"
1274 "client_longest_output_list:%lu\r\n"
1275 "client_biggest_input_buf:%lu\r\n"
1276 "blocked_clients:%d\r\n",
1277 listLength(server
.clients
)-listLength(server
.slaves
),
1279 server
.bpop_blocked_clients
);
1283 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1287 bytesToHuman(hmem
,zmalloc_used_memory());
1288 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1289 if (sections
++) info
= sdscat(info
,"\r\n");
1290 info
= sdscatprintf(info
,
1292 "used_memory:%zu\r\n"
1293 "used_memory_human:%s\r\n"
1294 "used_memory_rss:%zu\r\n"
1295 "used_memory_peak:%zu\r\n"
1296 "used_memory_peak_human:%s\r\n"
1297 "mem_fragmentation_ratio:%.2f\r\n"
1298 "mem_allocator:%s\r\n",
1299 zmalloc_used_memory(),
1302 server
.stat_peak_memory
,
1304 zmalloc_get_fragmentation_ratio(),
1310 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1311 if (sections
++) info
= sdscat(info
,"\r\n");
1312 info
= sdscatprintf(info
,
1315 "aof_enabled:%d\r\n"
1316 "changes_since_last_save:%lld\r\n"
1317 "bgsave_in_progress:%d\r\n"
1318 "last_save_time:%ld\r\n"
1319 "bgrewriteaof_in_progress:%d\r\n",
1323 server
.bgsavechildpid
!= -1,
1325 server
.bgrewritechildpid
!= -1);
1327 if (server
.appendonly
) {
1328 info
= sdscatprintf(info
,
1329 "aof_current_size:%lld\r\n"
1330 "aof_base_size:%lld\r\n"
1331 "aof_pending_rewrite:%d\r\n",
1332 (long long) server
.appendonly_current_size
,
1333 (long long) server
.auto_aofrewrite_base_size
,
1334 server
.aofrewrite_scheduled
);
1337 if (server
.loading
) {
1339 time_t eta
, elapsed
;
1340 off_t remaining_bytes
= server
.loading_total_bytes
-
1341 server
.loading_loaded_bytes
;
1343 perc
= ((double)server
.loading_loaded_bytes
/
1344 server
.loading_total_bytes
) * 100;
1346 elapsed
= time(NULL
)-server
.loading_start_time
;
1348 eta
= 1; /* A fake 1 second figure if we don't have
1351 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1354 info
= sdscatprintf(info
,
1355 "loading_start_time:%ld\r\n"
1356 "loading_total_bytes:%llu\r\n"
1357 "loading_loaded_bytes:%llu\r\n"
1358 "loading_loaded_perc:%.2f\r\n"
1359 "loading_eta_seconds:%ld\r\n"
1360 ,(unsigned long) server
.loading_start_time
,
1361 (unsigned long long) server
.loading_total_bytes
,
1362 (unsigned long long) server
.loading_loaded_bytes
,
1370 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1371 if (sections
++) info
= sdscat(info
,"\r\n");
1372 info
= sdscatprintf(info
,
1374 "total_connections_received:%lld\r\n"
1375 "total_commands_processed:%lld\r\n"
1376 "expired_keys:%lld\r\n"
1377 "evicted_keys:%lld\r\n"
1378 "keyspace_hits:%lld\r\n"
1379 "keyspace_misses:%lld\r\n"
1380 "pubsub_channels:%ld\r\n"
1381 "pubsub_patterns:%u\r\n"
1382 "latest_fork_usec:%lld\r\n",
1383 server
.stat_numconnections
,
1384 server
.stat_numcommands
,
1385 server
.stat_expiredkeys
,
1386 server
.stat_evictedkeys
,
1387 server
.stat_keyspace_hits
,
1388 server
.stat_keyspace_misses
,
1389 dictSize(server
.pubsub_channels
),
1390 listLength(server
.pubsub_patterns
),
1391 server
.stat_fork_time
);
1395 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1396 if (sections
++) info
= sdscat(info
,"\r\n");
1397 info
= sdscatprintf(info
,
1400 server
.masterhost
== NULL
? "master" : "slave");
1401 if (server
.masterhost
) {
1402 info
= sdscatprintf(info
,
1403 "master_host:%s\r\n"
1404 "master_port:%d\r\n"
1405 "master_link_status:%s\r\n"
1406 "master_last_io_seconds_ago:%d\r\n"
1407 "master_sync_in_progress:%d\r\n"
1410 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1413 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1414 server
.replstate
== REDIS_REPL_TRANSFER
1417 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1418 info
= sdscatprintf(info
,
1419 "master_sync_left_bytes:%ld\r\n"
1420 "master_sync_last_io_seconds_ago:%d\r\n"
1421 ,(long)server
.repl_transfer_left
,
1422 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1426 if (server
.replstate
!= REDIS_REPL_CONNECTED
) {
1427 info
= sdscatprintf(info
,
1428 "master_link_down_since_seconds:%ld\r\n",
1429 (long)time(NULL
)-server
.repl_down_since
);
1432 info
= sdscatprintf(info
,
1433 "connected_slaves:%d\r\n",
1434 listLength(server
.slaves
));
1438 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1439 if (sections
++) info
= sdscat(info
,"\r\n");
1440 info
= sdscatprintf(info
,
1442 "used_cpu_sys:%.2f\r\n"
1443 "used_cpu_user:%.2f\r\n"
1444 "used_cpu_sys_children:%.2f\r\n"
1445 "used_cpu_user_children:%.2f\r\n",
1446 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1447 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1448 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1449 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000);
1453 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1454 if (sections
++) info
= sdscat(info
,"\r\n");
1455 info
= sdscatprintf(info
, "# Commandstats\r\n");
1456 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1457 for (j
= 0; j
< numcommands
; j
++) {
1458 struct redisCommand
*c
= redisCommandTable
+j
;
1460 if (!c
->calls
) continue;
1461 info
= sdscatprintf(info
,
1462 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1463 c
->name
, c
->calls
, c
->microseconds
,
1464 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1469 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1470 if (sections
++) info
= sdscat(info
,"\r\n");
1471 info
= sdscatprintf(info
,
1473 "cluster_enabled:%d\r\n",
1474 server
.cluster_enabled
);
1478 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1479 if (sections
++) info
= sdscat(info
,"\r\n");
1480 info
= sdscatprintf(info
, "# Keyspace\r\n");
1481 for (j
= 0; j
< server
.dbnum
; j
++) {
1482 long long keys
, vkeys
;
1484 keys
= dictSize(server
.db
[j
].dict
);
1485 vkeys
= dictSize(server
.db
[j
].expires
);
1486 if (keys
|| vkeys
) {
1487 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1495 void infoCommand(redisClient
*c
) {
1496 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1499 addReply(c
,shared
.syntaxerr
);
1502 sds info
= genRedisInfoString(section
);
1503 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1504 (unsigned long)sdslen(info
)));
1505 addReplySds(c
,info
);
1506 addReply(c
,shared
.crlf
);
1509 void monitorCommand(redisClient
*c
) {
1510 /* ignore MONITOR if aleady slave or in monitor mode */
1511 if (c
->flags
& REDIS_SLAVE
) return;
1513 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1515 listAddNodeTail(server
.monitors
,c
);
1516 addReply(c
,shared
.ok
);
1519 /* ============================ Maxmemory directive ======================== */
1521 /* This function gets called when 'maxmemory' is set on the config file to limit
1522 * the max memory used by the server, and we are out of memory.
1523 * This function will try to, in order:
1525 * - Free objects from the free list
1526 * - Try to remove keys with an EXPIRE set
1528 * It is not possible to free enough memory to reach used-memory < maxmemory
1529 * the server will start refusing commands that will enlarge even more the
1532 void freeMemoryIfNeeded(void) {
1533 /* Remove keys accordingly to the active policy as long as we are
1534 * over the memory limit. */
1535 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1537 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1538 int j
, k
, freed
= 0;
1540 for (j
= 0; j
< server
.dbnum
; j
++) {
1541 long bestval
= 0; /* just to prevent warning */
1543 struct dictEntry
*de
;
1544 redisDb
*db
= server
.db
+j
;
1547 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1548 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1550 dict
= server
.db
[j
].dict
;
1552 dict
= server
.db
[j
].expires
;
1554 if (dictSize(dict
) == 0) continue;
1556 /* volatile-random and allkeys-random policy */
1557 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1558 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1560 de
= dictGetRandomKey(dict
);
1561 bestkey
= dictGetEntryKey(de
);
1564 /* volatile-lru and allkeys-lru policy */
1565 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1566 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1568 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1573 de
= dictGetRandomKey(dict
);
1574 thiskey
= dictGetEntryKey(de
);
1575 /* When policy is volatile-lru we need an additonal lookup
1576 * to locate the real key, as dict is set to db->expires. */
1577 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1578 de
= dictFind(db
->dict
, thiskey
);
1579 o
= dictGetEntryVal(de
);
1580 thisval
= estimateObjectIdleTime(o
);
1582 /* Higher idle time is better candidate for deletion */
1583 if (bestkey
== NULL
|| thisval
> bestval
) {
1591 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1592 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1596 de
= dictGetRandomKey(dict
);
1597 thiskey
= dictGetEntryKey(de
);
1598 thisval
= (long) dictGetEntryVal(de
);
1600 /* Expire sooner (minor expire unix timestamp) is better
1601 * candidate for deletion */
1602 if (bestkey
== NULL
|| thisval
< bestval
) {
1609 /* Finally remove the selected key. */
1611 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1612 propagateExpire(db
,keyobj
);
1613 dbDelete(db
,keyobj
);
1614 server
.stat_evictedkeys
++;
1615 decrRefCount(keyobj
);
1619 if (!freed
) return; /* nothing to free... */
1623 /* =================================== Main! ================================ */
1626 int linuxOvercommitMemoryValue(void) {
1627 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1631 if (fgets(buf
,64,fp
) == NULL
) {
1640 void linuxOvercommitMemoryWarning(void) {
1641 if (linuxOvercommitMemoryValue() == 0) {
1642 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.");
1645 #endif /* __linux__ */
1647 void createPidFile(void) {
1648 /* Try to write the pid file in a best-effort way. */
1649 FILE *fp
= fopen(server
.pidfile
,"w");
1651 fprintf(fp
,"%d\n",(int)getpid());
1656 void daemonize(void) {
1659 if (fork() != 0) exit(0); /* parent exits */
1660 setsid(); /* create a new session */
1662 /* Every output goes to /dev/null. If Redis is daemonized but
1663 * the 'logfile' is set to 'stdout' in the configuration file
1664 * it will not log at all. */
1665 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1666 dup2(fd
, STDIN_FILENO
);
1667 dup2(fd
, STDOUT_FILENO
);
1668 dup2(fd
, STDERR_FILENO
);
1669 if (fd
> STDERR_FILENO
) close(fd
);
1674 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1675 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1680 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1681 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1685 void redisAsciiArt(void) {
1686 #include "asciilogo.h"
1687 char *buf
= zmalloc(1024*16);
1689 snprintf(buf
,1024*16,ascii_logo
,
1692 strtol(redisGitDirty(),NULL
,10) > 0,
1693 (sizeof(long) == 8) ? "64" : "32",
1694 server
.cluster_enabled
? "cluster" : "stand alone",
1698 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1702 int main(int argc
, char **argv
) {
1707 if (strcmp(argv
[1], "-v") == 0 ||
1708 strcmp(argv
[1], "--version") == 0) version();
1709 if (strcmp(argv
[1], "--help") == 0) usage();
1710 resetServerSaveParams();
1711 loadServerConfig(argv
[1]);
1712 } else if ((argc
> 2)) {
1715 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'");
1717 if (server
.daemonize
) daemonize();
1719 if (server
.daemonize
) createPidFile();
1721 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1723 linuxOvercommitMemoryWarning();
1726 if (server
.appendonly
) {
1727 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1728 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1730 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1731 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",(float)(ustime()-start
)/1000000);
1733 if (server
.ipfd
> 0)
1734 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1735 if (server
.sofd
> 0)
1736 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1737 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1739 aeDeleteEventLoop(server
.el
);
1743 #ifdef HAVE_BACKTRACE
1744 static void *getMcontextEip(ucontext_t
*uc
) {
1745 #if defined(__FreeBSD__)
1746 return (void*) uc
->uc_mcontext
.mc_eip
;
1747 #elif defined(__dietlibc__)
1748 return (void*) uc
->uc_mcontext
.eip
;
1749 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1751 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1753 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1755 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1756 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1757 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1759 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1761 #elif defined(__i386__)
1762 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1763 #elif defined(__X86_64__) || defined(__x86_64__)
1764 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1765 #elif defined(__ia64__) /* Linux IA64 */
1766 return (void*) uc
->uc_mcontext
.sc_ip
;
1772 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1774 char **messages
= NULL
;
1775 int i
, trace_size
= 0;
1776 ucontext_t
*uc
= (ucontext_t
*) secret
;
1778 struct sigaction act
;
1779 REDIS_NOTUSED(info
);
1781 redisLog(REDIS_WARNING
,
1782 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1783 infostring
= genRedisInfoString("all");
1784 redisLogRaw(REDIS_WARNING
, infostring
);
1785 /* It's not safe to sdsfree() the returned string under memory
1786 * corruption conditions. Let it leak as we are going to abort */
1788 trace_size
= backtrace(trace
, 100);
1789 /* overwrite sigaction with caller's address */
1790 if (getMcontextEip(uc
) != NULL
) {
1791 trace
[1] = getMcontextEip(uc
);
1793 messages
= backtrace_symbols(trace
, trace_size
);
1795 for (i
=1; i
<trace_size
; ++i
)
1796 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1798 /* free(messages); Don't call free() with possibly corrupted memory. */
1799 if (server
.daemonize
) unlink(server
.pidfile
);
1801 /* Make sure we exit with the right signal at the end. So for instance
1802 * the core will be dumped if enabled. */
1803 sigemptyset (&act
.sa_mask
);
1804 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1805 * is used. Otherwise, sa_handler is used */
1806 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1807 act
.sa_handler
= SIG_DFL
;
1808 sigaction (sig
, &act
, NULL
);
1811 #endif /* HAVE_BACKTRACE */
1813 static void sigtermHandler(int sig
) {
1816 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1817 server
.shutdown_asap
= 1;
1820 void setupSignalHandlers(void) {
1821 struct sigaction act
;
1823 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1824 * Otherwise, sa_handler is used. */
1825 sigemptyset(&act
.sa_mask
);
1826 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1827 act
.sa_handler
= sigtermHandler
;
1828 sigaction(SIGTERM
, &act
, NULL
);
1830 #ifdef HAVE_BACKTRACE
1831 sigemptyset(&act
.sa_mask
);
1832 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1833 act
.sa_sigaction
= sigsegvHandler
;
1834 sigaction(SIGSEGV
, &act
, NULL
);
1835 sigaction(SIGBUS
, &act
, NULL
);
1836 sigaction(SIGFPE
, &act
, NULL
);
1837 sigaction(SIGILL
, &act
, NULL
);