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.
37 #endif /* HAVE_BACKTRACE */
46 #include <arpa/inet.h>
50 #include <sys/resource.h>
55 #include <sys/resource.h>
57 /* Our shared "common" objects */
59 struct sharedObjectsStruct shared
;
61 /* Global vars that are actally used as constants. The following double
62 * values are used for double on-disk serialization, and are initialized
63 * at runtime to avoid strange compiler optimizations. */
65 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
67 /*================================= Globals ================================= */
70 struct redisServer server
; /* server global state */
71 struct redisCommand
*commandTable
;
72 struct redisCommand redisCommandTable
[] = {
73 {"get",getCommand
,2,0,NULL
,1,1,1,0,0},
74 {"set",setCommand
,3,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,1,1,1,0,0},
75 {"setnx",setnxCommand
,3,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,1,1,1,0,0},
76 {"setex",setexCommand
,4,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,2,2,1,0,0},
77 {"append",appendCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
78 {"strlen",strlenCommand
,2,0,NULL
,1,1,1,0,0},
79 {"del",delCommand
,-2,0,noPreloadGetKeys
,1,-1,1,0,0},
80 {"exists",existsCommand
,2,0,NULL
,1,1,1,0,0},
81 {"setbit",setbitCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
82 {"getbit",getbitCommand
,3,0,NULL
,1,1,1,0,0},
83 {"setrange",setrangeCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
84 {"getrange",getrangeCommand
,4,0,NULL
,1,1,1,0,0},
85 {"substr",getrangeCommand
,4,0,NULL
,1,1,1,0,0},
86 {"incr",incrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
87 {"decr",decrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
88 {"mget",mgetCommand
,-2,0,NULL
,1,-1,1,0,0},
89 {"rpush",rpushCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
90 {"lpush",lpushCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
91 {"rpushx",rpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
92 {"lpushx",lpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
93 {"linsert",linsertCommand
,5,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
94 {"rpop",rpopCommand
,2,0,NULL
,1,1,1,0,0},
95 {"lpop",lpopCommand
,2,0,NULL
,1,1,1,0,0},
96 {"brpop",brpopCommand
,-3,0,NULL
,1,1,1,0,0},
97 {"brpoplpush",brpoplpushCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,2,1,0,0},
98 {"blpop",blpopCommand
,-3,0,NULL
,1,-2,1,0,0},
99 {"llen",llenCommand
,2,0,NULL
,1,1,1,0,0},
100 {"lindex",lindexCommand
,3,0,NULL
,1,1,1,0,0},
101 {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
102 {"lrange",lrangeCommand
,4,0,NULL
,1,1,1,0,0},
103 {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1,0,0},
104 {"lrem",lremCommand
,4,0,NULL
,1,1,1,0,0},
105 {"rpoplpush",rpoplpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1,0,0},
106 {"sadd",saddCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
107 {"srem",sremCommand
,-3,0,NULL
,1,1,1,0,0},
108 {"smove",smoveCommand
,4,0,NULL
,1,2,1,0,0},
109 {"sismember",sismemberCommand
,3,0,NULL
,1,1,1,0,0},
110 {"scard",scardCommand
,2,0,NULL
,1,1,1,0,0},
111 {"spop",spopCommand
,2,0,NULL
,1,1,1,0,0},
112 {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1,0,0},
113 {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
114 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
115 {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
116 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
117 {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
118 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
119 {"smembers",sinterCommand
,2,0,NULL
,1,1,1,0,0},
120 {"zadd",zaddCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
121 {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
122 {"zrem",zremCommand
,-3,0,NULL
,1,1,1,0,0},
123 {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1,0,0},
124 {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1,0,0},
125 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
126 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
127 {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1,0,0},
128 {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1,0,0},
129 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1,0,0},
130 {"zcount",zcountCommand
,4,0,NULL
,1,1,1,0,0},
131 {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1,0,0},
132 {"zcard",zcardCommand
,2,0,NULL
,1,1,1,0,0},
133 {"zscore",zscoreCommand
,3,0,NULL
,1,1,1,0,0},
134 {"zrank",zrankCommand
,3,0,NULL
,1,1,1,0,0},
135 {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1,0,0},
136 {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
137 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
138 {"hget",hgetCommand
,3,0,NULL
,1,1,1,0,0},
139 {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
140 {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1,0,0},
141 {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
142 {"hdel",hdelCommand
,-3,0,NULL
,1,1,1,0,0},
143 {"hlen",hlenCommand
,2,0,NULL
,1,1,1,0,0},
144 {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1,0,0},
145 {"hvals",hvalsCommand
,2,0,NULL
,1,1,1,0,0},
146 {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1,0,0},
147 {"hexists",hexistsCommand
,3,0,NULL
,1,1,1,0,0},
148 {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
149 {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
150 {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
151 {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2,0,0},
152 {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2,0,0},
153 {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0,0,0},
154 {"select",selectCommand
,2,0,NULL
,0,0,0,0,0},
155 {"move",moveCommand
,3,0,NULL
,1,1,1,0,0},
156 {"rename",renameCommand
,3,0,renameGetKeys
,1,2,1,0,0},
157 {"renamenx",renamenxCommand
,3,0,renameGetKeys
,1,2,1,0,0},
158 {"expire",expireCommand
,3,0,NULL
,1,1,1,0,0},
159 {"expireat",expireatCommand
,3,0,NULL
,1,1,1,0,0},
160 {"keys",keysCommand
,2,0,NULL
,0,0,0,0,0},
161 {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0,0,0},
162 {"auth",authCommand
,2,0,NULL
,0,0,0,0,0},
163 {"ping",pingCommand
,1,0,NULL
,0,0,0,0,0},
164 {"echo",echoCommand
,2,0,NULL
,0,0,0,0,0},
165 {"save",saveCommand
,1,0,NULL
,0,0,0,0,0},
166 {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0,0,0},
167 {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0,0,0},
168 {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0,0,0},
169 {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0,0,0},
170 {"type",typeCommand
,2,0,NULL
,1,1,1,0,0},
171 {"multi",multiCommand
,1,0,NULL
,0,0,0,0,0},
172 {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,NULL
,0,0,0,0,0},
173 {"discard",discardCommand
,1,0,NULL
,0,0,0,0,0},
174 {"sync",syncCommand
,1,0,NULL
,0,0,0,0,0},
175 {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0,0,0},
176 {"flushall",flushallCommand
,1,0,NULL
,0,0,0,0,0},
177 {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
178 {"info",infoCommand
,-1,0,NULL
,0,0,0,0,0},
179 {"monitor",monitorCommand
,1,0,NULL
,0,0,0,0,0},
180 {"ttl",ttlCommand
,2,0,NULL
,1,1,1,0,0},
181 {"persist",persistCommand
,2,0,NULL
,1,1,1,0,0},
182 {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0,0,0},
183 {"debug",debugCommand
,-2,0,NULL
,0,0,0,0,0},
184 {"config",configCommand
,-2,0,NULL
,0,0,0,0,0},
185 {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0,0,0},
186 {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0,0,0},
187 {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0,0,0},
188 {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0,0,0},
189 {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0,0,0},
190 {"watch",watchCommand
,-2,0,noPreloadGetKeys
,1,-1,1,0,0},
191 {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0,0,0},
192 {"cluster",clusterCommand
,-2,0,NULL
,0,0,0,0,0},
193 {"restore",restoreCommand
,4,0,NULL
,0,0,0,0,0},
194 {"migrate",migrateCommand
,6,0,NULL
,0,0,0,0,0},
195 {"dump",dumpCommand
,2,0,NULL
,0,0,0,0,0},
196 {"object",objectCommand
,-2,0,NULL
,0,0,0,0,0},
197 {"client",clientCommand
,-2,0,NULL
,0,0,0,0,0},
198 {"eval",evalCommand
,-3,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
199 {"evalsha",evalShaCommand
,-3,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
200 {"slowlog",slowlogCommand
,-2,0,NULL
,0,0,0,0,0}
203 /*============================ Utility functions ============================ */
205 /* Low level logging. To use only for very big messages, otherwise
206 * redisLog() is to prefer. */
207 void redisLogRaw(int level
, const char *msg
) {
208 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
209 const char *c
= ".-*#";
210 time_t now
= time(NULL
);
213 int rawmode
= (level
& REDIS_LOG_RAW
);
215 level
&= 0xff; /* clear flags */
216 if (level
< server
.verbosity
) return;
218 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
222 fprintf(fp
,"%s",msg
);
224 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
225 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
229 if (server
.logfile
) fclose(fp
);
231 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
234 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
235 * is used across the code. The raw version is only used in order to dump
236 * the INFO output on crash. */
237 void redisLog(int level
, const char *fmt
, ...) {
239 char msg
[REDIS_MAX_LOGMSG_LEN
];
241 if ((level
&0xff) < server
.verbosity
) return;
244 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
247 redisLogRaw(level
,msg
);
250 /* Redis generally does not try to recover from out of memory conditions
251 * when allocating objects or strings, it is not clear if it will be possible
252 * to report this condition to the client since the networking layer itself
253 * is based on heap allocation for send buffers, so we simply abort.
254 * At least the code will be simpler to read... */
255 void oom(const char *msg
) {
256 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
261 /* Return the UNIX time in microseconds */
262 long long ustime(void) {
266 gettimeofday(&tv
, NULL
);
267 ust
= ((long long)tv
.tv_sec
)*1000000;
272 /*====================== Hash table type implementation ==================== */
274 /* This is an hash table type that uses the SDS dynamic strings libary as
275 * keys and radis objects as values (objects can hold SDS strings,
278 void dictVanillaFree(void *privdata
, void *val
)
280 DICT_NOTUSED(privdata
);
284 void dictListDestructor(void *privdata
, void *val
)
286 DICT_NOTUSED(privdata
);
287 listRelease((list
*)val
);
290 int dictSdsKeyCompare(void *privdata
, const void *key1
,
294 DICT_NOTUSED(privdata
);
296 l1
= sdslen((sds
)key1
);
297 l2
= sdslen((sds
)key2
);
298 if (l1
!= l2
) return 0;
299 return memcmp(key1
, key2
, l1
) == 0;
302 /* A case insensitive version used for the command lookup table. */
303 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
306 DICT_NOTUSED(privdata
);
308 return strcasecmp(key1
, key2
) == 0;
311 void dictRedisObjectDestructor(void *privdata
, void *val
)
313 DICT_NOTUSED(privdata
);
315 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
319 void dictSdsDestructor(void *privdata
, void *val
)
321 DICT_NOTUSED(privdata
);
326 int dictObjKeyCompare(void *privdata
, const void *key1
,
329 const robj
*o1
= key1
, *o2
= key2
;
330 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
333 unsigned int dictObjHash(const void *key
) {
335 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
338 unsigned int dictSdsHash(const void *key
) {
339 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
342 unsigned int dictSdsCaseHash(const void *key
) {
343 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
346 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
349 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
352 if (o1
->encoding
== REDIS_ENCODING_INT
&&
353 o2
->encoding
== REDIS_ENCODING_INT
)
354 return o1
->ptr
== o2
->ptr
;
356 o1
= getDecodedObject(o1
);
357 o2
= getDecodedObject(o2
);
358 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
364 unsigned int dictEncObjHash(const void *key
) {
365 robj
*o
= (robj
*) key
;
367 if (o
->encoding
== REDIS_ENCODING_RAW
) {
368 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
370 if (o
->encoding
== REDIS_ENCODING_INT
) {
374 len
= ll2string(buf
,32,(long)o
->ptr
);
375 return dictGenHashFunction((unsigned char*)buf
, len
);
379 o
= getDecodedObject(o
);
380 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
387 /* Sets type hash table */
388 dictType setDictType
= {
389 dictEncObjHash
, /* hash function */
392 dictEncObjKeyCompare
, /* key compare */
393 dictRedisObjectDestructor
, /* key destructor */
394 NULL
/* val destructor */
397 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
398 dictType zsetDictType
= {
399 dictEncObjHash
, /* hash function */
402 dictEncObjKeyCompare
, /* key compare */
403 dictRedisObjectDestructor
, /* key destructor */
404 NULL
/* val destructor */
407 /* Db->dict, keys are sds strings, vals are Redis objects. */
408 dictType dbDictType
= {
409 dictSdsHash
, /* hash function */
412 dictSdsKeyCompare
, /* key compare */
413 dictSdsDestructor
, /* key destructor */
414 dictRedisObjectDestructor
/* val destructor */
418 dictType keyptrDictType
= {
419 dictSdsHash
, /* hash function */
422 dictSdsKeyCompare
, /* key compare */
423 NULL
, /* key destructor */
424 NULL
/* val destructor */
427 /* Command table. sds string -> command struct pointer. */
428 dictType commandTableDictType
= {
429 dictSdsCaseHash
, /* hash function */
432 dictSdsKeyCaseCompare
, /* key compare */
433 dictSdsDestructor
, /* key destructor */
434 NULL
/* val destructor */
437 /* Hash type hash table (note that small hashes are represented with zimpaps) */
438 dictType hashDictType
= {
439 dictEncObjHash
, /* hash function */
442 dictEncObjKeyCompare
, /* key compare */
443 dictRedisObjectDestructor
, /* key destructor */
444 dictRedisObjectDestructor
/* val destructor */
447 /* Keylist hash table type has unencoded redis objects as keys and
448 * lists as values. It's used for blocking operations (BLPOP) and to
449 * map swapped keys to a list of clients waiting for this keys to be loaded. */
450 dictType keylistDictType
= {
451 dictObjHash
, /* hash function */
454 dictObjKeyCompare
, /* key compare */
455 dictRedisObjectDestructor
, /* key destructor */
456 dictListDestructor
/* val destructor */
459 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
460 * clusterNode structures. */
461 dictType clusterNodesDictType
= {
462 dictSdsHash
, /* hash function */
465 dictSdsKeyCompare
, /* key compare */
466 dictSdsDestructor
, /* key destructor */
467 NULL
/* val destructor */
470 int htNeedsResize(dict
*dict
) {
471 long long size
, used
;
473 size
= dictSlots(dict
);
474 used
= dictSize(dict
);
475 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
476 (used
*100/size
< REDIS_HT_MINFILL
));
479 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
480 * we resize the hash table to save memory */
481 void tryResizeHashTables(void) {
484 for (j
= 0; j
< server
.dbnum
; j
++) {
485 if (htNeedsResize(server
.db
[j
].dict
))
486 dictResize(server
.db
[j
].dict
);
487 if (htNeedsResize(server
.db
[j
].expires
))
488 dictResize(server
.db
[j
].expires
);
492 /* Our hash table implementation performs rehashing incrementally while
493 * we write/read from the hash table. Still if the server is idle, the hash
494 * table will use two tables for a long time. So we try to use 1 millisecond
495 * of CPU time at every serverCron() loop in order to rehash some key. */
496 void incrementallyRehash(void) {
499 for (j
= 0; j
< server
.dbnum
; j
++) {
500 if (dictIsRehashing(server
.db
[j
].dict
)) {
501 dictRehashMilliseconds(server
.db
[j
].dict
,1);
502 break; /* already used our millisecond for this loop... */
507 /* This function is called once a background process of some kind terminates,
508 * as we want to avoid resizing the hash tables when there is a child in order
509 * to play well with copy-on-write (otherwise when a resize happens lots of
510 * memory pages are copied). The goal of this function is to update the ability
511 * for dict.c to resize the hash tables accordingly to the fact we have o not
513 void updateDictResizePolicy(void) {
514 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
520 /* ======================= Cron: called every 100 ms ======================== */
522 /* Try to expire a few timed out keys. The algorithm used is adaptive and
523 * will use few CPU cycles if there are few expiring keys, otherwise
524 * it will get more aggressive to avoid that too much memory is used by
525 * keys that can be removed from the keyspace. */
526 void activeExpireCycle(void) {
529 for (j
= 0; j
< server
.dbnum
; j
++) {
531 redisDb
*db
= server
.db
+j
;
533 /* Continue to expire if at the end of the cycle more than 25%
534 * of the keys were expired. */
536 long num
= dictSize(db
->expires
);
537 time_t now
= time(NULL
);
540 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
541 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
546 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
547 t
= (time_t) dictGetEntryVal(de
);
549 sds key
= dictGetEntryKey(de
);
550 robj
*keyobj
= createStringObject(key
,sdslen(key
));
552 propagateExpire(db
,keyobj
);
554 decrRefCount(keyobj
);
556 server
.stat_expiredkeys
++;
559 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
563 void updateLRUClock(void) {
564 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
568 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
569 int j
, loops
= server
.cronloops
;
570 REDIS_NOTUSED(eventLoop
);
572 REDIS_NOTUSED(clientData
);
574 /* We take a cached value of the unix time in the global state because
575 * with virtual memory and aging there is to store the current time
576 * in objects at every object access, and accuracy is not needed.
577 * To access a global var is faster than calling time(NULL) */
578 server
.unixtime
= time(NULL
);
580 /* We have just 22 bits per object for LRU information.
581 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
582 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
584 * Note that even if this will wrap after 1.5 years it's not a problem,
585 * everything will still work but just some object will appear younger
586 * to Redis. But for this to happen a given object should never be touched
589 * Note that you can change the resolution altering the
590 * REDIS_LRU_CLOCK_RESOLUTION define.
594 /* Record the max memory used since the server was started. */
595 if (zmalloc_used_memory() > server
.stat_peak_memory
)
596 server
.stat_peak_memory
= zmalloc_used_memory();
598 /* We received a SIGTERM, shutting down here in a safe way, as it is
599 * not ok doing so inside the signal handler. */
600 if (server
.shutdown_asap
) {
601 if (prepareForShutdown() == REDIS_OK
) exit(0);
602 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
605 /* Show some info about non-empty databases */
606 for (j
= 0; j
< server
.dbnum
; j
++) {
607 long long size
, used
, vkeys
;
609 size
= dictSlots(server
.db
[j
].dict
);
610 used
= dictSize(server
.db
[j
].dict
);
611 vkeys
= dictSize(server
.db
[j
].expires
);
612 if (!(loops
% 50) && (used
|| vkeys
)) {
613 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
614 /* dictPrintStats(server.dict); */
618 /* We don't want to resize the hash tables while a bacground saving
619 * is in progress: the saving child is created using fork() that is
620 * implemented with a copy-on-write semantic in most modern systems, so
621 * if we resize the HT while there is the saving child at work actually
622 * a lot of memory movements in the parent will cause a lot of pages
624 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
625 if (!(loops
% 10)) tryResizeHashTables();
626 if (server
.activerehashing
) incrementallyRehash();
629 /* Show information about connected clients */
631 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
632 listLength(server
.clients
)-listLength(server
.slaves
),
633 listLength(server
.slaves
),
634 zmalloc_used_memory());
637 /* Close connections of timedout clients */
638 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
639 closeTimedoutClients();
641 /* Start a scheduled AOF rewrite if this was requested by the user while
642 * a BGSAVE was in progress. */
643 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1 &&
644 server
.aofrewrite_scheduled
)
646 rewriteAppendOnlyFileBackground();
649 /* Check if a background saving or AOF rewrite in progress terminated. */
650 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
654 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
655 int exitcode
= WEXITSTATUS(statloc
);
658 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
660 if (pid
== server
.bgsavechildpid
) {
661 backgroundSaveDoneHandler(exitcode
,bysignal
);
663 backgroundRewriteDoneHandler(exitcode
,bysignal
);
665 updateDictResizePolicy();
668 time_t now
= time(NULL
);
670 /* If there is not a background saving/rewrite in progress check if
671 * we have to save/rewrite now */
672 for (j
= 0; j
< server
.saveparamslen
; j
++) {
673 struct saveparam
*sp
= server
.saveparams
+j
;
675 if (server
.dirty
>= sp
->changes
&&
676 now
-server
.lastsave
> sp
->seconds
) {
677 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
678 sp
->changes
, sp
->seconds
);
679 rdbSaveBackground(server
.dbfilename
);
684 /* Trigger an AOF rewrite if needed */
685 if (server
.bgsavechildpid
== -1 &&
686 server
.bgrewritechildpid
== -1 &&
687 server
.auto_aofrewrite_perc
&&
688 server
.appendonly_current_size
> server
.auto_aofrewrite_min_size
)
690 long long base
= server
.auto_aofrewrite_base_size
?
691 server
.auto_aofrewrite_base_size
: 1;
692 long long growth
= (server
.appendonly_current_size
*100/base
) - 100;
693 if (growth
>= server
.auto_aofrewrite_perc
) {
694 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
695 rewriteAppendOnlyFileBackground();
700 /* Expire a few keys per cycle, only if this is a master.
701 * On slaves we wait for DEL operations synthesized by the master
702 * in order to guarantee a strict consistency. */
703 if (server
.masterhost
== NULL
) activeExpireCycle();
705 /* Replication cron function -- used to reconnect to master and
706 * to detect transfer failures. */
707 if (!(loops
% 10)) replicationCron();
709 /* Run other sub-systems specific cron jobs */
710 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
712 if (!(loops
% 10)) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)1000);
717 /* This function gets called every time Redis is entering the
718 * main loop of the event driven library, that is, before to sleep
719 * for ready file descriptors. */
720 void beforeSleep(struct aeEventLoop
*eventLoop
) {
721 REDIS_NOTUSED(eventLoop
);
725 /* Try to process pending commands for clients that were just unblocked. */
726 while (listLength(server
.unblocked_clients
)) {
727 ln
= listFirst(server
.unblocked_clients
);
728 redisAssert(ln
!= NULL
);
730 listDelNode(server
.unblocked_clients
,ln
);
731 c
->flags
&= ~REDIS_UNBLOCKED
;
733 /* Process remaining data in the input buffer. */
734 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
735 processInputBuffer(c
);
738 /* Write the AOF buffer on disk */
739 flushAppendOnlyFile();
742 /* =========================== Server initialization ======================== */
744 void createSharedObjects(void) {
747 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
748 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
749 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
750 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
751 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
752 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
753 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
754 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
755 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
756 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
757 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
758 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
759 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
760 "-ERR Operation against a key holding the wrong kind of value\r\n"));
761 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
762 "-ERR no such key\r\n"));
763 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
764 "-ERR syntax error\r\n"));
765 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
766 "-ERR source and destination objects are the same\r\n"));
767 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
768 "-ERR index out of range\r\n"));
769 shared
.noscripterr
= createObject(REDIS_STRING
,sdsnew(
770 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
771 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
772 "-LOADING Redis is loading the dataset in memory\r\n"));
773 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
774 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
775 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
776 shared
.select0
= createStringObject("select 0\r\n",10);
777 shared
.select1
= createStringObject("select 1\r\n",10);
778 shared
.select2
= createStringObject("select 2\r\n",10);
779 shared
.select3
= createStringObject("select 3\r\n",10);
780 shared
.select4
= createStringObject("select 4\r\n",10);
781 shared
.select5
= createStringObject("select 5\r\n",10);
782 shared
.select6
= createStringObject("select 6\r\n",10);
783 shared
.select7
= createStringObject("select 7\r\n",10);
784 shared
.select8
= createStringObject("select 8\r\n",10);
785 shared
.select9
= createStringObject("select 9\r\n",10);
786 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
787 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
788 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
789 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
790 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
791 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
792 shared
.mbulk3
= createStringObject("*3\r\n",4);
793 shared
.mbulk4
= createStringObject("*4\r\n",4);
794 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
795 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
796 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
800 void initServerConfig() {
801 server
.port
= REDIS_SERVERPORT
;
802 server
.bindaddr
= NULL
;
803 server
.unixsocket
= NULL
;
806 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
807 server
.verbosity
= REDIS_VERBOSE
;
808 server
.maxidletime
= REDIS_MAXIDLETIME
;
809 server
.saveparams
= NULL
;
811 server
.logfile
= NULL
; /* NULL = log on standard output */
812 server
.syslog_enabled
= 0;
813 server
.syslog_ident
= zstrdup("redis");
814 server
.syslog_facility
= LOG_LOCAL0
;
815 server
.daemonize
= 0;
816 server
.appendonly
= 0;
817 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
818 server
.no_appendfsync_on_rewrite
= 0;
819 server
.auto_aofrewrite_perc
= REDIS_AUTO_AOFREWRITE_PERC
;
820 server
.auto_aofrewrite_min_size
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
;
821 server
.auto_aofrewrite_base_size
= 0;
822 server
.aofrewrite_scheduled
= 0;
823 server
.lastfsync
= time(NULL
);
824 server
.appendfd
= -1;
825 server
.appendseldb
= -1; /* Make sure the first time will not match */
826 server
.pidfile
= zstrdup("/var/run/redis.pid");
827 server
.dbfilename
= zstrdup("dump.rdb");
828 server
.appendfilename
= zstrdup("appendonly.aof");
829 server
.requirepass
= NULL
;
830 server
.rdbcompression
= 1;
831 server
.activerehashing
= 1;
832 server
.maxclients
= 0;
833 server
.bpop_blocked_clients
= 0;
834 server
.maxmemory
= 0;
835 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
836 server
.maxmemory_samples
= 3;
837 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
838 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
839 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
840 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
841 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
842 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
843 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
844 server
.shutdown_asap
= 0;
845 server
.cluster_enabled
= 0;
846 server
.cluster
.configfile
= zstrdup("nodes.conf");
847 server
.lua_time_limit
= REDIS_LUA_TIME_LIMIT
;
850 resetServerSaveParams();
852 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
853 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
854 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
855 /* Replication related */
857 server
.masterauth
= NULL
;
858 server
.masterhost
= NULL
;
859 server
.masterport
= 6379;
860 server
.master
= NULL
;
861 server
.replstate
= REDIS_REPL_NONE
;
862 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
863 server
.repl_serve_stale_data
= 1;
864 server
.repl_down_since
= -1;
866 /* Double constants initialization */
868 R_PosInf
= 1.0/R_Zero
;
869 R_NegInf
= -1.0/R_Zero
;
870 R_Nan
= R_Zero
/R_Zero
;
872 /* Command table -- we intiialize it here as it is part of the
873 * initial configuration, since command names may be changed via
874 * redis.conf using the rename-command directive. */
875 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
876 populateCommandTable();
877 server
.delCommand
= lookupCommandByCString("del");
878 server
.multiCommand
= lookupCommandByCString("multi");
881 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
882 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
888 signal(SIGHUP
, SIG_IGN
);
889 signal(SIGPIPE
, SIG_IGN
);
890 setupSignalHandlers();
892 if (server
.syslog_enabled
) {
893 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
894 server
.syslog_facility
);
897 server
.clients
= listCreate();
898 server
.slaves
= listCreate();
899 server
.monitors
= listCreate();
900 server
.unblocked_clients
= listCreate();
902 createSharedObjects();
903 server
.el
= aeCreateEventLoop();
904 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
906 if (server
.port
!= 0) {
907 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
908 if (server
.ipfd
== ANET_ERR
) {
909 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
913 if (server
.unixsocket
!= NULL
) {
914 unlink(server
.unixsocket
); /* don't care if this fails */
915 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
916 if (server
.sofd
== ANET_ERR
) {
917 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
921 if (server
.ipfd
< 0 && server
.sofd
< 0) {
922 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
925 for (j
= 0; j
< server
.dbnum
; j
++) {
926 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
927 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
928 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
929 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
932 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
933 server
.pubsub_patterns
= listCreate();
934 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
935 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
936 server
.cronloops
= 0;
937 server
.bgsavechildpid
= -1;
938 server
.bgrewritechildpid
= -1;
939 server
.bgrewritebuf
= sdsempty();
940 server
.aofbuf
= sdsempty();
941 server
.lastsave
= time(NULL
);
943 server
.stat_numcommands
= 0;
944 server
.stat_numconnections
= 0;
945 server
.stat_expiredkeys
= 0;
946 server
.stat_evictedkeys
= 0;
947 server
.stat_starttime
= time(NULL
);
948 server
.stat_keyspace_misses
= 0;
949 server
.stat_keyspace_hits
= 0;
950 server
.stat_peak_memory
= 0;
951 server
.stat_fork_time
= 0;
952 server
.unixtime
= time(NULL
);
953 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
954 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
955 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
956 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
957 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
959 if (server
.appendonly
) {
960 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
961 if (server
.appendfd
== -1) {
962 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
968 if (server
.cluster_enabled
) clusterInit();
972 srand(time(NULL
)^getpid());
975 /* Populates the Redis Command Table starting from the hard coded list
976 * we have on top of redis.c file. */
977 void populateCommandTable(void) {
979 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
981 for (j
= 0; j
< numcommands
; j
++) {
982 struct redisCommand
*c
= redisCommandTable
+j
;
985 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
986 assert(retval
== DICT_OK
);
990 void resetCommandTableStats(void) {
991 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
994 for (j
= 0; j
< numcommands
; j
++) {
995 struct redisCommand
*c
= redisCommandTable
+j
;
1002 /* ====================== Commands lookup and execution ===================== */
1004 struct redisCommand
*lookupCommand(sds name
) {
1005 return dictFetchValue(server
.commands
, name
);
1008 struct redisCommand
*lookupCommandByCString(char *s
) {
1009 struct redisCommand
*cmd
;
1010 sds name
= sdsnew(s
);
1012 cmd
= dictFetchValue(server
.commands
, name
);
1017 /* Call() is the core of Redis execution of a command */
1018 void call(redisClient
*c
) {
1019 long long dirty
, start
= ustime(), duration
;
1021 dirty
= server
.dirty
;
1023 dirty
= server
.dirty
-dirty
;
1024 duration
= ustime()-start
;
1025 c
->cmd
->microseconds
+= duration
;
1026 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1029 if (server
.appendonly
&& dirty
)
1030 feedAppendOnlyFile(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1031 if ((dirty
|| c
->cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1032 listLength(server
.slaves
))
1033 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1034 if (listLength(server
.monitors
))
1035 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1036 server
.stat_numcommands
++;
1039 /* If this function gets called we already read a whole
1040 * command, argments are in the client argv/argc fields.
1041 * processCommand() execute the command or prepare the
1042 * server for a bulk read from the client.
1044 * If 1 is returned the client is still alive and valid and
1045 * and other operations can be performed by the caller. Otherwise
1046 * if 0 is returned the client was destroied (i.e. after QUIT). */
1047 int processCommand(redisClient
*c
) {
1048 /* The QUIT command is handled separately. Normal command procs will
1049 * go through checking for replication and QUIT will cause trouble
1050 * when FORCE_REPLICATION is enabled and would be implemented in
1051 * a regular command proc. */
1052 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1053 addReply(c
,shared
.ok
);
1054 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1058 /* Now lookup the command and check ASAP about trivial error conditions
1059 * such as wrong arity, bad command name and so forth. */
1060 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1062 addReplyErrorFormat(c
,"unknown command '%s'",
1063 (char*)c
->argv
[0]->ptr
);
1065 } else if ((c
->cmd
->arity
> 0 && c
->cmd
->arity
!= c
->argc
) ||
1066 (c
->argc
< -c
->cmd
->arity
)) {
1067 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1072 /* Check if the user is authenticated */
1073 if (server
.requirepass
&& !c
->authenticated
&& c
->cmd
->proc
!= authCommand
)
1075 addReplyError(c
,"operation not permitted");
1079 /* If cluster is enabled, redirect here */
1080 if (server
.cluster_enabled
&&
1081 !(c
->cmd
->getkeys_proc
== NULL
&& c
->cmd
->firstkey
== 0)) {
1084 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1085 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1089 clusterNode
*n
= getNodeByQuery(c
,c
->cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1091 addReplyError(c
,"Multi keys request invalid in cluster");
1093 } else if (n
!= server
.cluster
.myself
) {
1094 addReplySds(c
,sdscatprintf(sdsempty(),
1095 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1096 hashslot
,n
->ip
,n
->port
));
1102 /* Handle the maxmemory directive.
1104 * First we try to free some memory if possible (if there are volatile
1105 * keys in the dataset). If there are not the only thing we can do
1106 * is returning an error. */
1107 if (server
.maxmemory
) freeMemoryIfNeeded();
1108 if (server
.maxmemory
&& (c
->cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1109 zmalloc_used_memory() > server
.maxmemory
)
1111 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1115 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1116 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1118 c
->cmd
->proc
!= subscribeCommand
&&
1119 c
->cmd
->proc
!= unsubscribeCommand
&&
1120 c
->cmd
->proc
!= psubscribeCommand
&&
1121 c
->cmd
->proc
!= punsubscribeCommand
) {
1122 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1126 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1127 * we are a slave with a broken link with master. */
1128 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1129 server
.repl_serve_stale_data
== 0 &&
1130 c
->cmd
->proc
!= infoCommand
&& c
->cmd
->proc
!= slaveofCommand
)
1133 "link with MASTER is down and slave-serve-stale-data is set to no");
1137 /* Loading DB? Return an error if the command is not INFO */
1138 if (server
.loading
&& c
->cmd
->proc
!= infoCommand
) {
1139 addReply(c
, shared
.loadingerr
);
1143 /* Exec the command */
1144 if (c
->flags
& REDIS_MULTI
&&
1145 c
->cmd
->proc
!= execCommand
&& c
->cmd
->proc
!= discardCommand
&&
1146 c
->cmd
->proc
!= multiCommand
&& c
->cmd
->proc
!= watchCommand
)
1148 queueMultiCommand(c
);
1149 addReply(c
,shared
.queued
);
1156 /*================================== Shutdown =============================== */
1158 int prepareForShutdown() {
1159 redisLog(REDIS_WARNING
,"User requested shutdown...");
1160 /* Kill the saving child if there is a background saving in progress.
1161 We want to avoid race conditions, for instance our saving child may
1162 overwrite the synchronous saving did by SHUTDOWN. */
1163 if (server
.bgsavechildpid
!= -1) {
1164 redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!");
1165 kill(server
.bgsavechildpid
,SIGKILL
);
1166 rdbRemoveTempFile(server
.bgsavechildpid
);
1168 if (server
.appendonly
) {
1169 /* Kill the AOF saving child as the AOF we already have may be longer
1170 * but contains the full dataset anyway. */
1171 if (server
.bgrewritechildpid
!= -1) {
1172 redisLog(REDIS_WARNING
,
1173 "There is a child rewriting the AOF. Killing it!");
1174 kill(server
.bgrewritechildpid
,SIGKILL
);
1176 /* Append only file: fsync() the AOF and exit */
1177 redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file.");
1178 aof_fsync(server
.appendfd
);
1180 if (server
.saveparamslen
> 0) {
1181 redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting.");
1182 /* Snapshotting. Perform a SYNC SAVE and exit */
1183 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1184 /* Ooops.. error saving! The best we can do is to continue
1185 * operating. Note that if there was a background saving process,
1186 * in the next cron() Redis will be notified that the background
1187 * saving aborted, handling special stuff like slaves pending for
1188 * synchronization... */
1189 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit.");
1193 if (server
.daemonize
) {
1194 redisLog(REDIS_NOTICE
,"Removing the pid file.");
1195 unlink(server
.pidfile
);
1197 /* Close the listening sockets. Apparently this allows faster restarts. */
1198 if (server
.ipfd
!= -1) close(server
.ipfd
);
1199 if (server
.sofd
!= -1) close(server
.sofd
);
1201 redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye...");
1205 /*================================== Commands =============================== */
1207 void authCommand(redisClient
*c
) {
1208 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1209 c
->authenticated
= 1;
1210 addReply(c
,shared
.ok
);
1212 c
->authenticated
= 0;
1213 addReplyError(c
,"invalid password");
1217 void pingCommand(redisClient
*c
) {
1218 addReply(c
,shared
.pong
);
1221 void echoCommand(redisClient
*c
) {
1222 addReplyBulk(c
,c
->argv
[1]);
1225 /* Convert an amount of bytes into a human readable string in the form
1226 * of 100B, 2G, 100M, 4K, and so forth. */
1227 void bytesToHuman(char *s
, unsigned long long n
) {
1232 sprintf(s
,"%lluB",n
);
1234 } else if (n
< (1024*1024)) {
1235 d
= (double)n
/(1024);
1236 sprintf(s
,"%.2fK",d
);
1237 } else if (n
< (1024LL*1024*1024)) {
1238 d
= (double)n
/(1024*1024);
1239 sprintf(s
,"%.2fM",d
);
1240 } else if (n
< (1024LL*1024*1024*1024)) {
1241 d
= (double)n
/(1024LL*1024*1024);
1242 sprintf(s
,"%.2fG",d
);
1246 /* Create the string returned by the INFO command. This is decoupled
1247 * by the INFO command itself as we need to report the same information
1248 * on memory corruption problems. */
1249 sds
genRedisInfoString(char *section
) {
1250 sds info
= sdsempty();
1251 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1253 struct rusage self_ru
, c_ru
;
1254 unsigned long lol
, bib
;
1255 int allsections
= 0, defsections
= 0;
1259 allsections
= strcasecmp(section
,"all") == 0;
1260 defsections
= strcasecmp(section
,"default") == 0;
1263 getrusage(RUSAGE_SELF
, &self_ru
);
1264 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1265 getClientsMaxBuffers(&lol
,&bib
);
1268 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1269 if (sections
++) info
= sdscat(info
,"\r\n");
1270 info
= sdscatprintf(info
,
1272 "redis_version:%s\r\n"
1273 "redis_git_sha1:%s\r\n"
1274 "redis_git_dirty:%d\r\n"
1276 "multiplexing_api:%s\r\n"
1277 "process_id:%ld\r\n"
1279 "uptime_in_seconds:%ld\r\n"
1280 "uptime_in_days:%ld\r\n"
1281 "lru_clock:%ld\r\n",
1284 strtol(redisGitDirty(),NULL
,10) > 0,
1285 (sizeof(long) == 8) ? "64" : "32",
1291 (unsigned long) server
.lruclock
);
1295 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1296 if (sections
++) info
= sdscat(info
,"\r\n");
1297 info
= sdscatprintf(info
,
1299 "connected_clients:%d\r\n"
1300 "client_longest_output_list:%lu\r\n"
1301 "client_biggest_input_buf:%lu\r\n"
1302 "blocked_clients:%d\r\n",
1303 listLength(server
.clients
)-listLength(server
.slaves
),
1305 server
.bpop_blocked_clients
);
1309 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1313 bytesToHuman(hmem
,zmalloc_used_memory());
1314 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1315 if (sections
++) info
= sdscat(info
,"\r\n");
1316 info
= sdscatprintf(info
,
1318 "used_memory:%zu\r\n"
1319 "used_memory_human:%s\r\n"
1320 "used_memory_rss:%zu\r\n"
1321 "used_memory_peak:%zu\r\n"
1322 "used_memory_peak_human:%s\r\n"
1323 "used_memory_lua:%lld\r\n"
1324 "mem_fragmentation_ratio:%.2f\r\n"
1325 "mem_allocator:%s\r\n",
1326 zmalloc_used_memory(),
1329 server
.stat_peak_memory
,
1331 ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL,
1332 zmalloc_get_fragmentation_ratio(),
1338 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1339 if (sections
++) info
= sdscat(info
,"\r\n");
1340 info
= sdscatprintf(info
,
1343 "aof_enabled:%d\r\n"
1344 "changes_since_last_save:%lld\r\n"
1345 "bgsave_in_progress:%d\r\n"
1346 "last_save_time:%ld\r\n"
1347 "bgrewriteaof_in_progress:%d\r\n",
1351 server
.bgsavechildpid
!= -1,
1353 server
.bgrewritechildpid
!= -1);
1355 if (server
.appendonly
) {
1356 info
= sdscatprintf(info
,
1357 "aof_current_size:%lld\r\n"
1358 "aof_base_size:%lld\r\n"
1359 "aof_pending_rewrite:%d\r\n",
1360 (long long) server
.appendonly_current_size
,
1361 (long long) server
.auto_aofrewrite_base_size
,
1362 server
.aofrewrite_scheduled
);
1365 if (server
.loading
) {
1367 time_t eta
, elapsed
;
1368 off_t remaining_bytes
= server
.loading_total_bytes
-
1369 server
.loading_loaded_bytes
;
1371 perc
= ((double)server
.loading_loaded_bytes
/
1372 server
.loading_total_bytes
) * 100;
1374 elapsed
= time(NULL
)-server
.loading_start_time
;
1376 eta
= 1; /* A fake 1 second figure if we don't have
1379 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1382 info
= sdscatprintf(info
,
1383 "loading_start_time:%ld\r\n"
1384 "loading_total_bytes:%llu\r\n"
1385 "loading_loaded_bytes:%llu\r\n"
1386 "loading_loaded_perc:%.2f\r\n"
1387 "loading_eta_seconds:%ld\r\n"
1388 ,(unsigned long) server
.loading_start_time
,
1389 (unsigned long long) server
.loading_total_bytes
,
1390 (unsigned long long) server
.loading_loaded_bytes
,
1398 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1399 if (sections
++) info
= sdscat(info
,"\r\n");
1400 info
= sdscatprintf(info
,
1402 "total_connections_received:%lld\r\n"
1403 "total_commands_processed:%lld\r\n"
1404 "expired_keys:%lld\r\n"
1405 "evicted_keys:%lld\r\n"
1406 "keyspace_hits:%lld\r\n"
1407 "keyspace_misses:%lld\r\n"
1408 "pubsub_channels:%ld\r\n"
1409 "pubsub_patterns:%u\r\n"
1410 "latest_fork_usec:%lld\r\n",
1411 server
.stat_numconnections
,
1412 server
.stat_numcommands
,
1413 server
.stat_expiredkeys
,
1414 server
.stat_evictedkeys
,
1415 server
.stat_keyspace_hits
,
1416 server
.stat_keyspace_misses
,
1417 dictSize(server
.pubsub_channels
),
1418 listLength(server
.pubsub_patterns
),
1419 server
.stat_fork_time
);
1423 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1424 if (sections
++) info
= sdscat(info
,"\r\n");
1425 info
= sdscatprintf(info
,
1428 server
.masterhost
== NULL
? "master" : "slave");
1429 if (server
.masterhost
) {
1430 info
= sdscatprintf(info
,
1431 "master_host:%s\r\n"
1432 "master_port:%d\r\n"
1433 "master_link_status:%s\r\n"
1434 "master_last_io_seconds_ago:%d\r\n"
1435 "master_sync_in_progress:%d\r\n"
1438 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1441 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1442 server
.replstate
== REDIS_REPL_TRANSFER
1445 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1446 info
= sdscatprintf(info
,
1447 "master_sync_left_bytes:%ld\r\n"
1448 "master_sync_last_io_seconds_ago:%d\r\n"
1449 ,(long)server
.repl_transfer_left
,
1450 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1454 if (server
.replstate
!= REDIS_REPL_CONNECTED
) {
1455 info
= sdscatprintf(info
,
1456 "master_link_down_since_seconds:%ld\r\n",
1457 (long)time(NULL
)-server
.repl_down_since
);
1460 info
= sdscatprintf(info
,
1461 "connected_slaves:%d\r\n",
1462 listLength(server
.slaves
));
1466 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1467 if (sections
++) info
= sdscat(info
,"\r\n");
1468 info
= sdscatprintf(info
,
1470 "used_cpu_sys:%.2f\r\n"
1471 "used_cpu_user:%.2f\r\n"
1472 "used_cpu_sys_children:%.2f\r\n"
1473 "used_cpu_user_children:%.2f\r\n",
1474 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1475 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1476 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1477 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000);
1481 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1482 if (sections
++) info
= sdscat(info
,"\r\n");
1483 info
= sdscatprintf(info
, "# Commandstats\r\n");
1484 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1485 for (j
= 0; j
< numcommands
; j
++) {
1486 struct redisCommand
*c
= redisCommandTable
+j
;
1488 if (!c
->calls
) continue;
1489 info
= sdscatprintf(info
,
1490 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1491 c
->name
, c
->calls
, c
->microseconds
,
1492 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1497 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1498 if (sections
++) info
= sdscat(info
,"\r\n");
1499 info
= sdscatprintf(info
,
1501 "cluster_enabled:%d\r\n",
1502 server
.cluster_enabled
);
1506 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1507 if (sections
++) info
= sdscat(info
,"\r\n");
1508 info
= sdscatprintf(info
, "# Keyspace\r\n");
1509 for (j
= 0; j
< server
.dbnum
; j
++) {
1510 long long keys
, vkeys
;
1512 keys
= dictSize(server
.db
[j
].dict
);
1513 vkeys
= dictSize(server
.db
[j
].expires
);
1514 if (keys
|| vkeys
) {
1515 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1523 void infoCommand(redisClient
*c
) {
1524 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1527 addReply(c
,shared
.syntaxerr
);
1530 sds info
= genRedisInfoString(section
);
1531 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1532 (unsigned long)sdslen(info
)));
1533 addReplySds(c
,info
);
1534 addReply(c
,shared
.crlf
);
1537 void monitorCommand(redisClient
*c
) {
1538 /* ignore MONITOR if aleady slave or in monitor mode */
1539 if (c
->flags
& REDIS_SLAVE
) return;
1541 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1543 listAddNodeTail(server
.monitors
,c
);
1544 addReply(c
,shared
.ok
);
1547 /* ============================ Maxmemory directive ======================== */
1549 /* This function gets called when 'maxmemory' is set on the config file to limit
1550 * the max memory used by the server, and we are out of memory.
1551 * This function will try to, in order:
1553 * - Free objects from the free list
1554 * - Try to remove keys with an EXPIRE set
1556 * It is not possible to free enough memory to reach used-memory < maxmemory
1557 * the server will start refusing commands that will enlarge even more the
1560 void freeMemoryIfNeeded(void) {
1561 /* Remove keys accordingly to the active policy as long as we are
1562 * over the memory limit. */
1563 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1565 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1566 int j
, k
, freed
= 0;
1568 for (j
= 0; j
< server
.dbnum
; j
++) {
1569 long bestval
= 0; /* just to prevent warning */
1571 struct dictEntry
*de
;
1572 redisDb
*db
= server
.db
+j
;
1575 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1576 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1578 dict
= server
.db
[j
].dict
;
1580 dict
= server
.db
[j
].expires
;
1582 if (dictSize(dict
) == 0) continue;
1584 /* volatile-random and allkeys-random policy */
1585 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1586 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1588 de
= dictGetRandomKey(dict
);
1589 bestkey
= dictGetEntryKey(de
);
1592 /* volatile-lru and allkeys-lru policy */
1593 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1594 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1596 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1601 de
= dictGetRandomKey(dict
);
1602 thiskey
= dictGetEntryKey(de
);
1603 /* When policy is volatile-lru we need an additonal lookup
1604 * to locate the real key, as dict is set to db->expires. */
1605 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1606 de
= dictFind(db
->dict
, thiskey
);
1607 o
= dictGetEntryVal(de
);
1608 thisval
= estimateObjectIdleTime(o
);
1610 /* Higher idle time is better candidate for deletion */
1611 if (bestkey
== NULL
|| thisval
> bestval
) {
1619 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1620 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1624 de
= dictGetRandomKey(dict
);
1625 thiskey
= dictGetEntryKey(de
);
1626 thisval
= (long) dictGetEntryVal(de
);
1628 /* Expire sooner (minor expire unix timestamp) is better
1629 * candidate for deletion */
1630 if (bestkey
== NULL
|| thisval
< bestval
) {
1637 /* Finally remove the selected key. */
1639 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1640 propagateExpire(db
,keyobj
);
1641 dbDelete(db
,keyobj
);
1642 server
.stat_evictedkeys
++;
1643 decrRefCount(keyobj
);
1647 if (!freed
) return; /* nothing to free... */
1651 /* =================================== Main! ================================ */
1654 int linuxOvercommitMemoryValue(void) {
1655 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1659 if (fgets(buf
,64,fp
) == NULL
) {
1668 void linuxOvercommitMemoryWarning(void) {
1669 if (linuxOvercommitMemoryValue() == 0) {
1670 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.");
1673 #endif /* __linux__ */
1675 void createPidFile(void) {
1676 /* Try to write the pid file in a best-effort way. */
1677 FILE *fp
= fopen(server
.pidfile
,"w");
1679 fprintf(fp
,"%d\n",(int)getpid());
1684 void daemonize(void) {
1687 if (fork() != 0) exit(0); /* parent exits */
1688 setsid(); /* create a new session */
1690 /* Every output goes to /dev/null. If Redis is daemonized but
1691 * the 'logfile' is set to 'stdout' in the configuration file
1692 * it will not log at all. */
1693 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1694 dup2(fd
, STDIN_FILENO
);
1695 dup2(fd
, STDOUT_FILENO
);
1696 dup2(fd
, STDERR_FILENO
);
1697 if (fd
> STDERR_FILENO
) close(fd
);
1702 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1703 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1708 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1709 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1713 void redisAsciiArt(void) {
1714 #include "asciilogo.h"
1715 char *buf
= zmalloc(1024*16);
1717 snprintf(buf
,1024*16,ascii_logo
,
1720 strtol(redisGitDirty(),NULL
,10) > 0,
1721 (sizeof(long) == 8) ? "64" : "32",
1722 server
.cluster_enabled
? "cluster" : "stand alone",
1726 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1730 int main(int argc
, char **argv
) {
1735 if (strcmp(argv
[1], "-v") == 0 ||
1736 strcmp(argv
[1], "--version") == 0) version();
1737 if (strcmp(argv
[1], "--help") == 0) usage();
1738 resetServerSaveParams();
1739 loadServerConfig(argv
[1]);
1740 } else if ((argc
> 2)) {
1743 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'");
1745 if (server
.daemonize
) daemonize();
1747 if (server
.daemonize
) createPidFile();
1749 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1751 linuxOvercommitMemoryWarning();
1754 if (server
.appendonly
) {
1755 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1756 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1758 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1759 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",(float)(ustime()-start
)/1000000);
1761 if (server
.ipfd
> 0)
1762 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1763 if (server
.sofd
> 0)
1764 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1765 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1767 aeDeleteEventLoop(server
.el
);
1771 #ifdef HAVE_BACKTRACE
1772 static void *getMcontextEip(ucontext_t
*uc
) {
1773 #if defined(__FreeBSD__)
1774 return (void*) uc
->uc_mcontext
.mc_eip
;
1775 #elif defined(__dietlibc__)
1776 return (void*) uc
->uc_mcontext
.eip
;
1777 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1779 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1781 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1783 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1784 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1785 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1787 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1789 #elif defined(__i386__)
1790 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1791 #elif defined(__X86_64__) || defined(__x86_64__)
1792 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1793 #elif defined(__ia64__) /* Linux IA64 */
1794 return (void*) uc
->uc_mcontext
.sc_ip
;
1800 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1802 char **messages
= NULL
;
1803 int i
, trace_size
= 0;
1804 ucontext_t
*uc
= (ucontext_t
*) secret
;
1806 struct sigaction act
;
1807 REDIS_NOTUSED(info
);
1809 redisLog(REDIS_WARNING
,
1810 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1811 infostring
= genRedisInfoString("all");
1812 redisLogRaw(REDIS_WARNING
, infostring
);
1813 /* It's not safe to sdsfree() the returned string under memory
1814 * corruption conditions. Let it leak as we are going to abort */
1816 trace_size
= backtrace(trace
, 100);
1817 /* overwrite sigaction with caller's address */
1818 if (getMcontextEip(uc
) != NULL
) {
1819 trace
[1] = getMcontextEip(uc
);
1821 messages
= backtrace_symbols(trace
, trace_size
);
1823 for (i
=1; i
<trace_size
; ++i
)
1824 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1826 /* free(messages); Don't call free() with possibly corrupted memory. */
1827 if (server
.daemonize
) unlink(server
.pidfile
);
1829 /* Make sure we exit with the right signal at the end. So for instance
1830 * the core will be dumped if enabled. */
1831 sigemptyset (&act
.sa_mask
);
1832 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1833 * is used. Otherwise, sa_handler is used */
1834 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1835 act
.sa_handler
= SIG_DFL
;
1836 sigaction (sig
, &act
, NULL
);
1839 #endif /* HAVE_BACKTRACE */
1841 static void sigtermHandler(int sig
) {
1844 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1845 server
.shutdown_asap
= 1;
1848 void setupSignalHandlers(void) {
1849 struct sigaction act
;
1851 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1852 * Otherwise, sa_handler is used. */
1853 sigemptyset(&act
.sa_mask
);
1854 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1855 act
.sa_handler
= sigtermHandler
;
1856 sigaction(SIGTERM
, &act
, NULL
);
1858 #ifdef HAVE_BACKTRACE
1859 sigemptyset(&act
.sa_mask
);
1860 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1861 act
.sa_sigaction
= sigsegvHandler
;
1862 sigaction(SIGSEGV
, &act
, NULL
);
1863 sigaction(SIGBUS
, &act
, NULL
);
1864 sigaction(SIGFPE
, &act
, NULL
);
1865 sigaction(SIGILL
, &act
, NULL
);