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 {"eval",evalCommand
,-3,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
198 {"evalsha",evalShaCommand
,-3,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
199 {"slowlog",slowlogCommand
,-2,0,NULL
,0,0,0,0,0}
202 /*============================ Utility functions ============================ */
204 /* Low level logging. To use only for very big messages, otherwise
205 * redisLog() is to prefer. */
206 void redisLogRaw(int level
, const char *msg
) {
207 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
208 const char *c
= ".-*#";
209 time_t now
= time(NULL
);
212 int rawmode
= (level
& REDIS_LOG_RAW
);
214 level
&= 0xff; /* clear flags */
215 if (level
< server
.verbosity
) return;
217 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
221 fprintf(fp
,"%s",msg
);
223 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
224 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
228 if (server
.logfile
) fclose(fp
);
230 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
233 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
234 * is used across the code. The raw version is only used in order to dump
235 * the INFO output on crash. */
236 void redisLog(int level
, const char *fmt
, ...) {
238 char msg
[REDIS_MAX_LOGMSG_LEN
];
240 if ((level
&0xff) < server
.verbosity
) return;
243 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
246 redisLogRaw(level
,msg
);
249 /* Redis generally does not try to recover from out of memory conditions
250 * when allocating objects or strings, it is not clear if it will be possible
251 * to report this condition to the client since the networking layer itself
252 * is based on heap allocation for send buffers, so we simply abort.
253 * At least the code will be simpler to read... */
254 void oom(const char *msg
) {
255 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
260 /* Return the UNIX time in microseconds */
261 long long ustime(void) {
265 gettimeofday(&tv
, NULL
);
266 ust
= ((long long)tv
.tv_sec
)*1000000;
271 /*====================== Hash table type implementation ==================== */
273 /* This is an hash table type that uses the SDS dynamic strings libary as
274 * keys and radis objects as values (objects can hold SDS strings,
277 void dictVanillaFree(void *privdata
, void *val
)
279 DICT_NOTUSED(privdata
);
283 void dictListDestructor(void *privdata
, void *val
)
285 DICT_NOTUSED(privdata
);
286 listRelease((list
*)val
);
289 int dictSdsKeyCompare(void *privdata
, const void *key1
,
293 DICT_NOTUSED(privdata
);
295 l1
= sdslen((sds
)key1
);
296 l2
= sdslen((sds
)key2
);
297 if (l1
!= l2
) return 0;
298 return memcmp(key1
, key2
, l1
) == 0;
301 /* A case insensitive version used for the command lookup table. */
302 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
305 DICT_NOTUSED(privdata
);
307 return strcasecmp(key1
, key2
) == 0;
310 void dictRedisObjectDestructor(void *privdata
, void *val
)
312 DICT_NOTUSED(privdata
);
314 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
318 void dictSdsDestructor(void *privdata
, void *val
)
320 DICT_NOTUSED(privdata
);
325 int dictObjKeyCompare(void *privdata
, const void *key1
,
328 const robj
*o1
= key1
, *o2
= key2
;
329 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
332 unsigned int dictObjHash(const void *key
) {
334 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
337 unsigned int dictSdsHash(const void *key
) {
338 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
341 unsigned int dictSdsCaseHash(const void *key
) {
342 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
345 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
348 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
351 if (o1
->encoding
== REDIS_ENCODING_INT
&&
352 o2
->encoding
== REDIS_ENCODING_INT
)
353 return o1
->ptr
== o2
->ptr
;
355 o1
= getDecodedObject(o1
);
356 o2
= getDecodedObject(o2
);
357 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
363 unsigned int dictEncObjHash(const void *key
) {
364 robj
*o
= (robj
*) key
;
366 if (o
->encoding
== REDIS_ENCODING_RAW
) {
367 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
369 if (o
->encoding
== REDIS_ENCODING_INT
) {
373 len
= ll2string(buf
,32,(long)o
->ptr
);
374 return dictGenHashFunction((unsigned char*)buf
, len
);
378 o
= getDecodedObject(o
);
379 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
386 /* Sets type hash table */
387 dictType setDictType
= {
388 dictEncObjHash
, /* hash function */
391 dictEncObjKeyCompare
, /* key compare */
392 dictRedisObjectDestructor
, /* key destructor */
393 NULL
/* val destructor */
396 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
397 dictType zsetDictType
= {
398 dictEncObjHash
, /* hash function */
401 dictEncObjKeyCompare
, /* key compare */
402 dictRedisObjectDestructor
, /* key destructor */
403 NULL
/* val destructor */
406 /* Db->dict, keys are sds strings, vals are Redis objects. */
407 dictType dbDictType
= {
408 dictSdsHash
, /* hash function */
411 dictSdsKeyCompare
, /* key compare */
412 dictSdsDestructor
, /* key destructor */
413 dictRedisObjectDestructor
/* val destructor */
417 dictType keyptrDictType
= {
418 dictSdsHash
, /* hash function */
421 dictSdsKeyCompare
, /* key compare */
422 NULL
, /* key destructor */
423 NULL
/* val destructor */
426 /* Command table. sds string -> command struct pointer. */
427 dictType commandTableDictType
= {
428 dictSdsCaseHash
, /* hash function */
431 dictSdsKeyCaseCompare
, /* key compare */
432 dictSdsDestructor
, /* key destructor */
433 NULL
/* val destructor */
436 /* Hash type hash table (note that small hashes are represented with zimpaps) */
437 dictType hashDictType
= {
438 dictEncObjHash
, /* hash function */
441 dictEncObjKeyCompare
, /* key compare */
442 dictRedisObjectDestructor
, /* key destructor */
443 dictRedisObjectDestructor
/* val destructor */
446 /* Keylist hash table type has unencoded redis objects as keys and
447 * lists as values. It's used for blocking operations (BLPOP) and to
448 * map swapped keys to a list of clients waiting for this keys to be loaded. */
449 dictType keylistDictType
= {
450 dictObjHash
, /* hash function */
453 dictObjKeyCompare
, /* key compare */
454 dictRedisObjectDestructor
, /* key destructor */
455 dictListDestructor
/* val destructor */
458 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
459 * clusterNode structures. */
460 dictType clusterNodesDictType
= {
461 dictSdsHash
, /* hash function */
464 dictSdsKeyCompare
, /* key compare */
465 dictSdsDestructor
, /* key destructor */
466 NULL
/* val destructor */
469 int htNeedsResize(dict
*dict
) {
470 long long size
, used
;
472 size
= dictSlots(dict
);
473 used
= dictSize(dict
);
474 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
475 (used
*100/size
< REDIS_HT_MINFILL
));
478 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
479 * we resize the hash table to save memory */
480 void tryResizeHashTables(void) {
483 for (j
= 0; j
< server
.dbnum
; j
++) {
484 if (htNeedsResize(server
.db
[j
].dict
))
485 dictResize(server
.db
[j
].dict
);
486 if (htNeedsResize(server
.db
[j
].expires
))
487 dictResize(server
.db
[j
].expires
);
491 /* Our hash table implementation performs rehashing incrementally while
492 * we write/read from the hash table. Still if the server is idle, the hash
493 * table will use two tables for a long time. So we try to use 1 millisecond
494 * of CPU time at every serverCron() loop in order to rehash some key. */
495 void incrementallyRehash(void) {
498 for (j
= 0; j
< server
.dbnum
; j
++) {
499 if (dictIsRehashing(server
.db
[j
].dict
)) {
500 dictRehashMilliseconds(server
.db
[j
].dict
,1);
501 break; /* already used our millisecond for this loop... */
506 /* This function is called once a background process of some kind terminates,
507 * as we want to avoid resizing the hash tables when there is a child in order
508 * to play well with copy-on-write (otherwise when a resize happens lots of
509 * memory pages are copied). The goal of this function is to update the ability
510 * for dict.c to resize the hash tables accordingly to the fact we have o not
512 void updateDictResizePolicy(void) {
513 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
519 /* ======================= Cron: called every 100 ms ======================== */
521 /* Try to expire a few timed out keys. The algorithm used is adaptive and
522 * will use few CPU cycles if there are few expiring keys, otherwise
523 * it will get more aggressive to avoid that too much memory is used by
524 * keys that can be removed from the keyspace. */
525 void activeExpireCycle(void) {
528 for (j
= 0; j
< server
.dbnum
; j
++) {
530 redisDb
*db
= server
.db
+j
;
532 /* Continue to expire if at the end of the cycle more than 25%
533 * of the keys were expired. */
535 long num
= dictSize(db
->expires
);
536 time_t now
= time(NULL
);
539 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
540 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
545 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
546 t
= (time_t) dictGetEntryVal(de
);
548 sds key
= dictGetEntryKey(de
);
549 robj
*keyobj
= createStringObject(key
,sdslen(key
));
551 propagateExpire(db
,keyobj
);
553 decrRefCount(keyobj
);
555 server
.stat_expiredkeys
++;
558 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
562 void updateLRUClock(void) {
563 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
567 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
568 int j
, loops
= server
.cronloops
;
569 REDIS_NOTUSED(eventLoop
);
571 REDIS_NOTUSED(clientData
);
573 /* We take a cached value of the unix time in the global state because
574 * with virtual memory and aging there is to store the current time
575 * in objects at every object access, and accuracy is not needed.
576 * To access a global var is faster than calling time(NULL) */
577 server
.unixtime
= time(NULL
);
579 /* We have just 22 bits per object for LRU information.
580 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
581 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
583 * Note that even if this will wrap after 1.5 years it's not a problem,
584 * everything will still work but just some object will appear younger
585 * to Redis. But for this to happen a given object should never be touched
588 * Note that you can change the resolution altering the
589 * REDIS_LRU_CLOCK_RESOLUTION define.
593 /* Record the max memory used since the server was started. */
594 if (zmalloc_used_memory() > server
.stat_peak_memory
)
595 server
.stat_peak_memory
= zmalloc_used_memory();
597 /* We received a SIGTERM, shutting down here in a safe way, as it is
598 * not ok doing so inside the signal handler. */
599 if (server
.shutdown_asap
) {
600 if (prepareForShutdown() == REDIS_OK
) exit(0);
601 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
604 /* Show some info about non-empty databases */
605 for (j
= 0; j
< server
.dbnum
; j
++) {
606 long long size
, used
, vkeys
;
608 size
= dictSlots(server
.db
[j
].dict
);
609 used
= dictSize(server
.db
[j
].dict
);
610 vkeys
= dictSize(server
.db
[j
].expires
);
611 if (!(loops
% 50) && (used
|| vkeys
)) {
612 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
613 /* dictPrintStats(server.dict); */
617 /* We don't want to resize the hash tables while a bacground saving
618 * is in progress: the saving child is created using fork() that is
619 * implemented with a copy-on-write semantic in most modern systems, so
620 * if we resize the HT while there is the saving child at work actually
621 * a lot of memory movements in the parent will cause a lot of pages
623 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
624 if (!(loops
% 10)) tryResizeHashTables();
625 if (server
.activerehashing
) incrementallyRehash();
628 /* Show information about connected clients */
630 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
631 listLength(server
.clients
)-listLength(server
.slaves
),
632 listLength(server
.slaves
),
633 zmalloc_used_memory());
636 /* Close connections of timedout clients */
637 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
638 closeTimedoutClients();
640 /* Start a scheduled AOF rewrite if this was requested by the user while
641 * a BGSAVE was in progress. */
642 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1 &&
643 server
.aofrewrite_scheduled
)
645 rewriteAppendOnlyFileBackground();
648 /* Check if a background saving or AOF rewrite in progress terminated. */
649 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
653 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
654 int exitcode
= WEXITSTATUS(statloc
);
657 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
659 if (pid
== server
.bgsavechildpid
) {
660 backgroundSaveDoneHandler(exitcode
,bysignal
);
662 backgroundRewriteDoneHandler(exitcode
,bysignal
);
664 updateDictResizePolicy();
667 time_t now
= time(NULL
);
669 /* If there is not a background saving/rewrite in progress check if
670 * we have to save/rewrite now */
671 for (j
= 0; j
< server
.saveparamslen
; j
++) {
672 struct saveparam
*sp
= server
.saveparams
+j
;
674 if (server
.dirty
>= sp
->changes
&&
675 now
-server
.lastsave
> sp
->seconds
) {
676 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
677 sp
->changes
, sp
->seconds
);
678 rdbSaveBackground(server
.dbfilename
);
683 /* Trigger an AOF rewrite if needed */
684 if (server
.bgsavechildpid
== -1 &&
685 server
.bgrewritechildpid
== -1 &&
686 server
.auto_aofrewrite_perc
&&
687 server
.appendonly_current_size
> server
.auto_aofrewrite_min_size
)
689 long long base
= server
.auto_aofrewrite_base_size
?
690 server
.auto_aofrewrite_base_size
: 1;
691 long long growth
= (server
.appendonly_current_size
*100/base
) - 100;
692 if (growth
>= server
.auto_aofrewrite_perc
) {
693 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
694 rewriteAppendOnlyFileBackground();
699 /* Expire a few keys per cycle, only if this is a master.
700 * On slaves we wait for DEL operations synthesized by the master
701 * in order to guarantee a strict consistency. */
702 if (server
.masterhost
== NULL
) activeExpireCycle();
704 /* Replication cron function -- used to reconnect to master and
705 * to detect transfer failures. */
706 if (!(loops
% 10)) replicationCron();
708 /* Run other sub-systems specific cron jobs */
709 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
715 /* This function gets called every time Redis is entering the
716 * main loop of the event driven library, that is, before to sleep
717 * for ready file descriptors. */
718 void beforeSleep(struct aeEventLoop
*eventLoop
) {
719 REDIS_NOTUSED(eventLoop
);
723 /* Try to process pending commands for clients that were just unblocked. */
724 while (listLength(server
.unblocked_clients
)) {
725 ln
= listFirst(server
.unblocked_clients
);
726 redisAssert(ln
!= NULL
);
728 listDelNode(server
.unblocked_clients
,ln
);
729 c
->flags
&= ~REDIS_UNBLOCKED
;
731 /* Process remaining data in the input buffer. */
732 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
733 processInputBuffer(c
);
736 /* Write the AOF buffer on disk */
737 flushAppendOnlyFile();
740 /* =========================== Server initialization ======================== */
742 void createSharedObjects(void) {
745 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
746 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
747 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
748 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
749 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
750 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
751 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
752 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
753 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
754 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
755 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
756 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
757 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
758 "-ERR Operation against a key holding the wrong kind of value\r\n"));
759 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
760 "-ERR no such key\r\n"));
761 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
762 "-ERR syntax error\r\n"));
763 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
764 "-ERR source and destination objects are the same\r\n"));
765 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
766 "-ERR index out of range\r\n"));
767 shared
.noscripterr
= createObject(REDIS_STRING
,sdsnew(
768 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
769 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
770 "-LOADING Redis is loading the dataset in memory\r\n"));
771 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
772 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
773 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
774 shared
.select0
= createStringObject("select 0\r\n",10);
775 shared
.select1
= createStringObject("select 1\r\n",10);
776 shared
.select2
= createStringObject("select 2\r\n",10);
777 shared
.select3
= createStringObject("select 3\r\n",10);
778 shared
.select4
= createStringObject("select 4\r\n",10);
779 shared
.select5
= createStringObject("select 5\r\n",10);
780 shared
.select6
= createStringObject("select 6\r\n",10);
781 shared
.select7
= createStringObject("select 7\r\n",10);
782 shared
.select8
= createStringObject("select 8\r\n",10);
783 shared
.select9
= createStringObject("select 9\r\n",10);
784 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
785 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
786 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
787 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
788 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
789 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
790 shared
.mbulk3
= createStringObject("*3\r\n",4);
791 shared
.mbulk4
= createStringObject("*4\r\n",4);
792 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
793 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
794 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
798 void initServerConfig() {
799 server
.port
= REDIS_SERVERPORT
;
800 server
.bindaddr
= NULL
;
801 server
.unixsocket
= NULL
;
804 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
805 server
.verbosity
= REDIS_VERBOSE
;
806 server
.maxidletime
= REDIS_MAXIDLETIME
;
807 server
.saveparams
= NULL
;
809 server
.logfile
= NULL
; /* NULL = log on standard output */
810 server
.syslog_enabled
= 0;
811 server
.syslog_ident
= zstrdup("redis");
812 server
.syslog_facility
= LOG_LOCAL0
;
813 server
.daemonize
= 0;
814 server
.appendonly
= 0;
815 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
816 server
.no_appendfsync_on_rewrite
= 0;
817 server
.auto_aofrewrite_perc
= REDIS_AUTO_AOFREWRITE_PERC
;
818 server
.auto_aofrewrite_min_size
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
;
819 server
.auto_aofrewrite_base_size
= 0;
820 server
.aofrewrite_scheduled
= 0;
821 server
.lastfsync
= time(NULL
);
822 server
.appendfd
= -1;
823 server
.appendseldb
= -1; /* Make sure the first time will not match */
824 server
.pidfile
= zstrdup("/var/run/redis.pid");
825 server
.dbfilename
= zstrdup("dump.rdb");
826 server
.appendfilename
= zstrdup("appendonly.aof");
827 server
.requirepass
= NULL
;
828 server
.rdbcompression
= 1;
829 server
.activerehashing
= 1;
830 server
.maxclients
= 0;
831 server
.bpop_blocked_clients
= 0;
832 server
.maxmemory
= 0;
833 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
834 server
.maxmemory_samples
= 3;
835 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
836 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
837 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
838 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
839 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
840 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
841 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
842 server
.shutdown_asap
= 0;
843 server
.cluster_enabled
= 0;
844 server
.cluster
.configfile
= zstrdup("nodes.conf");
845 server
.lua_time_limit
= REDIS_LUA_TIME_LIMIT
;
848 resetServerSaveParams();
850 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
851 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
852 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
853 /* Replication related */
855 server
.masterauth
= NULL
;
856 server
.masterhost
= NULL
;
857 server
.masterport
= 6379;
858 server
.master
= NULL
;
859 server
.replstate
= REDIS_REPL_NONE
;
860 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
861 server
.repl_serve_stale_data
= 1;
862 server
.repl_down_since
= -1;
864 /* Double constants initialization */
866 R_PosInf
= 1.0/R_Zero
;
867 R_NegInf
= -1.0/R_Zero
;
868 R_Nan
= R_Zero
/R_Zero
;
870 /* Command table -- we intiialize it here as it is part of the
871 * initial configuration, since command names may be changed via
872 * redis.conf using the rename-command directive. */
873 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
874 populateCommandTable();
875 server
.delCommand
= lookupCommandByCString("del");
876 server
.multiCommand
= lookupCommandByCString("multi");
879 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
880 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
886 signal(SIGHUP
, SIG_IGN
);
887 signal(SIGPIPE
, SIG_IGN
);
888 setupSignalHandlers();
890 if (server
.syslog_enabled
) {
891 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
892 server
.syslog_facility
);
895 server
.clients
= listCreate();
896 server
.slaves
= listCreate();
897 server
.monitors
= listCreate();
898 server
.unblocked_clients
= listCreate();
900 createSharedObjects();
901 server
.el
= aeCreateEventLoop();
902 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
904 if (server
.port
!= 0) {
905 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
906 if (server
.ipfd
== ANET_ERR
) {
907 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
911 if (server
.unixsocket
!= NULL
) {
912 unlink(server
.unixsocket
); /* don't care if this fails */
913 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
914 if (server
.sofd
== ANET_ERR
) {
915 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
919 if (server
.ipfd
< 0 && server
.sofd
< 0) {
920 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
923 for (j
= 0; j
< server
.dbnum
; j
++) {
924 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
925 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
926 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
927 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
930 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
931 server
.pubsub_patterns
= listCreate();
932 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
933 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
934 server
.cronloops
= 0;
935 server
.bgsavechildpid
= -1;
936 server
.bgrewritechildpid
= -1;
937 server
.bgrewritebuf
= sdsempty();
938 server
.aofbuf
= sdsempty();
939 server
.lastsave
= time(NULL
);
941 server
.stat_numcommands
= 0;
942 server
.stat_numconnections
= 0;
943 server
.stat_expiredkeys
= 0;
944 server
.stat_evictedkeys
= 0;
945 server
.stat_starttime
= time(NULL
);
946 server
.stat_keyspace_misses
= 0;
947 server
.stat_keyspace_hits
= 0;
948 server
.stat_peak_memory
= 0;
949 server
.stat_fork_time
= 0;
950 server
.unixtime
= time(NULL
);
951 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
952 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
953 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
954 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
955 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
957 if (server
.appendonly
) {
958 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
959 if (server
.appendfd
== -1) {
960 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
966 if (server
.cluster_enabled
) clusterInit();
969 srand(time(NULL
)^getpid());
972 /* Populates the Redis Command Table starting from the hard coded list
973 * we have on top of redis.c file. */
974 void populateCommandTable(void) {
976 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
978 for (j
= 0; j
< numcommands
; j
++) {
979 struct redisCommand
*c
= redisCommandTable
+j
;
982 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
983 assert(retval
== DICT_OK
);
987 void resetCommandTableStats(void) {
988 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
991 for (j
= 0; j
< numcommands
; j
++) {
992 struct redisCommand
*c
= redisCommandTable
+j
;
999 /* ====================== Commands lookup and execution ===================== */
1001 struct redisCommand
*lookupCommand(sds name
) {
1002 return dictFetchValue(server
.commands
, name
);
1005 struct redisCommand
*lookupCommandByCString(char *s
) {
1006 struct redisCommand
*cmd
;
1007 sds name
= sdsnew(s
);
1009 cmd
= dictFetchValue(server
.commands
, name
);
1014 /* Call() is the core of Redis execution of a command */
1015 void call(redisClient
*c
) {
1016 long long dirty
, start
= ustime(), duration
;
1018 dirty
= server
.dirty
;
1020 dirty
= server
.dirty
-dirty
;
1021 duration
= ustime()-start
;
1022 c
->cmd
->microseconds
+= duration
;
1023 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1026 if (server
.appendonly
&& dirty
)
1027 feedAppendOnlyFile(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1028 if ((dirty
|| c
->cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1029 listLength(server
.slaves
))
1030 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1031 if (listLength(server
.monitors
))
1032 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1033 server
.stat_numcommands
++;
1036 /* If this function gets called we already read a whole
1037 * command, argments are in the client argv/argc fields.
1038 * processCommand() execute the command or prepare the
1039 * server for a bulk read from the client.
1041 * If 1 is returned the client is still alive and valid and
1042 * and other operations can be performed by the caller. Otherwise
1043 * if 0 is returned the client was destroied (i.e. after QUIT). */
1044 int processCommand(redisClient
*c
) {
1045 /* The QUIT command is handled separately. Normal command procs will
1046 * go through checking for replication and QUIT will cause trouble
1047 * when FORCE_REPLICATION is enabled and would be implemented in
1048 * a regular command proc. */
1049 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1050 addReply(c
,shared
.ok
);
1051 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1055 /* Now lookup the command and check ASAP about trivial error conditions
1056 * such as wrong arity, bad command name and so forth. */
1057 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1059 addReplyErrorFormat(c
,"unknown command '%s'",
1060 (char*)c
->argv
[0]->ptr
);
1062 } else if ((c
->cmd
->arity
> 0 && c
->cmd
->arity
!= c
->argc
) ||
1063 (c
->argc
< -c
->cmd
->arity
)) {
1064 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1069 /* Check if the user is authenticated */
1070 if (server
.requirepass
&& !c
->authenticated
&& c
->cmd
->proc
!= authCommand
)
1072 addReplyError(c
,"operation not permitted");
1076 /* If cluster is enabled, redirect here */
1077 if (server
.cluster_enabled
&&
1078 !(c
->cmd
->getkeys_proc
== NULL
&& c
->cmd
->firstkey
== 0)) {
1081 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1082 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1086 clusterNode
*n
= getNodeByQuery(c
,c
->cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1088 addReplyError(c
,"Multi keys request invalid in cluster");
1090 } else if (n
!= server
.cluster
.myself
) {
1091 addReplySds(c
,sdscatprintf(sdsempty(),
1092 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1093 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
&& (c
->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 c
->cmd
->proc
!= subscribeCommand
&&
1116 c
->cmd
->proc
!= unsubscribeCommand
&&
1117 c
->cmd
->proc
!= psubscribeCommand
&&
1118 c
->cmd
->proc
!= punsubscribeCommand
) {
1119 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1123 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1124 * we are a slave with a broken link with master. */
1125 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1126 server
.repl_serve_stale_data
== 0 &&
1127 c
->cmd
->proc
!= infoCommand
&& c
->cmd
->proc
!= slaveofCommand
)
1130 "link with MASTER is down and slave-serve-stale-data is set to no");
1134 /* Loading DB? Return an error if the command is not INFO */
1135 if (server
.loading
&& c
->cmd
->proc
!= infoCommand
) {
1136 addReply(c
, shared
.loadingerr
);
1140 /* Exec the command */
1141 if (c
->flags
& REDIS_MULTI
&&
1142 c
->cmd
->proc
!= execCommand
&& c
->cmd
->proc
!= discardCommand
&&
1143 c
->cmd
->proc
!= multiCommand
&& c
->cmd
->proc
!= watchCommand
)
1145 queueMultiCommand(c
);
1146 addReply(c
,shared
.queued
);
1153 /*================================== Shutdown =============================== */
1155 int prepareForShutdown() {
1156 redisLog(REDIS_WARNING
,"User requested shutdown...");
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 child saving an .rdb. Killing it!");
1162 kill(server
.bgsavechildpid
,SIGKILL
);
1163 rdbRemoveTempFile(server
.bgsavechildpid
);
1165 if (server
.appendonly
) {
1166 /* Kill the AOF saving child as the AOF we already have may be longer
1167 * but contains the full dataset anyway. */
1168 if (server
.bgrewritechildpid
!= -1) {
1169 redisLog(REDIS_WARNING
,
1170 "There is a child rewriting the AOF. Killing it!");
1171 kill(server
.bgrewritechildpid
,SIGKILL
);
1173 /* Append only file: fsync() the AOF and exit */
1174 redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file.");
1175 aof_fsync(server
.appendfd
);
1177 if (server
.saveparamslen
> 0) {
1178 redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting.");
1179 /* Snapshotting. Perform a SYNC SAVE and exit */
1180 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1181 /* Ooops.. error saving! The best we can do is to continue
1182 * operating. Note that if there was a background saving process,
1183 * in the next cron() Redis will be notified that the background
1184 * saving aborted, handling special stuff like slaves pending for
1185 * synchronization... */
1186 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit.");
1190 if (server
.daemonize
) {
1191 redisLog(REDIS_NOTICE
,"Removing the pid file.");
1192 unlink(server
.pidfile
);
1194 /* Close the listening sockets. Apparently this allows faster restarts. */
1195 if (server
.ipfd
!= -1) close(server
.ipfd
);
1196 if (server
.sofd
!= -1) close(server
.sofd
);
1198 redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye...");
1202 /*================================== Commands =============================== */
1204 void authCommand(redisClient
*c
) {
1205 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1206 c
->authenticated
= 1;
1207 addReply(c
,shared
.ok
);
1209 c
->authenticated
= 0;
1210 addReplyError(c
,"invalid password");
1214 void pingCommand(redisClient
*c
) {
1215 addReply(c
,shared
.pong
);
1218 void echoCommand(redisClient
*c
) {
1219 addReplyBulk(c
,c
->argv
[1]);
1222 /* Convert an amount of bytes into a human readable string in the form
1223 * of 100B, 2G, 100M, 4K, and so forth. */
1224 void bytesToHuman(char *s
, unsigned long long n
) {
1229 sprintf(s
,"%lluB",n
);
1231 } else if (n
< (1024*1024)) {
1232 d
= (double)n
/(1024);
1233 sprintf(s
,"%.2fK",d
);
1234 } else if (n
< (1024LL*1024*1024)) {
1235 d
= (double)n
/(1024*1024);
1236 sprintf(s
,"%.2fM",d
);
1237 } else if (n
< (1024LL*1024*1024*1024)) {
1238 d
= (double)n
/(1024LL*1024*1024);
1239 sprintf(s
,"%.2fG",d
);
1243 /* Create the string returned by the INFO command. This is decoupled
1244 * by the INFO command itself as we need to report the same information
1245 * on memory corruption problems. */
1246 sds
genRedisInfoString(char *section
) {
1247 sds info
= sdsempty();
1248 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1250 struct rusage self_ru
, c_ru
;
1251 unsigned long lol
, bib
;
1252 int allsections
= 0, defsections
= 0;
1256 allsections
= strcasecmp(section
,"all") == 0;
1257 defsections
= strcasecmp(section
,"default") == 0;
1260 getrusage(RUSAGE_SELF
, &self_ru
);
1261 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1262 getClientsMaxBuffers(&lol
,&bib
);
1265 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1266 if (sections
++) info
= sdscat(info
,"\r\n");
1267 info
= sdscatprintf(info
,
1269 "redis_version:%s\r\n"
1270 "redis_git_sha1:%s\r\n"
1271 "redis_git_dirty:%d\r\n"
1273 "multiplexing_api:%s\r\n"
1274 "process_id:%ld\r\n"
1276 "uptime_in_seconds:%ld\r\n"
1277 "uptime_in_days:%ld\r\n"
1278 "lru_clock:%ld\r\n",
1281 strtol(redisGitDirty(),NULL
,10) > 0,
1282 (sizeof(long) == 8) ? "64" : "32",
1288 (unsigned long) server
.lruclock
);
1292 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1293 if (sections
++) info
= sdscat(info
,"\r\n");
1294 info
= sdscatprintf(info
,
1296 "connected_clients:%d\r\n"
1297 "client_longest_output_list:%lu\r\n"
1298 "client_biggest_input_buf:%lu\r\n"
1299 "blocked_clients:%d\r\n",
1300 listLength(server
.clients
)-listLength(server
.slaves
),
1302 server
.bpop_blocked_clients
);
1306 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1310 bytesToHuman(hmem
,zmalloc_used_memory());
1311 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1312 if (sections
++) info
= sdscat(info
,"\r\n");
1313 info
= sdscatprintf(info
,
1315 "used_memory:%zu\r\n"
1316 "used_memory_human:%s\r\n"
1317 "used_memory_rss:%zu\r\n"
1318 "used_memory_peak:%zu\r\n"
1319 "used_memory_peak_human:%s\r\n"
1320 "used_memory_lua:%lld\r\n"
1321 "mem_fragmentation_ratio:%.2f\r\n"
1322 "mem_allocator:%s\r\n",
1323 zmalloc_used_memory(),
1326 server
.stat_peak_memory
,
1328 ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL,
1329 zmalloc_get_fragmentation_ratio(),
1335 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1336 if (sections
++) info
= sdscat(info
,"\r\n");
1337 info
= sdscatprintf(info
,
1340 "aof_enabled:%d\r\n"
1341 "changes_since_last_save:%lld\r\n"
1342 "bgsave_in_progress:%d\r\n"
1343 "last_save_time:%ld\r\n"
1344 "bgrewriteaof_in_progress:%d\r\n",
1348 server
.bgsavechildpid
!= -1,
1350 server
.bgrewritechildpid
!= -1);
1352 if (server
.appendonly
) {
1353 info
= sdscatprintf(info
,
1354 "aof_current_size:%lld\r\n"
1355 "aof_base_size:%lld\r\n"
1356 "aof_pending_rewrite:%d\r\n",
1357 (long long) server
.appendonly_current_size
,
1358 (long long) server
.auto_aofrewrite_base_size
,
1359 server
.aofrewrite_scheduled
);
1362 if (server
.loading
) {
1364 time_t eta
, elapsed
;
1365 off_t remaining_bytes
= server
.loading_total_bytes
-
1366 server
.loading_loaded_bytes
;
1368 perc
= ((double)server
.loading_loaded_bytes
/
1369 server
.loading_total_bytes
) * 100;
1371 elapsed
= time(NULL
)-server
.loading_start_time
;
1373 eta
= 1; /* A fake 1 second figure if we don't have
1376 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1379 info
= sdscatprintf(info
,
1380 "loading_start_time:%ld\r\n"
1381 "loading_total_bytes:%llu\r\n"
1382 "loading_loaded_bytes:%llu\r\n"
1383 "loading_loaded_perc:%.2f\r\n"
1384 "loading_eta_seconds:%ld\r\n"
1385 ,(unsigned long) server
.loading_start_time
,
1386 (unsigned long long) server
.loading_total_bytes
,
1387 (unsigned long long) server
.loading_loaded_bytes
,
1395 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1396 if (sections
++) info
= sdscat(info
,"\r\n");
1397 info
= sdscatprintf(info
,
1399 "total_connections_received:%lld\r\n"
1400 "total_commands_processed:%lld\r\n"
1401 "expired_keys:%lld\r\n"
1402 "evicted_keys:%lld\r\n"
1403 "keyspace_hits:%lld\r\n"
1404 "keyspace_misses:%lld\r\n"
1405 "pubsub_channels:%ld\r\n"
1406 "pubsub_patterns:%u\r\n"
1407 "latest_fork_usec:%lld\r\n",
1408 server
.stat_numconnections
,
1409 server
.stat_numcommands
,
1410 server
.stat_expiredkeys
,
1411 server
.stat_evictedkeys
,
1412 server
.stat_keyspace_hits
,
1413 server
.stat_keyspace_misses
,
1414 dictSize(server
.pubsub_channels
),
1415 listLength(server
.pubsub_patterns
),
1416 server
.stat_fork_time
);
1420 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1421 if (sections
++) info
= sdscat(info
,"\r\n");
1422 info
= sdscatprintf(info
,
1425 server
.masterhost
== NULL
? "master" : "slave");
1426 if (server
.masterhost
) {
1427 info
= sdscatprintf(info
,
1428 "master_host:%s\r\n"
1429 "master_port:%d\r\n"
1430 "master_link_status:%s\r\n"
1431 "master_last_io_seconds_ago:%d\r\n"
1432 "master_sync_in_progress:%d\r\n"
1435 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1438 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1439 server
.replstate
== REDIS_REPL_TRANSFER
1442 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1443 info
= sdscatprintf(info
,
1444 "master_sync_left_bytes:%ld\r\n"
1445 "master_sync_last_io_seconds_ago:%d\r\n"
1446 ,(long)server
.repl_transfer_left
,
1447 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1451 if (server
.replstate
!= REDIS_REPL_CONNECTED
) {
1452 info
= sdscatprintf(info
,
1453 "master_link_down_since_seconds:%ld\r\n",
1454 (long)time(NULL
)-server
.repl_down_since
);
1457 info
= sdscatprintf(info
,
1458 "connected_slaves:%d\r\n",
1459 listLength(server
.slaves
));
1463 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1464 if (sections
++) info
= sdscat(info
,"\r\n");
1465 info
= sdscatprintf(info
,
1467 "used_cpu_sys:%.2f\r\n"
1468 "used_cpu_user:%.2f\r\n"
1469 "used_cpu_sys_children:%.2f\r\n"
1470 "used_cpu_user_children:%.2f\r\n",
1471 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1472 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1473 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1474 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000);
1478 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1479 if (sections
++) info
= sdscat(info
,"\r\n");
1480 info
= sdscatprintf(info
, "# Commandstats\r\n");
1481 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1482 for (j
= 0; j
< numcommands
; j
++) {
1483 struct redisCommand
*c
= redisCommandTable
+j
;
1485 if (!c
->calls
) continue;
1486 info
= sdscatprintf(info
,
1487 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1488 c
->name
, c
->calls
, c
->microseconds
,
1489 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1494 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1495 if (sections
++) info
= sdscat(info
,"\r\n");
1496 info
= sdscatprintf(info
,
1498 "cluster_enabled:%d\r\n",
1499 server
.cluster_enabled
);
1503 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1504 if (sections
++) info
= sdscat(info
,"\r\n");
1505 info
= sdscatprintf(info
, "# Keyspace\r\n");
1506 for (j
= 0; j
< server
.dbnum
; j
++) {
1507 long long keys
, vkeys
;
1509 keys
= dictSize(server
.db
[j
].dict
);
1510 vkeys
= dictSize(server
.db
[j
].expires
);
1511 if (keys
|| vkeys
) {
1512 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1520 void infoCommand(redisClient
*c
) {
1521 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1524 addReply(c
,shared
.syntaxerr
);
1527 sds info
= genRedisInfoString(section
);
1528 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1529 (unsigned long)sdslen(info
)));
1530 addReplySds(c
,info
);
1531 addReply(c
,shared
.crlf
);
1534 void monitorCommand(redisClient
*c
) {
1535 /* ignore MONITOR if aleady slave or in monitor mode */
1536 if (c
->flags
& REDIS_SLAVE
) return;
1538 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1540 listAddNodeTail(server
.monitors
,c
);
1541 addReply(c
,shared
.ok
);
1544 /* ============================ Maxmemory directive ======================== */
1546 /* This function gets called when 'maxmemory' is set on the config file to limit
1547 * the max memory used by the server, and we are out of memory.
1548 * This function will try to, in order:
1550 * - Free objects from the free list
1551 * - Try to remove keys with an EXPIRE set
1553 * It is not possible to free enough memory to reach used-memory < maxmemory
1554 * the server will start refusing commands that will enlarge even more the
1557 void freeMemoryIfNeeded(void) {
1558 /* Remove keys accordingly to the active policy as long as we are
1559 * over the memory limit. */
1560 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1562 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1563 int j
, k
, freed
= 0;
1565 for (j
= 0; j
< server
.dbnum
; j
++) {
1566 long bestval
= 0; /* just to prevent warning */
1568 struct dictEntry
*de
;
1569 redisDb
*db
= server
.db
+j
;
1572 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1573 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1575 dict
= server
.db
[j
].dict
;
1577 dict
= server
.db
[j
].expires
;
1579 if (dictSize(dict
) == 0) continue;
1581 /* volatile-random and allkeys-random policy */
1582 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1583 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1585 de
= dictGetRandomKey(dict
);
1586 bestkey
= dictGetEntryKey(de
);
1589 /* volatile-lru and allkeys-lru policy */
1590 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1591 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1593 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1598 de
= dictGetRandomKey(dict
);
1599 thiskey
= dictGetEntryKey(de
);
1600 /* When policy is volatile-lru we need an additonal lookup
1601 * to locate the real key, as dict is set to db->expires. */
1602 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1603 de
= dictFind(db
->dict
, thiskey
);
1604 o
= dictGetEntryVal(de
);
1605 thisval
= estimateObjectIdleTime(o
);
1607 /* Higher idle time is better candidate for deletion */
1608 if (bestkey
== NULL
|| thisval
> bestval
) {
1616 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1617 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1621 de
= dictGetRandomKey(dict
);
1622 thiskey
= dictGetEntryKey(de
);
1623 thisval
= (long) dictGetEntryVal(de
);
1625 /* Expire sooner (minor expire unix timestamp) is better
1626 * candidate for deletion */
1627 if (bestkey
== NULL
|| thisval
< bestval
) {
1634 /* Finally remove the selected key. */
1636 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1637 propagateExpire(db
,keyobj
);
1638 dbDelete(db
,keyobj
);
1639 server
.stat_evictedkeys
++;
1640 decrRefCount(keyobj
);
1644 if (!freed
) return; /* nothing to free... */
1648 /* =================================== Main! ================================ */
1651 int linuxOvercommitMemoryValue(void) {
1652 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1656 if (fgets(buf
,64,fp
) == NULL
) {
1665 void linuxOvercommitMemoryWarning(void) {
1666 if (linuxOvercommitMemoryValue() == 0) {
1667 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.");
1670 #endif /* __linux__ */
1672 void createPidFile(void) {
1673 /* Try to write the pid file in a best-effort way. */
1674 FILE *fp
= fopen(server
.pidfile
,"w");
1676 fprintf(fp
,"%d\n",(int)getpid());
1681 void daemonize(void) {
1684 if (fork() != 0) exit(0); /* parent exits */
1685 setsid(); /* create a new session */
1687 /* Every output goes to /dev/null. If Redis is daemonized but
1688 * the 'logfile' is set to 'stdout' in the configuration file
1689 * it will not log at all. */
1690 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1691 dup2(fd
, STDIN_FILENO
);
1692 dup2(fd
, STDOUT_FILENO
);
1693 dup2(fd
, STDERR_FILENO
);
1694 if (fd
> STDERR_FILENO
) close(fd
);
1699 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1700 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1705 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1706 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1710 void redisAsciiArt(void) {
1711 #include "asciilogo.h"
1712 char *buf
= zmalloc(1024*16);
1714 snprintf(buf
,1024*16,ascii_logo
,
1717 strtol(redisGitDirty(),NULL
,10) > 0,
1718 (sizeof(long) == 8) ? "64" : "32",
1719 server
.cluster_enabled
? "cluster" : "stand alone",
1723 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1727 int main(int argc
, char **argv
) {
1732 if (strcmp(argv
[1], "-v") == 0 ||
1733 strcmp(argv
[1], "--version") == 0) version();
1734 if (strcmp(argv
[1], "--help") == 0) usage();
1735 resetServerSaveParams();
1736 loadServerConfig(argv
[1]);
1737 } else if ((argc
> 2)) {
1740 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'");
1742 if (server
.daemonize
) daemonize();
1744 if (server
.daemonize
) createPidFile();
1746 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1748 linuxOvercommitMemoryWarning();
1751 if (server
.appendonly
) {
1752 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1753 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1755 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1756 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",(float)(ustime()-start
)/1000000);
1758 if (server
.ipfd
> 0)
1759 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1760 if (server
.sofd
> 0)
1761 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1762 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1764 aeDeleteEventLoop(server
.el
);
1768 #ifdef HAVE_BACKTRACE
1769 static void *getMcontextEip(ucontext_t
*uc
) {
1770 #if defined(__FreeBSD__)
1771 return (void*) uc
->uc_mcontext
.mc_eip
;
1772 #elif defined(__dietlibc__)
1773 return (void*) uc
->uc_mcontext
.eip
;
1774 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1776 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1778 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1780 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1781 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1782 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1784 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1786 #elif defined(__i386__)
1787 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1788 #elif defined(__X86_64__) || defined(__x86_64__)
1789 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1790 #elif defined(__ia64__) /* Linux IA64 */
1791 return (void*) uc
->uc_mcontext
.sc_ip
;
1797 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1799 char **messages
= NULL
;
1800 int i
, trace_size
= 0;
1801 ucontext_t
*uc
= (ucontext_t
*) secret
;
1803 struct sigaction act
;
1804 REDIS_NOTUSED(info
);
1806 redisLog(REDIS_WARNING
,
1807 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1808 infostring
= genRedisInfoString("all");
1809 redisLogRaw(REDIS_WARNING
, infostring
);
1810 /* It's not safe to sdsfree() the returned string under memory
1811 * corruption conditions. Let it leak as we are going to abort */
1813 trace_size
= backtrace(trace
, 100);
1814 /* overwrite sigaction with caller's address */
1815 if (getMcontextEip(uc
) != NULL
) {
1816 trace
[1] = getMcontextEip(uc
);
1818 messages
= backtrace_symbols(trace
, trace_size
);
1820 for (i
=1; i
<trace_size
; ++i
)
1821 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1823 /* free(messages); Don't call free() with possibly corrupted memory. */
1824 if (server
.daemonize
) unlink(server
.pidfile
);
1826 /* Make sure we exit with the right signal at the end. So for instance
1827 * the core will be dumped if enabled. */
1828 sigemptyset (&act
.sa_mask
);
1829 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1830 * is used. Otherwise, sa_handler is used */
1831 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1832 act
.sa_handler
= SIG_DFL
;
1833 sigaction (sig
, &act
, NULL
);
1836 #endif /* HAVE_BACKTRACE */
1838 static void sigtermHandler(int sig
) {
1841 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1842 server
.shutdown_asap
= 1;
1845 void setupSignalHandlers(void) {
1846 struct sigaction act
;
1848 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1849 * Otherwise, sa_handler is used. */
1850 sigemptyset(&act
.sa_mask
);
1851 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1852 act
.sa_handler
= sigtermHandler
;
1853 sigaction(SIGTERM
, &act
, NULL
);
1855 #ifdef HAVE_BACKTRACE
1856 sigemptyset(&act
.sa_mask
);
1857 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1858 act
.sa_sigaction
= sigsegvHandler
;
1859 sigaction(SIGSEGV
, &act
, NULL
);
1860 sigaction(SIGBUS
, &act
, NULL
);
1861 sigaction(SIGFPE
, &act
, NULL
);
1862 sigaction(SIGILL
, &act
, NULL
);