2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
35 #endif /* HAVE_BACKTRACE */
44 #include <arpa/inet.h>
48 #include <sys/resource.h>
54 #include <sys/resource.h>
56 /* Our shared "common" objects */
58 struct sharedObjectsStruct shared
;
60 /* Global vars that are actally used as constants. The following double
61 * values are used for double on-disk serialization, and are initialized
62 * at runtime to avoid strange compiler optimizations. */
64 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
66 /*================================= Globals ================================= */
69 struct redisServer server
; /* server global state */
70 struct redisCommand
*commandTable
;
71 struct redisCommand redisCommandTable
[] = {
72 {"get",getCommand
,2,0,NULL
,1,1,1,0,0},
73 {"set",setCommand
,3,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,1,1,1,0,0},
74 {"setnx",setnxCommand
,3,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,1,1,1,0,0},
75 {"setex",setexCommand
,4,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,2,2,1,0,0},
76 {"append",appendCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
77 {"strlen",strlenCommand
,2,0,NULL
,1,1,1,0,0},
78 {"del",delCommand
,-2,0,noPreloadGetKeys
,1,-1,1,0,0},
79 {"exists",existsCommand
,2,0,NULL
,1,1,1,0,0},
80 {"setbit",setbitCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
81 {"getbit",getbitCommand
,3,0,NULL
,1,1,1,0,0},
82 {"setrange",setrangeCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
83 {"getrange",getrangeCommand
,4,0,NULL
,1,1,1,0,0},
84 {"substr",getrangeCommand
,4,0,NULL
,1,1,1,0,0},
85 {"incr",incrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
86 {"decr",decrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
87 {"mget",mgetCommand
,-2,0,NULL
,1,-1,1,0,0},
88 {"rpush",rpushCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
89 {"lpush",lpushCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
90 {"rpushx",rpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
91 {"lpushx",lpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
92 {"linsert",linsertCommand
,5,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
93 {"rpop",rpopCommand
,2,0,NULL
,1,1,1,0,0},
94 {"lpop",lpopCommand
,2,0,NULL
,1,1,1,0,0},
95 {"brpop",brpopCommand
,-3,0,NULL
,1,1,1,0,0},
96 {"brpoplpush",brpoplpushCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,2,1,0,0},
97 {"blpop",blpopCommand
,-3,0,NULL
,1,-2,1,0,0},
98 {"llen",llenCommand
,2,0,NULL
,1,1,1,0,0},
99 {"lindex",lindexCommand
,3,0,NULL
,1,1,1,0,0},
100 {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
101 {"lrange",lrangeCommand
,4,0,NULL
,1,1,1,0,0},
102 {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1,0,0},
103 {"lrem",lremCommand
,4,0,NULL
,1,1,1,0,0},
104 {"rpoplpush",rpoplpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1,0,0},
105 {"sadd",saddCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
106 {"srem",sremCommand
,-3,0,NULL
,1,1,1,0,0},
107 {"smove",smoveCommand
,4,0,NULL
,1,2,1,0,0},
108 {"sismember",sismemberCommand
,3,0,NULL
,1,1,1,0,0},
109 {"scard",scardCommand
,2,0,NULL
,1,1,1,0,0},
110 {"spop",spopCommand
,2,0,NULL
,1,1,1,0,0},
111 {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1,0,0},
112 {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
113 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
114 {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
115 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
116 {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0},
117 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0},
118 {"smembers",sinterCommand
,2,0,NULL
,1,1,1,0,0},
119 {"zadd",zaddCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
120 {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
121 {"zrem",zremCommand
,-3,0,NULL
,1,1,1,0,0},
122 {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1,0,0},
123 {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1,0,0},
124 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
125 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0},
126 {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1,0,0},
127 {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1,0,0},
128 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1,0,0},
129 {"zcount",zcountCommand
,4,0,NULL
,1,1,1,0,0},
130 {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1,0,0},
131 {"zcard",zcardCommand
,2,0,NULL
,1,1,1,0,0},
132 {"zscore",zscoreCommand
,3,0,NULL
,1,1,1,0,0},
133 {"zrank",zrankCommand
,3,0,NULL
,1,1,1,0,0},
134 {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1,0,0},
135 {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
136 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
137 {"hget",hgetCommand
,3,0,NULL
,1,1,1,0,0},
138 {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
139 {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1,0,0},
140 {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
141 {"hdel",hdelCommand
,-3,0,NULL
,1,1,1,0,0},
142 {"hlen",hlenCommand
,2,0,NULL
,1,1,1,0,0},
143 {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1,0,0},
144 {"hvals",hvalsCommand
,2,0,NULL
,1,1,1,0,0},
145 {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1,0,0},
146 {"hexists",hexistsCommand
,3,0,NULL
,1,1,1,0,0},
147 {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
148 {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
149 {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
150 {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2,0,0},
151 {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2,0,0},
152 {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0,0,0},
153 {"select",selectCommand
,2,0,NULL
,0,0,0,0,0},
154 {"move",moveCommand
,3,0,NULL
,1,1,1,0,0},
155 {"rename",renameCommand
,3,0,renameGetKeys
,1,2,1,0,0},
156 {"renamenx",renamenxCommand
,3,0,renameGetKeys
,1,2,1,0,0},
157 {"expire",expireCommand
,3,0,NULL
,1,1,1,0,0},
158 {"expireat",expireatCommand
,3,0,NULL
,1,1,1,0,0},
159 {"keys",keysCommand
,2,0,NULL
,0,0,0,0,0},
160 {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0,0,0},
161 {"auth",authCommand
,2,0,NULL
,0,0,0,0,0},
162 {"ping",pingCommand
,1,0,NULL
,0,0,0,0,0},
163 {"echo",echoCommand
,2,0,NULL
,0,0,0,0,0},
164 {"save",saveCommand
,1,0,NULL
,0,0,0,0,0},
165 {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0,0,0},
166 {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0,0,0},
167 {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0,0,0},
168 {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0,0,0},
169 {"type",typeCommand
,2,0,NULL
,1,1,1,0,0},
170 {"multi",multiCommand
,1,0,NULL
,0,0,0,0,0},
171 {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,NULL
,0,0,0,0,0},
172 {"discard",discardCommand
,1,0,NULL
,0,0,0,0,0},
173 {"sync",syncCommand
,1,0,NULL
,0,0,0,0,0},
174 {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0,0,0},
175 {"flushall",flushallCommand
,1,0,NULL
,0,0,0,0,0},
176 {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0},
177 {"info",infoCommand
,-1,0,NULL
,0,0,0,0,0},
178 {"monitor",monitorCommand
,1,0,NULL
,0,0,0,0,0},
179 {"ttl",ttlCommand
,2,0,NULL
,1,1,1,0,0},
180 {"persist",persistCommand
,2,0,NULL
,1,1,1,0,0},
181 {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0,0,0},
182 {"debug",debugCommand
,-2,0,NULL
,0,0,0,0,0},
183 {"config",configCommand
,-2,0,NULL
,0,0,0,0,0},
184 {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0,0,0},
185 {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0,0,0},
186 {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0,0,0},
187 {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0,0,0},
188 {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0,0,0},
189 {"watch",watchCommand
,-2,0,noPreloadGetKeys
,1,-1,1,0,0},
190 {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0,0,0},
191 {"cluster",clusterCommand
,-2,0,NULL
,0,0,0,0,0},
192 {"restore",restoreCommand
,4,0,NULL
,0,0,0,0,0},
193 {"migrate",migrateCommand
,6,0,NULL
,0,0,0,0,0},
194 {"dump",dumpCommand
,2,0,NULL
,0,0,0,0,0},
195 {"object",objectCommand
,-2,0,NULL
,0,0,0,0,0},
196 {"client",clientCommand
,-2,0,NULL
,0,0,0,0,0}
199 /*============================ Utility functions ============================ */
201 /* Low level logging. To use only for very big messages, otherwise
202 * redisLog() is to prefer. */
203 void redisLogRaw(int level
, const char *msg
) {
204 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
205 const char *c
= ".-*#";
206 time_t now
= time(NULL
);
209 int rawmode
= (level
& REDIS_LOG_RAW
);
211 level
&= 0xff; /* clear flags */
212 if (level
< server
.verbosity
) return;
214 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
218 fprintf(fp
,"%s",msg
);
220 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
221 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
225 if (server
.logfile
) fclose(fp
);
227 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
230 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
231 * is used across the code. The raw version is only used in order to dump
232 * the INFO output on crash. */
233 void redisLog(int level
, const char *fmt
, ...) {
235 char msg
[REDIS_MAX_LOGMSG_LEN
];
237 if ((level
&0xff) < server
.verbosity
) return;
240 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
243 redisLogRaw(level
,msg
);
246 /* Redis generally does not try to recover from out of memory conditions
247 * when allocating objects or strings, it is not clear if it will be possible
248 * to report this condition to the client since the networking layer itself
249 * is based on heap allocation for send buffers, so we simply abort.
250 * At least the code will be simpler to read... */
251 void oom(const char *msg
) {
252 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
257 /* Return the UNIX time in microseconds */
258 long long ustime(void) {
262 gettimeofday(&tv
, NULL
);
263 ust
= ((long long)tv
.tv_sec
)*1000000;
268 /*====================== Hash table type implementation ==================== */
270 /* This is an hash table type that uses the SDS dynamic strings libary as
271 * keys and radis objects as values (objects can hold SDS strings,
274 void dictVanillaFree(void *privdata
, void *val
)
276 DICT_NOTUSED(privdata
);
280 void dictListDestructor(void *privdata
, void *val
)
282 DICT_NOTUSED(privdata
);
283 listRelease((list
*)val
);
286 int dictSdsKeyCompare(void *privdata
, const void *key1
,
290 DICT_NOTUSED(privdata
);
292 l1
= sdslen((sds
)key1
);
293 l2
= sdslen((sds
)key2
);
294 if (l1
!= l2
) return 0;
295 return memcmp(key1
, key2
, l1
) == 0;
298 /* A case insensitive version used for the command lookup table. */
299 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
302 DICT_NOTUSED(privdata
);
304 return strcasecmp(key1
, key2
) == 0;
307 void dictRedisObjectDestructor(void *privdata
, void *val
)
309 DICT_NOTUSED(privdata
);
311 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
315 void dictSdsDestructor(void *privdata
, void *val
)
317 DICT_NOTUSED(privdata
);
322 int dictObjKeyCompare(void *privdata
, const void *key1
,
325 const robj
*o1
= key1
, *o2
= key2
;
326 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
329 unsigned int dictObjHash(const void *key
) {
331 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
334 unsigned int dictSdsHash(const void *key
) {
335 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
338 unsigned int dictSdsCaseHash(const void *key
) {
339 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
342 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
345 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
348 if (o1
->encoding
== REDIS_ENCODING_INT
&&
349 o2
->encoding
== REDIS_ENCODING_INT
)
350 return o1
->ptr
== o2
->ptr
;
352 o1
= getDecodedObject(o1
);
353 o2
= getDecodedObject(o2
);
354 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
360 unsigned int dictEncObjHash(const void *key
) {
361 robj
*o
= (robj
*) key
;
363 if (o
->encoding
== REDIS_ENCODING_RAW
) {
364 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
366 if (o
->encoding
== REDIS_ENCODING_INT
) {
370 len
= ll2string(buf
,32,(long)o
->ptr
);
371 return dictGenHashFunction((unsigned char*)buf
, len
);
375 o
= getDecodedObject(o
);
376 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
383 /* Sets type and diskstore negative caching hash table */
384 dictType setDictType
= {
385 dictEncObjHash
, /* hash function */
388 dictEncObjKeyCompare
, /* key compare */
389 dictRedisObjectDestructor
, /* key destructor */
390 NULL
/* val destructor */
393 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
394 dictType zsetDictType
= {
395 dictEncObjHash
, /* hash function */
398 dictEncObjKeyCompare
, /* key compare */
399 dictRedisObjectDestructor
, /* key destructor */
400 NULL
/* val destructor */
403 /* Db->dict, keys are sds strings, vals are Redis objects. */
404 dictType dbDictType
= {
405 dictSdsHash
, /* hash function */
408 dictSdsKeyCompare
, /* key compare */
409 dictSdsDestructor
, /* key destructor */
410 dictRedisObjectDestructor
/* val destructor */
414 dictType keyptrDictType
= {
415 dictSdsHash
, /* hash function */
418 dictSdsKeyCompare
, /* key compare */
419 NULL
, /* key destructor */
420 NULL
/* val destructor */
423 /* Command table. sds string -> command struct pointer. */
424 dictType commandTableDictType
= {
425 dictSdsCaseHash
, /* hash function */
428 dictSdsKeyCaseCompare
, /* key compare */
429 dictSdsDestructor
, /* key destructor */
430 NULL
/* val destructor */
433 /* Hash type hash table (note that small hashes are represented with zimpaps) */
434 dictType hashDictType
= {
435 dictEncObjHash
, /* hash function */
438 dictEncObjKeyCompare
, /* key compare */
439 dictRedisObjectDestructor
, /* key destructor */
440 dictRedisObjectDestructor
/* val destructor */
443 /* Keylist hash table type has unencoded redis objects as keys and
444 * lists as values. It's used for blocking operations (BLPOP) and to
445 * map swapped keys to a list of clients waiting for this keys to be loaded. */
446 dictType keylistDictType
= {
447 dictObjHash
, /* hash function */
450 dictObjKeyCompare
, /* key compare */
451 dictRedisObjectDestructor
, /* key destructor */
452 dictListDestructor
/* val destructor */
455 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
456 * clusterNode structures. */
457 dictType clusterNodesDictType
= {
458 dictSdsHash
, /* hash function */
461 dictSdsKeyCompare
, /* key compare */
462 dictSdsDestructor
, /* key destructor */
463 NULL
/* val destructor */
466 int htNeedsResize(dict
*dict
) {
467 long long size
, used
;
469 size
= dictSlots(dict
);
470 used
= dictSize(dict
);
471 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
472 (used
*100/size
< REDIS_HT_MINFILL
));
475 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
476 * we resize the hash table to save memory */
477 void tryResizeHashTables(void) {
480 for (j
= 0; j
< server
.dbnum
; j
++) {
481 if (htNeedsResize(server
.db
[j
].dict
))
482 dictResize(server
.db
[j
].dict
);
483 if (htNeedsResize(server
.db
[j
].expires
))
484 dictResize(server
.db
[j
].expires
);
488 /* Our hash table implementation performs rehashing incrementally while
489 * we write/read from the hash table. Still if the server is idle, the hash
490 * table will use two tables for a long time. So we try to use 1 millisecond
491 * of CPU time at every serverCron() loop in order to rehash some key. */
492 void incrementallyRehash(void) {
495 for (j
= 0; j
< server
.dbnum
; j
++) {
496 if (dictIsRehashing(server
.db
[j
].dict
)) {
497 dictRehashMilliseconds(server
.db
[j
].dict
,1);
498 break; /* already used our millisecond for this loop... */
503 /* This function is called once a background process of some kind terminates,
504 * as we want to avoid resizing the hash tables when there is a child in order
505 * to play well with copy-on-write (otherwise when a resize happens lots of
506 * memory pages are copied). The goal of this function is to update the ability
507 * for dict.c to resize the hash tables accordingly to the fact we have o not
509 void updateDictResizePolicy(void) {
510 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
516 /* ======================= Cron: called every 100 ms ======================== */
518 /* Try to expire a few timed out keys. The algorithm used is adaptive and
519 * will use few CPU cycles if there are few expiring keys, otherwise
520 * it will get more aggressive to avoid that too much memory is used by
521 * keys that can be removed from the keyspace. */
522 void activeExpireCycle(void) {
525 for (j
= 0; j
< server
.dbnum
; j
++) {
527 redisDb
*db
= server
.db
+j
;
529 /* Continue to expire if at the end of the cycle more than 25%
530 * of the keys were expired. */
532 long num
= dictSize(db
->expires
);
533 time_t now
= time(NULL
);
536 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
537 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
542 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
543 t
= (time_t) dictGetEntryVal(de
);
545 sds key
= dictGetEntryKey(de
);
546 robj
*keyobj
= createStringObject(key
,sdslen(key
));
548 propagateExpire(db
,keyobj
);
550 decrRefCount(keyobj
);
552 server
.stat_expiredkeys
++;
555 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
559 void updateLRUClock(void) {
560 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
564 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
565 int j
, loops
= server
.cronloops
;
566 REDIS_NOTUSED(eventLoop
);
568 REDIS_NOTUSED(clientData
);
570 /* We take a cached value of the unix time in the global state because
571 * with virtual memory and aging there is to store the current time
572 * in objects at every object access, and accuracy is not needed.
573 * To access a global var is faster than calling time(NULL) */
574 server
.unixtime
= time(NULL
);
575 /* We have just 22 bits per object for LRU information.
576 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
577 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
579 * Note that even if this will wrap after 1.5 years it's not a problem,
580 * everything will still work but just some object will appear younger
581 * to Redis. But for this to happen a given object should never be touched
584 * Note that you can change the resolution altering the
585 * REDIS_LRU_CLOCK_RESOLUTION define.
589 /* Record the max memory used since the server was started. */
590 if (zmalloc_used_memory() > server
.stat_peak_memory
)
591 server
.stat_peak_memory
= zmalloc_used_memory();
593 /* We received a SIGTERM, shutting down here in a safe way, as it is
594 * not ok doing so inside the signal handler. */
595 if (server
.shutdown_asap
) {
596 if (prepareForShutdown() == REDIS_OK
) exit(0);
597 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
600 /* Show some info about non-empty databases */
601 for (j
= 0; j
< server
.dbnum
; j
++) {
602 long long size
, used
, vkeys
;
604 size
= dictSlots(server
.db
[j
].dict
);
605 used
= dictSize(server
.db
[j
].dict
);
606 vkeys
= dictSize(server
.db
[j
].expires
);
607 if (!(loops
% 50) && (used
|| vkeys
)) {
608 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
609 /* dictPrintStats(server.dict); */
613 /* We don't want to resize the hash tables while a bacground saving
614 * is in progress: the saving child is created using fork() that is
615 * implemented with a copy-on-write semantic in most modern systems, so
616 * if we resize the HT while there is the saving child at work actually
617 * a lot of memory movements in the parent will cause a lot of pages
619 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
620 if (!(loops
% 10)) tryResizeHashTables();
621 if (server
.activerehashing
) incrementallyRehash();
624 /* Show information about connected clients */
626 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
627 listLength(server
.clients
)-listLength(server
.slaves
),
628 listLength(server
.slaves
),
629 zmalloc_used_memory());
632 /* Close connections of timedout clients */
633 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
634 closeTimedoutClients();
636 /* Start a scheduled AOF rewrite if this was requested by the user while
637 * a BGSAVE was in progress. */
638 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1 &&
639 server
.aofrewrite_scheduled
)
641 rewriteAppendOnlyFileBackground();
644 /* Check if a background saving or AOF rewrite in progress terminated. */
645 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
649 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
650 int exitcode
= WEXITSTATUS(statloc
);
653 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
655 if (pid
== server
.bgsavechildpid
) {
656 backgroundSaveDoneHandler(exitcode
,bysignal
);
658 backgroundRewriteDoneHandler(exitcode
,bysignal
);
660 updateDictResizePolicy();
662 } else if (server
.bgsavethread
!= (pthread_t
) -1) {
663 if (server
.bgsavethread
!= (pthread_t
) -1) {
666 pthread_mutex_lock(&server
.bgsavethread_mutex
);
667 state
= server
.bgsavethread_state
;
668 pthread_mutex_unlock(&server
.bgsavethread_mutex
);
670 if (state
== REDIS_BGSAVE_THREAD_DONE_OK
||
671 state
== REDIS_BGSAVE_THREAD_DONE_ERR
)
673 backgroundSaveDoneHandler(
674 (state
== REDIS_BGSAVE_THREAD_DONE_OK
) ? 0 : 1, 0);
677 } else if (!server
.ds_enabled
) {
678 time_t now
= time(NULL
);
680 /* If there is not a background saving/rewrite in progress check if
681 * we have to save/rewrite now */
682 for (j
= 0; j
< server
.saveparamslen
; j
++) {
683 struct saveparam
*sp
= server
.saveparams
+j
;
685 if (server
.dirty
>= sp
->changes
&&
686 now
-server
.lastsave
> sp
->seconds
) {
687 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
688 sp
->changes
, sp
->seconds
);
689 rdbSaveBackground(server
.dbfilename
);
694 /* Trigger an AOF rewrite if needed */
695 printf("%d\n", server
.auto_aofrewrite_perc
);
696 if (server
.auto_aofrewrite_perc
&&
697 server
.appendonly_current_size
> server
.auto_aofrewrite_min_size
)
699 int base
= server
.auto_aofrewrite_base_size
?
700 server
.auto_aofrewrite_base_size
: 1;
701 int growth
= (server
.appendonly_current_size
*100/base
);
702 if (growth
>= server
.auto_aofrewrite_perc
) {
703 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %d growth",growth
);
704 rewriteAppendOnlyFileBackground();
709 /* Expire a few keys per cycle, only if this is a master.
710 * On slaves we wait for DEL operations synthesized by the master
711 * in order to guarantee a strict consistency. */
712 if (server
.masterhost
== NULL
) activeExpireCycle();
714 /* Remove a few cached objects from memory if we are over the
715 * configured memory limit */
716 if (server
.ds_enabled
) cacheCron();
718 /* Replication cron function -- used to reconnect to master and
719 * to detect transfer failures. */
720 if (!(loops
% 10)) replicationCron();
722 /* Run other sub-systems specific cron jobs */
723 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
729 /* This function gets called every time Redis is entering the
730 * main loop of the event driven library, that is, before to sleep
731 * for ready file descriptors. */
732 void beforeSleep(struct aeEventLoop
*eventLoop
) {
733 REDIS_NOTUSED(eventLoop
);
737 /* Awake clients that got all the on disk keys they requested */
738 if (server
.ds_enabled
&& listLength(server
.io_ready_clients
)) {
741 listRewind(server
.io_ready_clients
,&li
);
742 while((ln
= listNext(&li
))) {
744 struct redisCommand
*cmd
;
746 /* Resume the client. */
747 listDelNode(server
.io_ready_clients
,ln
);
748 c
->flags
&= (~REDIS_IO_WAIT
);
749 server
.cache_blocked_clients
--;
750 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
751 readQueryFromClient
, c
);
752 cmd
= lookupCommand(c
->argv
[0]->ptr
);
753 redisAssert(cmd
!= NULL
);
756 /* There may be more data to process in the input buffer. */
757 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
758 processInputBuffer(c
);
762 /* Try to process pending commands for clients that were just unblocked. */
763 while (listLength(server
.unblocked_clients
)) {
764 ln
= listFirst(server
.unblocked_clients
);
765 redisAssert(ln
!= NULL
);
767 listDelNode(server
.unblocked_clients
,ln
);
768 c
->flags
&= ~REDIS_UNBLOCKED
;
770 /* Process remaining data in the input buffer. */
771 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
772 processInputBuffer(c
);
775 /* Write the AOF buffer on disk */
776 flushAppendOnlyFile();
779 /* =========================== Server initialization ======================== */
781 void createSharedObjects(void) {
784 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
785 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
786 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
787 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
788 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
789 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
790 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
791 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
792 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
793 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
794 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
795 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
796 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
797 "-ERR Operation against a key holding the wrong kind of value\r\n"));
798 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
799 "-ERR no such key\r\n"));
800 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
801 "-ERR syntax error\r\n"));
802 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
803 "-ERR source and destination objects are the same\r\n"));
804 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
805 "-ERR index out of range\r\n"));
806 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
807 "-LOADING Redis is loading the dataset in memory\r\n"));
808 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
809 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
810 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
811 shared
.select0
= createStringObject("select 0\r\n",10);
812 shared
.select1
= createStringObject("select 1\r\n",10);
813 shared
.select2
= createStringObject("select 2\r\n",10);
814 shared
.select3
= createStringObject("select 3\r\n",10);
815 shared
.select4
= createStringObject("select 4\r\n",10);
816 shared
.select5
= createStringObject("select 5\r\n",10);
817 shared
.select6
= createStringObject("select 6\r\n",10);
818 shared
.select7
= createStringObject("select 7\r\n",10);
819 shared
.select8
= createStringObject("select 8\r\n",10);
820 shared
.select9
= createStringObject("select 9\r\n",10);
821 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
822 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
823 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
824 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
825 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
826 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
827 shared
.mbulk3
= createStringObject("*3\r\n",4);
828 shared
.mbulk4
= createStringObject("*4\r\n",4);
829 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
830 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
831 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
835 void initServerConfig() {
836 server
.port
= REDIS_SERVERPORT
;
837 server
.bindaddr
= NULL
;
838 server
.unixsocket
= NULL
;
841 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
842 server
.verbosity
= REDIS_VERBOSE
;
843 server
.maxidletime
= REDIS_MAXIDLETIME
;
844 server
.saveparams
= NULL
;
846 server
.logfile
= NULL
; /* NULL = log on standard output */
847 server
.syslog_enabled
= 0;
848 server
.syslog_ident
= zstrdup("redis");
849 server
.syslog_facility
= LOG_LOCAL0
;
850 server
.daemonize
= 0;
851 server
.appendonly
= 0;
852 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
853 server
.no_appendfsync_on_rewrite
= 0;
854 server
.auto_aofrewrite_perc
= REDIS_AUTO_AOFREWRITE_PERC
;
855 server
.auto_aofrewrite_min_size
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
;
856 server
.auto_aofrewrite_base_size
= 0;
857 server
.aofrewrite_scheduled
= 0;
858 server
.lastfsync
= time(NULL
);
859 server
.appendfd
= -1;
860 server
.appendseldb
= -1; /* Make sure the first time will not match */
861 server
.pidfile
= zstrdup("/var/run/redis.pid");
862 server
.dbfilename
= zstrdup("dump.rdb");
863 server
.appendfilename
= zstrdup("appendonly.aof");
864 server
.requirepass
= NULL
;
865 server
.rdbcompression
= 1;
866 server
.activerehashing
= 1;
867 server
.maxclients
= 0;
868 server
.bpop_blocked_clients
= 0;
869 server
.maxmemory
= 0;
870 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
871 server
.maxmemory_samples
= 3;
872 server
.ds_enabled
= 0;
873 server
.ds_path
= sdsnew("/tmp/redis.ds");
874 server
.cache_max_memory
= 64LL*1024*1024; /* 64 MB of RAM */
875 server
.cache_blocked_clients
= 0;
876 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
877 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
878 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
879 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
880 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
881 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
882 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
883 server
.shutdown_asap
= 0;
884 server
.cache_flush_delay
= 0;
885 server
.cluster_enabled
= 0;
886 server
.cluster
.configfile
= zstrdup("nodes.conf");
889 resetServerSaveParams();
891 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
892 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
893 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
894 /* Replication related */
896 server
.masterauth
= NULL
;
897 server
.masterhost
= NULL
;
898 server
.masterport
= 6379;
899 server
.master
= NULL
;
900 server
.replstate
= REDIS_REPL_NONE
;
901 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
902 server
.repl_serve_stale_data
= 1;
904 /* Double constants initialization */
906 R_PosInf
= 1.0/R_Zero
;
907 R_NegInf
= -1.0/R_Zero
;
908 R_Nan
= R_Zero
/R_Zero
;
910 /* Command table -- we intiialize it here as it is part of the
911 * initial configuration, since command names may be changed via
912 * redis.conf using the rename-command directive. */
913 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
914 populateCommandTable();
915 server
.delCommand
= lookupCommandByCString("del");
916 server
.multiCommand
= lookupCommandByCString("multi");
922 signal(SIGHUP
, SIG_IGN
);
923 signal(SIGPIPE
, SIG_IGN
);
924 setupSignalHandlers();
926 if (server
.syslog_enabled
) {
927 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
928 server
.syslog_facility
);
931 server
.mainthread
= pthread_self();
932 server
.clients
= listCreate();
933 server
.slaves
= listCreate();
934 server
.monitors
= listCreate();
935 server
.unblocked_clients
= listCreate();
936 server
.cache_io_queue
= listCreate();
938 createSharedObjects();
939 server
.el
= aeCreateEventLoop();
940 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
942 if (server
.port
!= 0) {
943 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
944 if (server
.ipfd
== ANET_ERR
) {
945 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
949 if (server
.unixsocket
!= NULL
) {
950 unlink(server
.unixsocket
); /* don't care if this fails */
951 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
952 if (server
.sofd
== ANET_ERR
) {
953 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
957 if (server
.ipfd
< 0 && server
.sofd
< 0) {
958 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
961 for (j
= 0; j
< server
.dbnum
; j
++) {
962 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
963 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
964 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
965 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
966 if (server
.ds_enabled
) {
967 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
968 server
.db
[j
].io_negcache
= dictCreate(&setDictType
,NULL
);
969 server
.db
[j
].io_queued
= dictCreate(&setDictType
,NULL
);
973 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
974 server
.pubsub_patterns
= listCreate();
975 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
976 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
977 server
.cronloops
= 0;
978 server
.bgsavechildpid
= -1;
979 server
.bgrewritechildpid
= -1;
980 server
.bgsavethread_state
= REDIS_BGSAVE_THREAD_UNACTIVE
;
981 server
.bgsavethread
= (pthread_t
) -1;
982 server
.bgrewritebuf
= sdsempty();
983 server
.aofbuf
= sdsempty();
984 server
.lastsave
= time(NULL
);
986 server
.stat_numcommands
= 0;
987 server
.stat_numconnections
= 0;
988 server
.stat_expiredkeys
= 0;
989 server
.stat_evictedkeys
= 0;
990 server
.stat_starttime
= time(NULL
);
991 server
.stat_keyspace_misses
= 0;
992 server
.stat_keyspace_hits
= 0;
993 server
.stat_peak_memory
= 0;
994 server
.stat_fork_time
= 0;
995 server
.unixtime
= time(NULL
);
996 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
997 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
998 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
999 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
1000 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
1002 if (server
.appendonly
) {
1003 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1004 if (server
.appendfd
== -1) {
1005 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1011 if (server
.ds_enabled
) dsInit();
1012 if (server
.cluster_enabled
) clusterInit();
1013 srand(time(NULL
)^getpid());
1016 /* Populates the Redis Command Table starting from the hard coded list
1017 * we have on top of redis.c file. */
1018 void populateCommandTable(void) {
1020 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1022 for (j
= 0; j
< numcommands
; j
++) {
1023 struct redisCommand
*c
= redisCommandTable
+j
;
1026 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
1027 assert(retval
== DICT_OK
);
1031 void resetCommandTableStats(void) {
1032 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1035 for (j
= 0; j
< numcommands
; j
++) {
1036 struct redisCommand
*c
= redisCommandTable
+j
;
1038 c
->microseconds
= 0;
1043 /* ====================== Commands lookup and execution ===================== */
1045 struct redisCommand
*lookupCommand(sds name
) {
1046 return dictFetchValue(server
.commands
, name
);
1049 struct redisCommand
*lookupCommandByCString(char *s
) {
1050 struct redisCommand
*cmd
;
1051 sds name
= sdsnew(s
);
1053 cmd
= dictFetchValue(server
.commands
, name
);
1058 /* Call() is the core of Redis execution of a command */
1059 void call(redisClient
*c
, struct redisCommand
*cmd
) {
1060 long long dirty
, start
= ustime();
1062 dirty
= server
.dirty
;
1064 dirty
= server
.dirty
-dirty
;
1065 cmd
->microseconds
+= ustime()-start
;
1068 if (server
.appendonly
&& dirty
)
1069 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1070 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1071 listLength(server
.slaves
))
1072 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1073 if (listLength(server
.monitors
))
1074 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1075 server
.stat_numcommands
++;
1078 /* If this function gets called we already read a whole
1079 * command, argments are in the client argv/argc fields.
1080 * processCommand() execute the command or prepare the
1081 * server for a bulk read from the client.
1083 * If 1 is returned the client is still alive and valid and
1084 * and other operations can be performed by the caller. Otherwise
1085 * if 0 is returned the client was destroied (i.e. after QUIT). */
1086 int processCommand(redisClient
*c
) {
1087 struct redisCommand
*cmd
;
1089 /* The QUIT command is handled separately. Normal command procs will
1090 * go through checking for replication and QUIT will cause trouble
1091 * when FORCE_REPLICATION is enabled and would be implemented in
1092 * a regular command proc. */
1093 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1094 addReply(c
,shared
.ok
);
1095 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1099 /* Now lookup the command and check ASAP about trivial error conditions
1100 * such wrong arity, bad command name and so forth. */
1101 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1103 addReplyErrorFormat(c
,"unknown command '%s'",
1104 (char*)c
->argv
[0]->ptr
);
1106 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1107 (c
->argc
< -cmd
->arity
)) {
1108 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1113 /* Check if the user is authenticated */
1114 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1115 addReplyError(c
,"operation not permitted");
1119 /* If cluster is enabled, redirect here */
1120 if (server
.cluster_enabled
&&
1121 !(cmd
->getkeys_proc
== NULL
&& cmd
->firstkey
== 0)) {
1124 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1125 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1129 clusterNode
*n
= getNodeByQuery(c
,cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1131 addReplyError(c
,"Multi keys request invalid in cluster");
1133 } else if (n
!= server
.cluster
.myself
) {
1134 addReplySds(c
,sdscatprintf(sdsempty(),
1135 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1136 hashslot
,n
->ip
,n
->port
));
1142 /* Handle the maxmemory directive.
1144 * First we try to free some memory if possible (if there are volatile
1145 * keys in the dataset). If there are not the only thing we can do
1146 * is returning an error. */
1147 if (server
.maxmemory
) freeMemoryIfNeeded();
1148 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1149 zmalloc_used_memory() > server
.maxmemory
)
1151 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1155 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1156 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1158 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
1159 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
1160 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1164 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1165 * we are a slave with a broken link with master. */
1166 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1167 server
.repl_serve_stale_data
== 0 &&
1168 cmd
->proc
!= infoCommand
&& cmd
->proc
!= slaveofCommand
)
1171 "link with MASTER is down and slave-serve-stale-data is set to no");
1175 /* Loading DB? Return an error if the command is not INFO */
1176 if (server
.loading
&& cmd
->proc
!= infoCommand
) {
1177 addReply(c
, shared
.loadingerr
);
1181 /* Exec the command */
1182 if (c
->flags
& REDIS_MULTI
&&
1183 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
1184 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
1186 queueMultiCommand(c
,cmd
);
1187 addReply(c
,shared
.queued
);
1189 if (server
.ds_enabled
&& blockClientOnSwappedKeys(c
,cmd
))
1196 /*================================== Shutdown =============================== */
1198 int prepareForShutdown() {
1199 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1200 /* Kill the saving child if there is a background saving in progress.
1201 We want to avoid race conditions, for instance our saving child may
1202 overwrite the synchronous saving did by SHUTDOWN. */
1203 if (server
.bgsavechildpid
!= -1) {
1204 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
1205 kill(server
.bgsavechildpid
,SIGKILL
);
1206 rdbRemoveTempFile(server
.bgsavechildpid
);
1208 if (server
.ds_enabled
) {
1209 /* FIXME: flush all objects on disk */
1210 } else if (server
.appendonly
) {
1211 /* Append only file: fsync() the AOF and exit */
1212 aof_fsync(server
.appendfd
);
1213 } else if (server
.saveparamslen
> 0) {
1214 /* Snapshotting. Perform a SYNC SAVE and exit */
1215 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1216 /* Ooops.. error saving! The best we can do is to continue
1217 * operating. Note that if there was a background saving process,
1218 * in the next cron() Redis will be notified that the background
1219 * saving aborted, handling special stuff like slaves pending for
1220 * synchronization... */
1221 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1225 redisLog(REDIS_WARNING
,"Not saving DB.");
1227 if (server
.daemonize
) unlink(server
.pidfile
);
1228 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1232 /*================================== Commands =============================== */
1234 void authCommand(redisClient
*c
) {
1235 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1236 c
->authenticated
= 1;
1237 addReply(c
,shared
.ok
);
1239 c
->authenticated
= 0;
1240 addReplyError(c
,"invalid password");
1244 void pingCommand(redisClient
*c
) {
1245 addReply(c
,shared
.pong
);
1248 void echoCommand(redisClient
*c
) {
1249 addReplyBulk(c
,c
->argv
[1]);
1252 /* Convert an amount of bytes into a human readable string in the form
1253 * of 100B, 2G, 100M, 4K, and so forth. */
1254 void bytesToHuman(char *s
, unsigned long long n
) {
1259 sprintf(s
,"%lluB",n
);
1261 } else if (n
< (1024*1024)) {
1262 d
= (double)n
/(1024);
1263 sprintf(s
,"%.2fK",d
);
1264 } else if (n
< (1024LL*1024*1024)) {
1265 d
= (double)n
/(1024*1024);
1266 sprintf(s
,"%.2fM",d
);
1267 } else if (n
< (1024LL*1024*1024*1024)) {
1268 d
= (double)n
/(1024LL*1024*1024);
1269 sprintf(s
,"%.2fG",d
);
1273 /* Create the string returned by the INFO command. This is decoupled
1274 * by the INFO command itself as we need to report the same information
1275 * on memory corruption problems. */
1276 sds
genRedisInfoString(char *section
) {
1277 sds info
= sdsempty();
1278 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1280 struct rusage self_ru
, c_ru
;
1281 unsigned long lol
, bib
;
1282 int allsections
= 0, defsections
= 0;
1286 allsections
= strcasecmp(section
,"all") == 0;
1287 defsections
= strcasecmp(section
,"default") == 0;
1290 getrusage(RUSAGE_SELF
, &self_ru
);
1291 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1292 getClientsMaxBuffers(&lol
,&bib
);
1295 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1296 if (sections
++) info
= sdscat(info
,"\r\n");
1297 info
= sdscatprintf(info
,
1299 "redis_version:%s\r\n"
1300 "redis_git_sha1:%s\r\n"
1301 "redis_git_dirty:%d\r\n"
1303 "multiplexing_api:%s\r\n"
1304 "process_id:%ld\r\n"
1306 "uptime_in_seconds:%ld\r\n"
1307 "uptime_in_days:%ld\r\n"
1308 "lru_clock:%ld\r\n",
1311 strtol(redisGitDirty(),NULL
,10) > 0,
1312 (sizeof(long) == 8) ? "64" : "32",
1318 (unsigned long) server
.lruclock
);
1322 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1323 if (sections
++) info
= sdscat(info
,"\r\n");
1324 info
= sdscatprintf(info
,
1326 "connected_clients:%d\r\n"
1327 "client_longest_output_list:%lu\r\n"
1328 "client_biggest_input_buf:%lu\r\n"
1329 "blocked_clients:%d\r\n",
1330 listLength(server
.clients
)-listLength(server
.slaves
),
1332 server
.bpop_blocked_clients
);
1336 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1340 bytesToHuman(hmem
,zmalloc_used_memory());
1341 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1342 if (sections
++) info
= sdscat(info
,"\r\n");
1343 info
= sdscatprintf(info
,
1345 "used_memory:%zu\r\n"
1346 "used_memory_human:%s\r\n"
1347 "used_memory_rss:%zu\r\n"
1348 "used_memory_peak:%zu\r\n"
1349 "used_memory_peak_human:%s\r\n"
1350 "mem_fragmentation_ratio:%.2f\r\n"
1351 "mem_allocator:%s\r\n",
1352 zmalloc_used_memory(),
1355 server
.stat_peak_memory
,
1357 zmalloc_get_fragmentation_ratio(),
1362 /* Allocation statistics */
1363 if (allsections
|| !strcasecmp(section
,"allocstats")) {
1364 if (sections
++) info
= sdscat(info
,"\r\n");
1365 info
= sdscat(info
, "# Allocstats\r\nallocation_stats:");
1366 for (j
= 0; j
<= ZMALLOC_MAX_ALLOC_STAT
; j
++) {
1367 size_t count
= zmalloc_allocations_for_size(j
);
1369 if (info
[sdslen(info
)-1] != ':') info
= sdscatlen(info
,",",1);
1370 info
= sdscatprintf(info
,"%s%d=%zu",
1371 (j
== ZMALLOC_MAX_ALLOC_STAT
) ? ">=" : "",
1375 info
= sdscat(info
,"\r\n");
1379 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1380 if (sections
++) info
= sdscat(info
,"\r\n");
1381 info
= sdscatprintf(info
,
1384 "aof_enabled:%d\r\n"
1385 "changes_since_last_save:%lld\r\n"
1386 "bgsave_in_progress:%d\r\n"
1387 "last_save_time:%ld\r\n"
1388 "bgrewriteaof_in_progress:%d\r\n",
1392 server
.bgsavechildpid
!= -1 ||
1393 server
.bgsavethread
!= (pthread_t
) -1,
1395 server
.bgrewritechildpid
!= -1);
1397 if (server
.loading
) {
1399 time_t eta
, elapsed
;
1400 off_t remaining_bytes
= server
.loading_total_bytes
-
1401 server
.loading_loaded_bytes
;
1403 perc
= ((double)server
.loading_loaded_bytes
/
1404 server
.loading_total_bytes
) * 100;
1406 elapsed
= time(NULL
)-server
.loading_start_time
;
1408 eta
= 1; /* A fake 1 second figure if we don't have
1411 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1414 info
= sdscatprintf(info
,
1415 "loading_start_time:%ld\r\n"
1416 "loading_total_bytes:%llu\r\n"
1417 "loading_loaded_bytes:%llu\r\n"
1418 "loading_loaded_perc:%.2f\r\n"
1419 "loading_eta_seconds:%ld\r\n"
1420 ,(unsigned long) server
.loading_start_time
,
1421 (unsigned long long) server
.loading_total_bytes
,
1422 (unsigned long long) server
.loading_loaded_bytes
,
1430 if (allsections
|| defsections
|| !strcasecmp(section
,"diskstore")) {
1431 if (sections
++) info
= sdscat(info
,"\r\n");
1432 info
= sdscatprintf(info
,
1434 "ds_enabled:%d\r\n",
1435 server
.ds_enabled
!= 0);
1436 if (server
.ds_enabled
) {
1438 info
= sdscatprintf(info
,
1439 "cache_max_memory:%llu\r\n"
1440 "cache_blocked_clients:%lu\r\n"
1441 "cache_io_queue_len:%lu\r\n"
1442 "cache_io_jobs_new:%lu\r\n"
1443 "cache_io_jobs_processing:%lu\r\n"
1444 "cache_io_jobs_processed:%lu\r\n"
1445 "cache_io_ready_clients:%lu\r\n"
1446 ,(unsigned long long) server
.cache_max_memory
,
1447 (unsigned long) server
.cache_blocked_clients
,
1448 (unsigned long) listLength(server
.cache_io_queue
),
1449 (unsigned long) listLength(server
.io_newjobs
),
1450 (unsigned long) listLength(server
.io_processing
),
1451 (unsigned long) listLength(server
.io_processed
),
1452 (unsigned long) listLength(server
.io_ready_clients
)
1459 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1460 if (sections
++) info
= sdscat(info
,"\r\n");
1461 info
= sdscatprintf(info
,
1463 "total_connections_received:%lld\r\n"
1464 "total_commands_processed:%lld\r\n"
1465 "expired_keys:%lld\r\n"
1466 "evicted_keys:%lld\r\n"
1467 "keyspace_hits:%lld\r\n"
1468 "keyspace_misses:%lld\r\n"
1469 "pubsub_channels:%ld\r\n"
1470 "pubsub_patterns:%u\r\n"
1471 "latest_fork_usec:%lld\r\n",
1472 server
.stat_numconnections
,
1473 server
.stat_numcommands
,
1474 server
.stat_expiredkeys
,
1475 server
.stat_evictedkeys
,
1476 server
.stat_keyspace_hits
,
1477 server
.stat_keyspace_misses
,
1478 dictSize(server
.pubsub_channels
),
1479 listLength(server
.pubsub_patterns
),
1480 server
.stat_fork_time
);
1484 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1485 if (sections
++) info
= sdscat(info
,"\r\n");
1486 info
= sdscatprintf(info
,
1489 server
.masterhost
== NULL
? "master" : "slave");
1490 if (server
.masterhost
) {
1491 info
= sdscatprintf(info
,
1492 "master_host:%s\r\n"
1493 "master_port:%d\r\n"
1494 "master_link_status:%s\r\n"
1495 "master_last_io_seconds_ago:%d\r\n"
1496 "master_sync_in_progress:%d\r\n"
1499 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1502 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1503 server
.replstate
== REDIS_REPL_TRANSFER
1506 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1507 info
= sdscatprintf(info
,
1508 "master_sync_left_bytes:%ld\r\n"
1509 "master_sync_last_io_seconds_ago:%d\r\n"
1510 ,(long)server
.repl_transfer_left
,
1511 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1515 info
= sdscatprintf(info
,
1516 "connected_slaves:%d\r\n",
1517 listLength(server
.slaves
));
1521 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1522 if (sections
++) info
= sdscat(info
,"\r\n");
1523 info
= sdscatprintf(info
,
1525 "used_cpu_sys:%.2f\r\n"
1526 "used_cpu_user:%.2f\r\n"
1527 "used_cpu_sys_childrens:%.2f\r\n"
1528 "used_cpu_user_childrens:%.2f\r\n",
1529 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1530 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1531 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1532 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000);
1536 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1537 if (sections
++) info
= sdscat(info
,"\r\n");
1538 info
= sdscatprintf(info
, "# Commandstats\r\n");
1539 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1540 for (j
= 0; j
< numcommands
; j
++) {
1541 struct redisCommand
*c
= redisCommandTable
+j
;
1543 if (!c
->calls
) continue;
1544 info
= sdscatprintf(info
,
1545 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1546 c
->name
, c
->calls
, c
->microseconds
,
1547 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1552 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1553 if (sections
++) info
= sdscat(info
,"\r\n");
1554 info
= sdscatprintf(info
,
1556 "cluster_enabled:%d\r\n",
1557 server
.cluster_enabled
);
1561 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1562 if (sections
++) info
= sdscat(info
,"\r\n");
1563 info
= sdscatprintf(info
, "# Keyspace\r\n");
1564 for (j
= 0; j
< server
.dbnum
; j
++) {
1565 long long keys
, vkeys
;
1567 keys
= dictSize(server
.db
[j
].dict
);
1568 vkeys
= dictSize(server
.db
[j
].expires
);
1569 if (keys
|| vkeys
) {
1570 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1578 void infoCommand(redisClient
*c
) {
1579 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1582 addReply(c
,shared
.syntaxerr
);
1585 sds info
= genRedisInfoString(section
);
1586 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1587 (unsigned long)sdslen(info
)));
1588 addReplySds(c
,info
);
1589 addReply(c
,shared
.crlf
);
1592 void monitorCommand(redisClient
*c
) {
1593 /* ignore MONITOR if aleady slave or in monitor mode */
1594 if (c
->flags
& REDIS_SLAVE
) return;
1596 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1598 listAddNodeTail(server
.monitors
,c
);
1599 addReply(c
,shared
.ok
);
1602 /* ============================ Maxmemory directive ======================== */
1604 /* This function gets called when 'maxmemory' is set on the config file to limit
1605 * the max memory used by the server, and we are out of memory.
1606 * This function will try to, in order:
1608 * - Free objects from the free list
1609 * - Try to remove keys with an EXPIRE set
1611 * It is not possible to free enough memory to reach used-memory < maxmemory
1612 * the server will start refusing commands that will enlarge even more the
1615 void freeMemoryIfNeeded(void) {
1616 /* Remove keys accordingly to the active policy as long as we are
1617 * over the memory limit. */
1618 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1620 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1621 int j
, k
, freed
= 0;
1623 for (j
= 0; j
< server
.dbnum
; j
++) {
1624 long bestval
= 0; /* just to prevent warning */
1626 struct dictEntry
*de
;
1627 redisDb
*db
= server
.db
+j
;
1630 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1631 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1633 dict
= server
.db
[j
].dict
;
1635 dict
= server
.db
[j
].expires
;
1637 if (dictSize(dict
) == 0) continue;
1639 /* volatile-random and allkeys-random policy */
1640 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1641 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1643 de
= dictGetRandomKey(dict
);
1644 bestkey
= dictGetEntryKey(de
);
1647 /* volatile-lru and allkeys-lru policy */
1648 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1649 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1651 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1656 de
= dictGetRandomKey(dict
);
1657 thiskey
= dictGetEntryKey(de
);
1658 /* When policy is volatile-lru we need an additonal lookup
1659 * to locate the real key, as dict is set to db->expires. */
1660 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1661 de
= dictFind(db
->dict
, thiskey
);
1662 o
= dictGetEntryVal(de
);
1663 thisval
= estimateObjectIdleTime(o
);
1665 /* Higher idle time is better candidate for deletion */
1666 if (bestkey
== NULL
|| thisval
> bestval
) {
1674 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1675 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1679 de
= dictGetRandomKey(dict
);
1680 thiskey
= dictGetEntryKey(de
);
1681 thisval
= (long) dictGetEntryVal(de
);
1683 /* Expire sooner (minor expire unix timestamp) is better
1684 * candidate for deletion */
1685 if (bestkey
== NULL
|| thisval
< bestval
) {
1692 /* Finally remove the selected key. */
1694 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1695 propagateExpire(db
,keyobj
);
1696 dbDelete(db
,keyobj
);
1697 server
.stat_evictedkeys
++;
1698 decrRefCount(keyobj
);
1702 if (!freed
) return; /* nothing to free... */
1706 /* =================================== Main! ================================ */
1709 int linuxOvercommitMemoryValue(void) {
1710 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1714 if (fgets(buf
,64,fp
) == NULL
) {
1723 void linuxOvercommitMemoryWarning(void) {
1724 if (linuxOvercommitMemoryValue() == 0) {
1725 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.");
1728 #endif /* __linux__ */
1730 void createPidFile(void) {
1731 /* Try to write the pid file in a best-effort way. */
1732 FILE *fp
= fopen(server
.pidfile
,"w");
1734 fprintf(fp
,"%d\n",(int)getpid());
1739 void daemonize(void) {
1742 if (fork() != 0) exit(0); /* parent exits */
1743 setsid(); /* create a new session */
1745 /* Every output goes to /dev/null. If Redis is daemonized but
1746 * the 'logfile' is set to 'stdout' in the configuration file
1747 * it will not log at all. */
1748 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1749 dup2(fd
, STDIN_FILENO
);
1750 dup2(fd
, STDOUT_FILENO
);
1751 dup2(fd
, STDERR_FILENO
);
1752 if (fd
> STDERR_FILENO
) close(fd
);
1757 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1758 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1763 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1764 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1768 void redisAsciiArt(void) {
1769 #include "asciilogo.h"
1770 char *buf
= zmalloc(1024*16);
1772 snprintf(buf
,1024*16,ascii_logo
,
1775 strtol(redisGitDirty(),NULL
,10) > 0,
1776 (sizeof(long) == 8) ? "64" : "32",
1777 server
.cluster_enabled
? "cluster" : "stand alone",
1781 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1785 int main(int argc
, char **argv
) {
1790 if (strcmp(argv
[1], "-v") == 0 ||
1791 strcmp(argv
[1], "--version") == 0) version();
1792 if (strcmp(argv
[1], "--help") == 0) usage();
1793 resetServerSaveParams();
1794 loadServerConfig(argv
[1]);
1795 } else if ((argc
> 2)) {
1798 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'");
1800 if (server
.daemonize
) daemonize();
1802 if (server
.daemonize
) createPidFile();
1804 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1806 linuxOvercommitMemoryWarning();
1809 if (server
.ds_enabled
) {
1810 redisLog(REDIS_NOTICE
,"DB not loaded (running with disk back end)");
1811 } else if (server
.appendonly
) {
1812 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1813 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1815 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1816 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",(float)(ustime()-start
)/1000000);
1818 if (server
.ipfd
> 0)
1819 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1820 if (server
.sofd
> 0)
1821 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1822 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1824 aeDeleteEventLoop(server
.el
);
1828 #ifdef HAVE_BACKTRACE
1829 static void *getMcontextEip(ucontext_t
*uc
) {
1830 #if defined(__FreeBSD__)
1831 return (void*) uc
->uc_mcontext
.mc_eip
;
1832 #elif defined(__dietlibc__)
1833 return (void*) uc
->uc_mcontext
.eip
;
1834 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1836 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1838 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1840 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1841 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1842 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1844 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1846 #elif defined(__i386__)
1847 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1848 #elif defined(__X86_64__) || defined(__x86_64__)
1849 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1850 #elif defined(__ia64__) /* Linux IA64 */
1851 return (void*) uc
->uc_mcontext
.sc_ip
;
1857 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1859 char **messages
= NULL
;
1860 int i
, trace_size
= 0;
1861 ucontext_t
*uc
= (ucontext_t
*) secret
;
1863 struct sigaction act
;
1864 REDIS_NOTUSED(info
);
1866 redisLog(REDIS_WARNING
,
1867 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1868 infostring
= genRedisInfoString("all");
1869 redisLogRaw(REDIS_WARNING
, infostring
);
1870 /* It's not safe to sdsfree() the returned string under memory
1871 * corruption conditions. Let it leak as we are going to abort */
1873 trace_size
= backtrace(trace
, 100);
1874 /* overwrite sigaction with caller's address */
1875 if (getMcontextEip(uc
) != NULL
) {
1876 trace
[1] = getMcontextEip(uc
);
1878 messages
= backtrace_symbols(trace
, trace_size
);
1880 for (i
=1; i
<trace_size
; ++i
)
1881 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1883 /* free(messages); Don't call free() with possibly corrupted memory. */
1884 if (server
.daemonize
) unlink(server
.pidfile
);
1886 /* Make sure we exit with the right signal at the end. So for instance
1887 * the core will be dumped if enabled. */
1888 sigemptyset (&act
.sa_mask
);
1889 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1890 * is used. Otherwise, sa_handler is used */
1891 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1892 act
.sa_handler
= SIG_DFL
;
1893 sigaction (sig
, &act
, NULL
);
1896 #endif /* HAVE_BACKTRACE */
1898 static void sigtermHandler(int sig
) {
1901 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1902 server
.shutdown_asap
= 1;
1905 void setupSignalHandlers(void) {
1906 struct sigaction act
;
1908 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1909 * Otherwise, sa_handler is used. */
1910 sigemptyset(&act
.sa_mask
);
1911 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1912 act
.sa_handler
= sigtermHandler
;
1913 sigaction(SIGTERM
, &act
, NULL
);
1915 #ifdef HAVE_BACKTRACE
1916 sigemptyset(&act
.sa_mask
);
1917 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1918 act
.sa_sigaction
= sigsegvHandler
;
1919 sigaction(SIGSEGV
, &act
, NULL
);
1920 sigaction(SIGBUS
, &act
, NULL
);
1921 sigaction(SIGFPE
, &act
, NULL
);
1922 sigaction(SIGILL
, &act
, NULL
);