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 actually 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
;
73 /* Our command table. Command flags are expressed using strings where every
74 * character represents a flag. Later the populateCommandTable() function will
75 * take care of populating the real 'flags' field using this characters.
77 * This is the meaning of the flags:
79 * w: write command (may modify the key space).
80 * r: read command (will never modify the key space).
81 * m: may increase memory usage once called. Don't allow if out of memory.
82 * a: admin command, like SAVE or SHUTDOWN.
83 * p: Pub/Sub related command.
84 * f: force replication of this command, regarless of server.dirty.
85 * s: command not allowed in scripts.
86 * r: random command. Command is not deterministic, that is, the same command
87 * with the same arguments, with the same key space, may have different
88 * results. For instance SPOP and RANDOMKEY are two random commands. */
89 struct redisCommand redisCommandTable
[] = {
90 {"get",getCommand
,2,"r",0,NULL
,1,1,1,0,0},
91 {"set",setCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
92 {"setnx",setnxCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
93 {"setex",setexCommand
,4,"wm",0,noPreloadGetKeys
,2,2,1,0,0},
94 {"append",appendCommand
,3,"wm",0,NULL
,1,1,1,0,0},
95 {"strlen",strlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
96 {"del",delCommand
,-2,"w",0,noPreloadGetKeys
,1,-1,1,0,0},
97 {"exists",existsCommand
,2,"r",0,NULL
,1,1,1,0,0},
98 {"setbit",setbitCommand
,4,"wm",0,NULL
,1,1,1,0,0},
99 {"getbit",getbitCommand
,3,"r",0,NULL
,1,1,1,0,0},
100 {"setrange",setrangeCommand
,4,"wm",0,NULL
,1,1,1,0,0},
101 {"getrange",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
102 {"substr",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
103 {"incr",incrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
104 {"decr",decrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
105 {"mget",mgetCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
106 {"rpush",rpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
107 {"lpush",lpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
108 {"rpushx",rpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
109 {"lpushx",lpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
110 {"linsert",linsertCommand
,5,"wm",0,NULL
,1,1,1,0,0},
111 {"rpop",rpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
112 {"lpop",lpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
113 {"brpop",brpopCommand
,-3,"w",0,NULL
,1,1,1,0,0},
114 {"brpoplpush",brpoplpushCommand
,4,"wm",0,NULL
,1,2,1,0,0},
115 {"blpop",blpopCommand
,-3,"w",0,NULL
,1,-2,1,0,0},
116 {"llen",llenCommand
,2,"r",0,NULL
,1,1,1,0,0},
117 {"lindex",lindexCommand
,3,"r",0,NULL
,1,1,1,0,0},
118 {"lset",lsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
119 {"lrange",lrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
120 {"ltrim",ltrimCommand
,4,"w",0,NULL
,1,1,1,0,0},
121 {"lrem",lremCommand
,4,"w",0,NULL
,1,1,1,0,0},
122 {"rpoplpush",rpoplpushCommand
,3,"wm",0,NULL
,1,2,1,0,0},
123 {"sadd",saddCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
124 {"srem",sremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
125 {"smove",smoveCommand
,4,"w",0,NULL
,1,2,1,0,0},
126 {"sismember",sismemberCommand
,3,"r",0,NULL
,1,1,1,0,0},
127 {"scard",scardCommand
,2,"r",0,NULL
,1,1,1,0,0},
128 {"spop",spopCommand
,2,"wRs",0,NULL
,1,1,1,0,0},
129 {"srandmember",srandmemberCommand
,2,"rR",0,NULL
,1,1,1,0,0},
130 {"sinter",sinterCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
131 {"sinterstore",sinterstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
132 {"sunion",sunionCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
133 {"sunionstore",sunionstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
134 {"sdiff",sdiffCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
135 {"sdiffstore",sdiffstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
136 {"smembers",sinterCommand
,2,"r",0,NULL
,1,1,1,0,0},
137 {"zadd",zaddCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
138 {"zincrby",zincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
139 {"zrem",zremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
140 {"zremrangebyscore",zremrangebyscoreCommand
,4,"w",0,NULL
,1,1,1,0,0},
141 {"zremrangebyrank",zremrangebyrankCommand
,4,"w",0,NULL
,1,1,1,0,0},
142 {"zunionstore",zunionstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
143 {"zinterstore",zinterstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
144 {"zrange",zrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
145 {"zrangebyscore",zrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
146 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
147 {"zcount",zcountCommand
,4,"r",0,NULL
,1,1,1,0,0},
148 {"zrevrange",zrevrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
149 {"zcard",zcardCommand
,2,"r",0,NULL
,1,1,1,0,0},
150 {"zscore",zscoreCommand
,3,"r",0,NULL
,1,1,1,0,0},
151 {"zrank",zrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
152 {"zrevrank",zrevrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
153 {"hset",hsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
154 {"hsetnx",hsetnxCommand
,4,"wm",0,NULL
,1,1,1,0,0},
155 {"hget",hgetCommand
,3,"r",0,NULL
,1,1,1,0,0},
156 {"hmset",hmsetCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
157 {"hmget",hmgetCommand
,-3,"r",0,NULL
,1,1,1,0,0},
158 {"hincrby",hincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
159 {"hdel",hdelCommand
,-3,"w",0,NULL
,1,1,1,0,0},
160 {"hlen",hlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
161 {"hkeys",hkeysCommand
,2,"r",0,NULL
,1,1,1,0,0},
162 {"hvals",hvalsCommand
,2,"r",0,NULL
,1,1,1,0,0},
163 {"hgetall",hgetallCommand
,2,"r",0,NULL
,1,1,1,0,0},
164 {"hexists",hexistsCommand
,3,"r",0,NULL
,1,1,1,0,0},
165 {"incrby",incrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
166 {"decrby",decrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
167 {"getset",getsetCommand
,3,"wm",0,NULL
,1,1,1,0,0},
168 {"mset",msetCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
169 {"msetnx",msetnxCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
170 {"randomkey",randomkeyCommand
,1,"rR",0,NULL
,0,0,0,0,0},
171 {"select",selectCommand
,2,"r",0,NULL
,0,0,0,0,0},
172 {"move",moveCommand
,3,"w",0,NULL
,1,1,1,0,0},
173 {"rename",renameCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
174 {"renamenx",renamenxCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
175 {"expire",expireCommand
,3,"w",0,NULL
,1,1,1,0,0},
176 {"expireat",expireatCommand
,3,"w",0,NULL
,1,1,1,0,0},
177 {"keys",keysCommand
,2,"r",0,NULL
,0,0,0,0,0},
178 {"dbsize",dbsizeCommand
,1,"r",0,NULL
,0,0,0,0,0},
179 {"auth",authCommand
,2,"r",0,NULL
,0,0,0,0,0},
180 {"ping",pingCommand
,1,"r",0,NULL
,0,0,0,0,0},
181 {"echo",echoCommand
,2,"r",0,NULL
,0,0,0,0,0},
182 {"save",saveCommand
,1,"ar",0,NULL
,0,0,0,0,0},
183 {"bgsave",bgsaveCommand
,1,"ar",0,NULL
,0,0,0,0,0},
184 {"bgrewriteaof",bgrewriteaofCommand
,1,"ar",0,NULL
,0,0,0,0,0},
185 {"shutdown",shutdownCommand
,1,"ar",0,NULL
,0,0,0,0,0},
186 {"lastsave",lastsaveCommand
,1,"r",0,NULL
,0,0,0,0,0},
187 {"type",typeCommand
,2,"r",0,NULL
,1,1,1,0,0},
188 {"multi",multiCommand
,1,"rs",0,NULL
,0,0,0,0,0},
189 {"exec",execCommand
,1,"wms",0,NULL
,0,0,0,0,0},
190 {"discard",discardCommand
,1,"rs",0,NULL
,0,0,0,0,0},
191 {"sync",syncCommand
,1,"ars",0,NULL
,0,0,0,0,0},
192 {"flushdb",flushdbCommand
,1,"w",0,NULL
,0,0,0,0,0},
193 {"flushall",flushallCommand
,1,"w",0,NULL
,0,0,0,0,0},
194 {"sort",sortCommand
,-2,"wm",0,NULL
,1,1,1,0,0},
195 {"info",infoCommand
,-1,"r",0,NULL
,0,0,0,0,0},
196 {"monitor",monitorCommand
,1,"ars",0,NULL
,0,0,0,0,0},
197 {"ttl",ttlCommand
,2,"r",0,NULL
,1,1,1,0,0},
198 {"persist",persistCommand
,2,"w",0,NULL
,1,1,1,0,0},
199 {"slaveof",slaveofCommand
,3,"aws",0,NULL
,0,0,0,0,0},
200 {"debug",debugCommand
,-2,"aw",0,NULL
,0,0,0,0,0},
201 {"config",configCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
202 {"subscribe",subscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
203 {"unsubscribe",unsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
204 {"psubscribe",psubscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
205 {"punsubscribe",punsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
206 {"publish",publishCommand
,3,"rpf",0,NULL
,0,0,0,0,0},
207 {"watch",watchCommand
,-2,"rs",0,noPreloadGetKeys
,1,-1,1,0,0},
208 {"unwatch",unwatchCommand
,1,"rs",0,NULL
,0,0,0,0,0},
209 {"cluster",clusterCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
210 {"restore",restoreCommand
,4,"awm",0,NULL
,1,1,1,0,0},
211 {"migrate",migrateCommand
,6,"aw",0,NULL
,0,0,0,0,0},
212 {"asking",askingCommand
,1,"r",0,NULL
,0,0,0,0,0},
213 {"dump",dumpCommand
,2,"ar",0,NULL
,0,0,0,0,0},
214 {"object",objectCommand
,-2,"r",0,NULL
,0,0,0,0,0},
215 {"client",clientCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
216 {"eval",evalCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
217 {"evalsha",evalShaCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
218 {"slowlog",slowlogCommand
,-2,"r",0,NULL
,0,0,0,0,0}
221 /*============================ Utility functions ============================ */
223 /* Low level logging. To use only for very big messages, otherwise
224 * redisLog() is to prefer. */
225 void redisLogRaw(int level
, const char *msg
) {
226 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
227 const char *c
= ".-*#";
228 time_t now
= time(NULL
);
231 int rawmode
= (level
& REDIS_LOG_RAW
);
233 level
&= 0xff; /* clear flags */
234 if (level
< server
.verbosity
) return;
236 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
240 fprintf(fp
,"%s",msg
);
242 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
243 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
247 if (server
.logfile
) fclose(fp
);
249 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
252 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
253 * is used across the code. The raw version is only used in order to dump
254 * the INFO output on crash. */
255 void redisLog(int level
, const char *fmt
, ...) {
257 char msg
[REDIS_MAX_LOGMSG_LEN
];
259 if ((level
&0xff) < server
.verbosity
) return;
262 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
265 redisLogRaw(level
,msg
);
268 /* Redis generally does not try to recover from out of memory conditions
269 * when allocating objects or strings, it is not clear if it will be possible
270 * to report this condition to the client since the networking layer itself
271 * is based on heap allocation for send buffers, so we simply abort.
272 * At least the code will be simpler to read... */
273 void oom(const char *msg
) {
274 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
279 /* Return the UNIX time in microseconds */
280 long long ustime(void) {
284 gettimeofday(&tv
, NULL
);
285 ust
= ((long long)tv
.tv_sec
)*1000000;
290 /*====================== Hash table type implementation ==================== */
292 /* This is an hash table type that uses the SDS dynamic strings libary as
293 * keys and radis objects as values (objects can hold SDS strings,
296 void dictVanillaFree(void *privdata
, void *val
)
298 DICT_NOTUSED(privdata
);
302 void dictListDestructor(void *privdata
, void *val
)
304 DICT_NOTUSED(privdata
);
305 listRelease((list
*)val
);
308 int dictSdsKeyCompare(void *privdata
, const void *key1
,
312 DICT_NOTUSED(privdata
);
314 l1
= sdslen((sds
)key1
);
315 l2
= sdslen((sds
)key2
);
316 if (l1
!= l2
) return 0;
317 return memcmp(key1
, key2
, l1
) == 0;
320 /* A case insensitive version used for the command lookup table. */
321 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
324 DICT_NOTUSED(privdata
);
326 return strcasecmp(key1
, key2
) == 0;
329 void dictRedisObjectDestructor(void *privdata
, void *val
)
331 DICT_NOTUSED(privdata
);
333 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
337 void dictSdsDestructor(void *privdata
, void *val
)
339 DICT_NOTUSED(privdata
);
344 int dictObjKeyCompare(void *privdata
, const void *key1
,
347 const robj
*o1
= key1
, *o2
= key2
;
348 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
351 unsigned int dictObjHash(const void *key
) {
353 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
356 unsigned int dictSdsHash(const void *key
) {
357 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
360 unsigned int dictSdsCaseHash(const void *key
) {
361 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
364 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
367 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
370 if (o1
->encoding
== REDIS_ENCODING_INT
&&
371 o2
->encoding
== REDIS_ENCODING_INT
)
372 return o1
->ptr
== o2
->ptr
;
374 o1
= getDecodedObject(o1
);
375 o2
= getDecodedObject(o2
);
376 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
382 unsigned int dictEncObjHash(const void *key
) {
383 robj
*o
= (robj
*) key
;
385 if (o
->encoding
== REDIS_ENCODING_RAW
) {
386 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
388 if (o
->encoding
== REDIS_ENCODING_INT
) {
392 len
= ll2string(buf
,32,(long)o
->ptr
);
393 return dictGenHashFunction((unsigned char*)buf
, len
);
397 o
= getDecodedObject(o
);
398 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
405 /* Sets type hash table */
406 dictType setDictType
= {
407 dictEncObjHash
, /* hash function */
410 dictEncObjKeyCompare
, /* key compare */
411 dictRedisObjectDestructor
, /* key destructor */
412 NULL
/* val destructor */
415 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
416 dictType zsetDictType
= {
417 dictEncObjHash
, /* hash function */
420 dictEncObjKeyCompare
, /* key compare */
421 dictRedisObjectDestructor
, /* key destructor */
422 NULL
/* val destructor */
425 /* Db->dict, keys are sds strings, vals are Redis objects. */
426 dictType dbDictType
= {
427 dictSdsHash
, /* hash function */
430 dictSdsKeyCompare
, /* key compare */
431 dictSdsDestructor
, /* key destructor */
432 dictRedisObjectDestructor
/* val destructor */
436 dictType keyptrDictType
= {
437 dictSdsHash
, /* hash function */
440 dictSdsKeyCompare
, /* key compare */
441 NULL
, /* key destructor */
442 NULL
/* val destructor */
445 /* Command table. sds string -> command struct pointer. */
446 dictType commandTableDictType
= {
447 dictSdsCaseHash
, /* hash function */
450 dictSdsKeyCaseCompare
, /* key compare */
451 dictSdsDestructor
, /* key destructor */
452 NULL
/* val destructor */
455 /* Hash type hash table (note that small hashes are represented with zimpaps) */
456 dictType hashDictType
= {
457 dictEncObjHash
, /* hash function */
460 dictEncObjKeyCompare
, /* key compare */
461 dictRedisObjectDestructor
, /* key destructor */
462 dictRedisObjectDestructor
/* val destructor */
465 /* Keylist hash table type has unencoded redis objects as keys and
466 * lists as values. It's used for blocking operations (BLPOP) and to
467 * map swapped keys to a list of clients waiting for this keys to be loaded. */
468 dictType keylistDictType
= {
469 dictObjHash
, /* hash function */
472 dictObjKeyCompare
, /* key compare */
473 dictRedisObjectDestructor
, /* key destructor */
474 dictListDestructor
/* val destructor */
477 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
478 * clusterNode structures. */
479 dictType clusterNodesDictType
= {
480 dictSdsHash
, /* hash function */
483 dictSdsKeyCompare
, /* key compare */
484 dictSdsDestructor
, /* key destructor */
485 NULL
/* val destructor */
488 int htNeedsResize(dict
*dict
) {
489 long long size
, used
;
491 size
= dictSlots(dict
);
492 used
= dictSize(dict
);
493 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
494 (used
*100/size
< REDIS_HT_MINFILL
));
497 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
498 * we resize the hash table to save memory */
499 void tryResizeHashTables(void) {
502 for (j
= 0; j
< server
.dbnum
; j
++) {
503 if (htNeedsResize(server
.db
[j
].dict
))
504 dictResize(server
.db
[j
].dict
);
505 if (htNeedsResize(server
.db
[j
].expires
))
506 dictResize(server
.db
[j
].expires
);
510 /* Our hash table implementation performs rehashing incrementally while
511 * we write/read from the hash table. Still if the server is idle, the hash
512 * table will use two tables for a long time. So we try to use 1 millisecond
513 * of CPU time at every serverCron() loop in order to rehash some key. */
514 void incrementallyRehash(void) {
517 for (j
= 0; j
< server
.dbnum
; j
++) {
518 if (dictIsRehashing(server
.db
[j
].dict
)) {
519 dictRehashMilliseconds(server
.db
[j
].dict
,1);
520 break; /* already used our millisecond for this loop... */
525 /* This function is called once a background process of some kind terminates,
526 * as we want to avoid resizing the hash tables when there is a child in order
527 * to play well with copy-on-write (otherwise when a resize happens lots of
528 * memory pages are copied). The goal of this function is to update the ability
529 * for dict.c to resize the hash tables accordingly to the fact we have o not
531 void updateDictResizePolicy(void) {
532 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
538 /* ======================= Cron: called every 100 ms ======================== */
540 /* Try to expire a few timed out keys. The algorithm used is adaptive and
541 * will use few CPU cycles if there are few expiring keys, otherwise
542 * it will get more aggressive to avoid that too much memory is used by
543 * keys that can be removed from the keyspace. */
544 void activeExpireCycle(void) {
547 for (j
= 0; j
< server
.dbnum
; j
++) {
549 redisDb
*db
= server
.db
+j
;
551 /* Continue to expire if at the end of the cycle more than 25%
552 * of the keys were expired. */
554 long num
= dictSize(db
->expires
);
555 time_t now
= time(NULL
);
558 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
559 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
564 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
565 t
= (time_t) dictGetEntryVal(de
);
567 sds key
= dictGetEntryKey(de
);
568 robj
*keyobj
= createStringObject(key
,sdslen(key
));
570 propagateExpire(db
,keyobj
);
572 decrRefCount(keyobj
);
574 server
.stat_expiredkeys
++;
577 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
581 void updateLRUClock(void) {
582 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
586 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
587 int j
, loops
= server
.cronloops
;
588 REDIS_NOTUSED(eventLoop
);
590 REDIS_NOTUSED(clientData
);
592 /* We take a cached value of the unix time in the global state because
593 * with virtual memory and aging there is to store the current time
594 * in objects at every object access, and accuracy is not needed.
595 * To access a global var is faster than calling time(NULL) */
596 server
.unixtime
= time(NULL
);
598 /* We have just 22 bits per object for LRU information.
599 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
600 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
602 * Note that even if this will wrap after 1.5 years it's not a problem,
603 * everything will still work but just some object will appear younger
604 * to Redis. But for this to happen a given object should never be touched
607 * Note that you can change the resolution altering the
608 * REDIS_LRU_CLOCK_RESOLUTION define.
612 /* Record the max memory used since the server was started. */
613 if (zmalloc_used_memory() > server
.stat_peak_memory
)
614 server
.stat_peak_memory
= zmalloc_used_memory();
616 /* We received a SIGTERM, shutting down here in a safe way, as it is
617 * not ok doing so inside the signal handler. */
618 if (server
.shutdown_asap
) {
619 if (prepareForShutdown() == REDIS_OK
) exit(0);
620 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
623 /* Show some info about non-empty databases */
624 for (j
= 0; j
< server
.dbnum
; j
++) {
625 long long size
, used
, vkeys
;
627 size
= dictSlots(server
.db
[j
].dict
);
628 used
= dictSize(server
.db
[j
].dict
);
629 vkeys
= dictSize(server
.db
[j
].expires
);
630 if (!(loops
% 50) && (used
|| vkeys
)) {
631 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
632 /* dictPrintStats(server.dict); */
636 /* We don't want to resize the hash tables while a bacground saving
637 * is in progress: the saving child is created using fork() that is
638 * implemented with a copy-on-write semantic in most modern systems, so
639 * if we resize the HT while there is the saving child at work actually
640 * a lot of memory movements in the parent will cause a lot of pages
642 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
643 if (!(loops
% 10)) tryResizeHashTables();
644 if (server
.activerehashing
) incrementallyRehash();
647 /* Show information about connected clients */
649 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
650 listLength(server
.clients
)-listLength(server
.slaves
),
651 listLength(server
.slaves
),
652 zmalloc_used_memory());
655 /* Close connections of timedout clients */
656 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
657 closeTimedoutClients();
659 /* Start a scheduled AOF rewrite if this was requested by the user while
660 * a BGSAVE was in progress. */
661 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1 &&
662 server
.aofrewrite_scheduled
)
664 rewriteAppendOnlyFileBackground();
667 /* Check if a background saving or AOF rewrite in progress terminated. */
668 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
672 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
673 int exitcode
= WEXITSTATUS(statloc
);
676 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
678 if (pid
== server
.bgsavechildpid
) {
679 backgroundSaveDoneHandler(exitcode
,bysignal
);
681 backgroundRewriteDoneHandler(exitcode
,bysignal
);
683 updateDictResizePolicy();
686 time_t now
= time(NULL
);
688 /* If there is not a background saving/rewrite in progress check if
689 * we have to save/rewrite now */
690 for (j
= 0; j
< server
.saveparamslen
; j
++) {
691 struct saveparam
*sp
= server
.saveparams
+j
;
693 if (server
.dirty
>= sp
->changes
&&
694 now
-server
.lastsave
> sp
->seconds
) {
695 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
696 sp
->changes
, sp
->seconds
);
697 rdbSaveBackground(server
.dbfilename
);
702 /* Trigger an AOF rewrite if needed */
703 if (server
.bgsavechildpid
== -1 &&
704 server
.bgrewritechildpid
== -1 &&
705 server
.auto_aofrewrite_perc
&&
706 server
.appendonly_current_size
> server
.auto_aofrewrite_min_size
)
708 long long base
= server
.auto_aofrewrite_base_size
?
709 server
.auto_aofrewrite_base_size
: 1;
710 long long growth
= (server
.appendonly_current_size
*100/base
) - 100;
711 if (growth
>= server
.auto_aofrewrite_perc
) {
712 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
713 rewriteAppendOnlyFileBackground();
719 /* If we postponed an AOF buffer flush, let's try to do it every time the
720 * cron function is called. */
721 if (server
.aof_flush_postponed_start
) flushAppendOnlyFile(0);
723 /* Expire a few keys per cycle, only if this is a master.
724 * On slaves we wait for DEL operations synthesized by the master
725 * in order to guarantee a strict consistency. */
726 if (server
.masterhost
== NULL
) activeExpireCycle();
728 /* Replication cron function -- used to reconnect to master and
729 * to detect transfer failures. */
730 if (!(loops
% 10)) replicationCron();
732 /* Run other sub-systems specific cron jobs */
733 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
739 /* This function gets called every time Redis is entering the
740 * main loop of the event driven library, that is, before to sleep
741 * for ready file descriptors. */
742 void beforeSleep(struct aeEventLoop
*eventLoop
) {
743 REDIS_NOTUSED(eventLoop
);
747 /* Try to process pending commands for clients that were just unblocked. */
748 while (listLength(server
.unblocked_clients
)) {
749 ln
= listFirst(server
.unblocked_clients
);
750 redisAssert(ln
!= NULL
);
752 listDelNode(server
.unblocked_clients
,ln
);
753 c
->flags
&= ~REDIS_UNBLOCKED
;
755 /* Process remaining data in the input buffer. */
756 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
757 processInputBuffer(c
);
760 /* Write the AOF buffer on disk */
761 flushAppendOnlyFile(0);
764 /* =========================== Server initialization ======================== */
766 void createSharedObjects(void) {
769 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
770 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
771 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
772 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
773 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
774 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
775 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
776 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
777 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
778 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
779 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
780 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
781 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
782 "-ERR Operation against a key holding the wrong kind of value\r\n"));
783 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
784 "-ERR no such key\r\n"));
785 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
786 "-ERR syntax error\r\n"));
787 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
788 "-ERR source and destination objects are the same\r\n"));
789 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
790 "-ERR index out of range\r\n"));
791 shared
.noscripterr
= createObject(REDIS_STRING
,sdsnew(
792 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
793 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
794 "-LOADING Redis is loading the dataset in memory\r\n"));
795 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
796 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
797 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
798 shared
.select0
= createStringObject("select 0\r\n",10);
799 shared
.select1
= createStringObject("select 1\r\n",10);
800 shared
.select2
= createStringObject("select 2\r\n",10);
801 shared
.select3
= createStringObject("select 3\r\n",10);
802 shared
.select4
= createStringObject("select 4\r\n",10);
803 shared
.select5
= createStringObject("select 5\r\n",10);
804 shared
.select6
= createStringObject("select 6\r\n",10);
805 shared
.select7
= createStringObject("select 7\r\n",10);
806 shared
.select8
= createStringObject("select 8\r\n",10);
807 shared
.select9
= createStringObject("select 9\r\n",10);
808 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
809 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
810 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
811 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
812 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
813 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
814 shared
.mbulk3
= createStringObject("*3\r\n",4);
815 shared
.mbulk4
= createStringObject("*4\r\n",4);
816 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
817 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
818 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
822 void initServerConfig() {
823 server
.port
= REDIS_SERVERPORT
;
824 server
.bindaddr
= NULL
;
825 server
.unixsocket
= NULL
;
826 server
.unixsocketperm
= 0;
829 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
830 server
.verbosity
= REDIS_VERBOSE
;
831 server
.maxidletime
= REDIS_MAXIDLETIME
;
832 server
.saveparams
= NULL
;
834 server
.logfile
= NULL
; /* NULL = log on standard output */
835 server
.syslog_enabled
= 0;
836 server
.syslog_ident
= zstrdup("redis");
837 server
.syslog_facility
= LOG_LOCAL0
;
838 server
.daemonize
= 0;
839 server
.appendonly
= 0;
840 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
841 server
.no_appendfsync_on_rewrite
= 0;
842 server
.auto_aofrewrite_perc
= REDIS_AUTO_AOFREWRITE_PERC
;
843 server
.auto_aofrewrite_min_size
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
;
844 server
.auto_aofrewrite_base_size
= 0;
845 server
.aofrewrite_scheduled
= 0;
846 server
.lastfsync
= time(NULL
);
847 server
.appendfd
= -1;
848 server
.appendseldb
= -1; /* Make sure the first time will not match */
849 server
.aof_flush_postponed_start
= 0;
850 server
.pidfile
= zstrdup("/var/run/redis.pid");
851 server
.dbfilename
= zstrdup("dump.rdb");
852 server
.appendfilename
= zstrdup("appendonly.aof");
853 server
.requirepass
= NULL
;
854 server
.rdbcompression
= 1;
855 server
.activerehashing
= 1;
856 server
.maxclients
= 0;
857 server
.bpop_blocked_clients
= 0;
858 server
.maxmemory
= 0;
859 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
860 server
.maxmemory_samples
= 3;
861 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
862 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
863 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
864 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
865 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
866 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
867 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
868 server
.shutdown_asap
= 0;
869 server
.cluster_enabled
= 0;
870 server
.cluster
.configfile
= zstrdup("nodes.conf");
871 server
.lua_time_limit
= REDIS_LUA_TIME_LIMIT
;
874 resetServerSaveParams();
876 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
877 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
878 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
879 /* Replication related */
881 server
.masterauth
= NULL
;
882 server
.masterhost
= NULL
;
883 server
.masterport
= 6379;
884 server
.master
= NULL
;
885 server
.replstate
= REDIS_REPL_NONE
;
886 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
887 server
.repl_serve_stale_data
= 1;
888 server
.repl_down_since
= -1;
890 /* Double constants initialization */
892 R_PosInf
= 1.0/R_Zero
;
893 R_NegInf
= -1.0/R_Zero
;
894 R_Nan
= R_Zero
/R_Zero
;
896 /* Command table -- we intiialize it here as it is part of the
897 * initial configuration, since command names may be changed via
898 * redis.conf using the rename-command directive. */
899 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
900 populateCommandTable();
901 server
.delCommand
= lookupCommandByCString("del");
902 server
.multiCommand
= lookupCommandByCString("multi");
905 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
906 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
912 signal(SIGHUP
, SIG_IGN
);
913 signal(SIGPIPE
, SIG_IGN
);
914 setupSignalHandlers();
916 if (server
.syslog_enabled
) {
917 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
918 server
.syslog_facility
);
921 server
.clients
= listCreate();
922 server
.slaves
= listCreate();
923 server
.monitors
= listCreate();
924 server
.unblocked_clients
= listCreate();
926 createSharedObjects();
927 server
.el
= aeCreateEventLoop();
928 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
930 if (server
.port
!= 0) {
931 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
932 if (server
.ipfd
== ANET_ERR
) {
933 redisLog(REDIS_WARNING
, "Opening port %d: %s",
934 server
.port
, server
.neterr
);
938 if (server
.unixsocket
!= NULL
) {
939 unlink(server
.unixsocket
); /* don't care if this fails */
940 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
,server
.unixsocketperm
);
941 if (server
.sofd
== ANET_ERR
) {
942 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
946 if (server
.ipfd
< 0 && server
.sofd
< 0) {
947 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
950 for (j
= 0; j
< server
.dbnum
; j
++) {
951 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
952 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
953 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
954 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
957 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
958 server
.pubsub_patterns
= listCreate();
959 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
960 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
961 server
.cronloops
= 0;
962 server
.bgsavechildpid
= -1;
963 server
.bgrewritechildpid
= -1;
964 server
.bgrewritebuf
= sdsempty();
965 server
.aofbuf
= sdsempty();
966 server
.lastsave
= time(NULL
);
968 server
.stat_numcommands
= 0;
969 server
.stat_numconnections
= 0;
970 server
.stat_expiredkeys
= 0;
971 server
.stat_evictedkeys
= 0;
972 server
.stat_starttime
= time(NULL
);
973 server
.stat_keyspace_misses
= 0;
974 server
.stat_keyspace_hits
= 0;
975 server
.stat_peak_memory
= 0;
976 server
.stat_fork_time
= 0;
977 server
.unixtime
= time(NULL
);
978 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
979 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
980 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
981 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
982 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
984 if (server
.appendonly
) {
985 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
986 if (server
.appendfd
== -1) {
987 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
993 if (server
.cluster_enabled
) clusterInit();
997 srand(time(NULL
)^getpid());
1000 /* Populates the Redis Command Table starting from the hard coded list
1001 * we have on top of redis.c file. */
1002 void populateCommandTable(void) {
1004 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1006 for (j
= 0; j
< numcommands
; j
++) {
1007 struct redisCommand
*c
= redisCommandTable
+j
;
1008 char *f
= c
->sflags
;
1013 case 'w': c
->flags
|= REDIS_CMD_WRITE
; break;
1014 case 'r': c
->flags
|= REDIS_CMD_READONLY
; break;
1015 case 'm': c
->flags
|= REDIS_CMD_DENYOOM
; break;
1016 case 'a': c
->flags
|= REDIS_CMD_ADMIN
; break;
1017 case 'p': c
->flags
|= REDIS_CMD_PUBSUB
; break;
1018 case 'f': c
->flags
|= REDIS_CMD_FORCE_REPLICATION
; break;
1019 case 's': c
->flags
|= REDIS_CMD_NOSCRIPT
; break;
1020 case 'R': c
->flags
|= REDIS_CMD_RANDOM
; break;
1021 default: redisPanic("Unsupported command flag"); break;
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
) {
1060 long long dirty
, start
= ustime(), duration
;
1062 dirty
= server
.dirty
;
1064 dirty
= server
.dirty
-dirty
;
1065 duration
= ustime()-start
;
1066 c
->cmd
->microseconds
+= duration
;
1067 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1070 if (server
.appendonly
&& dirty
> 0)
1071 feedAppendOnlyFile(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1072 if ((dirty
> 0 || c
->cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1073 listLength(server
.slaves
))
1074 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1075 if (listLength(server
.monitors
))
1076 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1077 server
.stat_numcommands
++;
1080 /* If this function gets called we already read a whole
1081 * command, argments are in the client argv/argc fields.
1082 * processCommand() execute the command or prepare the
1083 * server for a bulk read from the client.
1085 * If 1 is returned the client is still alive and valid and
1086 * and other operations can be performed by the caller. Otherwise
1087 * if 0 is returned the client was destroied (i.e. after QUIT). */
1088 int processCommand(redisClient
*c
) {
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 as wrong arity, bad command name and so forth. */
1101 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1103 addReplyErrorFormat(c
,"unknown command '%s'",
1104 (char*)c
->argv
[0]->ptr
);
1106 } else if ((c
->cmd
->arity
> 0 && c
->cmd
->arity
!= c
->argc
) ||
1107 (c
->argc
< -c
->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
&& c
->cmd
->proc
!= authCommand
)
1116 addReplyError(c
,"operation not permitted");
1120 /* If cluster is enabled, redirect here */
1121 if (server
.cluster_enabled
&&
1122 !(c
->cmd
->getkeys_proc
== NULL
&& c
->cmd
->firstkey
== 0)) {
1125 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1126 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1130 clusterNode
*n
= getNodeByQuery(c
,c
->cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1132 addReplyError(c
,"Multi keys request invalid in cluster");
1134 } else if (n
!= server
.cluster
.myself
) {
1135 addReplySds(c
,sdscatprintf(sdsempty(),
1136 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1137 hashslot
,n
->ip
,n
->port
));
1143 /* Handle the maxmemory directive.
1145 * First we try to free some memory if possible (if there are volatile
1146 * keys in the dataset). If there are not the only thing we can do
1147 * is returning an error. */
1148 if (server
.maxmemory
) freeMemoryIfNeeded();
1149 if (server
.maxmemory
&& (c
->cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1150 zmalloc_used_memory() > server
.maxmemory
)
1152 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1156 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1157 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1159 c
->cmd
->proc
!= subscribeCommand
&&
1160 c
->cmd
->proc
!= unsubscribeCommand
&&
1161 c
->cmd
->proc
!= psubscribeCommand
&&
1162 c
->cmd
->proc
!= punsubscribeCommand
) {
1163 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1167 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1168 * we are a slave with a broken link with master. */
1169 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1170 server
.repl_serve_stale_data
== 0 &&
1171 c
->cmd
->proc
!= infoCommand
&& c
->cmd
->proc
!= slaveofCommand
)
1174 "link with MASTER is down and slave-serve-stale-data is set to no");
1178 /* Loading DB? Return an error if the command is not INFO */
1179 if (server
.loading
&& c
->cmd
->proc
!= infoCommand
) {
1180 addReply(c
, shared
.loadingerr
);
1184 /* Exec the command */
1185 if (c
->flags
& REDIS_MULTI
&&
1186 c
->cmd
->proc
!= execCommand
&& c
->cmd
->proc
!= discardCommand
&&
1187 c
->cmd
->proc
!= multiCommand
&& c
->cmd
->proc
!= watchCommand
)
1189 queueMultiCommand(c
);
1190 addReply(c
,shared
.queued
);
1197 /*================================== Shutdown =============================== */
1199 int prepareForShutdown() {
1200 redisLog(REDIS_WARNING
,"User requested shutdown...");
1201 /* Kill the saving child if there is a background saving in progress.
1202 We want to avoid race conditions, for instance our saving child may
1203 overwrite the synchronous saving did by SHUTDOWN. */
1204 if (server
.bgsavechildpid
!= -1) {
1205 redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!");
1206 kill(server
.bgsavechildpid
,SIGKILL
);
1207 rdbRemoveTempFile(server
.bgsavechildpid
);
1209 if (server
.appendonly
) {
1210 /* Kill the AOF saving child as the AOF we already have may be longer
1211 * but contains the full dataset anyway. */
1212 if (server
.bgrewritechildpid
!= -1) {
1213 redisLog(REDIS_WARNING
,
1214 "There is a child rewriting the AOF. Killing it!");
1215 kill(server
.bgrewritechildpid
,SIGKILL
);
1217 /* Append only file: fsync() the AOF and exit */
1218 redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file.");
1219 aof_fsync(server
.appendfd
);
1221 if (server
.saveparamslen
> 0) {
1222 redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting.");
1223 /* Snapshotting. Perform a SYNC SAVE and exit */
1224 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1225 /* Ooops.. error saving! The best we can do is to continue
1226 * operating. Note that if there was a background saving process,
1227 * in the next cron() Redis will be notified that the background
1228 * saving aborted, handling special stuff like slaves pending for
1229 * synchronization... */
1230 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit.");
1234 if (server
.daemonize
) {
1235 redisLog(REDIS_NOTICE
,"Removing the pid file.");
1236 unlink(server
.pidfile
);
1238 /* Close the listening sockets. Apparently this allows faster restarts. */
1239 if (server
.ipfd
!= -1) close(server
.ipfd
);
1240 if (server
.sofd
!= -1) close(server
.sofd
);
1241 if (server
.unixsocket
) {
1242 redisLog(REDIS_NOTICE
,"Removing the unix socket file.");
1243 unlink(server
.unixsocket
); /* don't care if this fails */
1246 redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye...");
1250 /*================================== Commands =============================== */
1252 void authCommand(redisClient
*c
) {
1253 if (!server
.requirepass
) {
1254 addReplyError(c
,"Client sent AUTH, but no password is set");
1255 } else if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1256 c
->authenticated
= 1;
1257 addReply(c
,shared
.ok
);
1259 c
->authenticated
= 0;
1260 addReplyError(c
,"invalid password");
1264 void pingCommand(redisClient
*c
) {
1265 addReply(c
,shared
.pong
);
1268 void echoCommand(redisClient
*c
) {
1269 addReplyBulk(c
,c
->argv
[1]);
1272 /* Convert an amount of bytes into a human readable string in the form
1273 * of 100B, 2G, 100M, 4K, and so forth. */
1274 void bytesToHuman(char *s
, unsigned long long n
) {
1279 sprintf(s
,"%lluB",n
);
1281 } else if (n
< (1024*1024)) {
1282 d
= (double)n
/(1024);
1283 sprintf(s
,"%.2fK",d
);
1284 } else if (n
< (1024LL*1024*1024)) {
1285 d
= (double)n
/(1024*1024);
1286 sprintf(s
,"%.2fM",d
);
1287 } else if (n
< (1024LL*1024*1024*1024)) {
1288 d
= (double)n
/(1024LL*1024*1024);
1289 sprintf(s
,"%.2fG",d
);
1293 /* Create the string returned by the INFO command. This is decoupled
1294 * by the INFO command itself as we need to report the same information
1295 * on memory corruption problems. */
1296 sds
genRedisInfoString(char *section
) {
1297 sds info
= sdsempty();
1298 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1300 struct rusage self_ru
, c_ru
;
1301 unsigned long lol
, bib
;
1302 int allsections
= 0, defsections
= 0;
1306 allsections
= strcasecmp(section
,"all") == 0;
1307 defsections
= strcasecmp(section
,"default") == 0;
1310 getrusage(RUSAGE_SELF
, &self_ru
);
1311 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1312 getClientsMaxBuffers(&lol
,&bib
);
1315 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1316 if (sections
++) info
= sdscat(info
,"\r\n");
1317 info
= sdscatprintf(info
,
1319 "redis_version:%s\r\n"
1320 "redis_git_sha1:%s\r\n"
1321 "redis_git_dirty:%d\r\n"
1323 "multiplexing_api:%s\r\n"
1324 "process_id:%ld\r\n"
1326 "uptime_in_seconds:%ld\r\n"
1327 "uptime_in_days:%ld\r\n"
1328 "lru_clock:%ld\r\n",
1331 strtol(redisGitDirty(),NULL
,10) > 0,
1332 (sizeof(long) == 8) ? "64" : "32",
1338 (unsigned long) server
.lruclock
);
1342 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1343 if (sections
++) info
= sdscat(info
,"\r\n");
1344 info
= sdscatprintf(info
,
1346 "connected_clients:%d\r\n"
1347 "client_longest_output_list:%lu\r\n"
1348 "client_biggest_input_buf:%lu\r\n"
1349 "blocked_clients:%d\r\n",
1350 listLength(server
.clients
)-listLength(server
.slaves
),
1352 server
.bpop_blocked_clients
);
1356 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1360 bytesToHuman(hmem
,zmalloc_used_memory());
1361 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1362 if (sections
++) info
= sdscat(info
,"\r\n");
1363 info
= sdscatprintf(info
,
1365 "used_memory:%zu\r\n"
1366 "used_memory_human:%s\r\n"
1367 "used_memory_rss:%zu\r\n"
1368 "used_memory_peak:%zu\r\n"
1369 "used_memory_peak_human:%s\r\n"
1370 "used_memory_lua:%lld\r\n"
1371 "mem_fragmentation_ratio:%.2f\r\n"
1372 "mem_allocator:%s\r\n",
1373 zmalloc_used_memory(),
1376 server
.stat_peak_memory
,
1378 ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL,
1379 zmalloc_get_fragmentation_ratio(),
1385 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1386 if (sections
++) info
= sdscat(info
,"\r\n");
1387 info
= sdscatprintf(info
,
1390 "aof_enabled:%d\r\n"
1391 "changes_since_last_save:%lld\r\n"
1392 "bgsave_in_progress:%d\r\n"
1393 "last_save_time:%ld\r\n"
1394 "bgrewriteaof_in_progress:%d\r\n",
1398 server
.bgsavechildpid
!= -1,
1400 server
.bgrewritechildpid
!= -1);
1402 if (server
.appendonly
) {
1403 info
= sdscatprintf(info
,
1404 "aof_current_size:%lld\r\n"
1405 "aof_base_size:%lld\r\n"
1406 "aof_pending_rewrite:%d\r\n",
1407 (long long) server
.appendonly_current_size
,
1408 (long long) server
.auto_aofrewrite_base_size
,
1409 server
.aofrewrite_scheduled
);
1412 if (server
.loading
) {
1414 time_t eta
, elapsed
;
1415 off_t remaining_bytes
= server
.loading_total_bytes
-
1416 server
.loading_loaded_bytes
;
1418 perc
= ((double)server
.loading_loaded_bytes
/
1419 server
.loading_total_bytes
) * 100;
1421 elapsed
= time(NULL
)-server
.loading_start_time
;
1423 eta
= 1; /* A fake 1 second figure if we don't have
1426 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1429 info
= sdscatprintf(info
,
1430 "loading_start_time:%ld\r\n"
1431 "loading_total_bytes:%llu\r\n"
1432 "loading_loaded_bytes:%llu\r\n"
1433 "loading_loaded_perc:%.2f\r\n"
1434 "loading_eta_seconds:%ld\r\n"
1435 ,(unsigned long) server
.loading_start_time
,
1436 (unsigned long long) server
.loading_total_bytes
,
1437 (unsigned long long) server
.loading_loaded_bytes
,
1445 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1446 if (sections
++) info
= sdscat(info
,"\r\n");
1447 info
= sdscatprintf(info
,
1449 "total_connections_received:%lld\r\n"
1450 "total_commands_processed:%lld\r\n"
1451 "expired_keys:%lld\r\n"
1452 "evicted_keys:%lld\r\n"
1453 "keyspace_hits:%lld\r\n"
1454 "keyspace_misses:%lld\r\n"
1455 "pubsub_channels:%ld\r\n"
1456 "pubsub_patterns:%u\r\n"
1457 "latest_fork_usec:%lld\r\n",
1458 server
.stat_numconnections
,
1459 server
.stat_numcommands
,
1460 server
.stat_expiredkeys
,
1461 server
.stat_evictedkeys
,
1462 server
.stat_keyspace_hits
,
1463 server
.stat_keyspace_misses
,
1464 dictSize(server
.pubsub_channels
),
1465 listLength(server
.pubsub_patterns
),
1466 server
.stat_fork_time
);
1470 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1471 if (sections
++) info
= sdscat(info
,"\r\n");
1472 info
= sdscatprintf(info
,
1475 server
.masterhost
== NULL
? "master" : "slave");
1476 if (server
.masterhost
) {
1477 info
= sdscatprintf(info
,
1478 "master_host:%s\r\n"
1479 "master_port:%d\r\n"
1480 "master_link_status:%s\r\n"
1481 "master_last_io_seconds_ago:%d\r\n"
1482 "master_sync_in_progress:%d\r\n"
1485 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1488 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1489 server
.replstate
== REDIS_REPL_TRANSFER
1492 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1493 info
= sdscatprintf(info
,
1494 "master_sync_left_bytes:%ld\r\n"
1495 "master_sync_last_io_seconds_ago:%d\r\n"
1496 ,(long)server
.repl_transfer_left
,
1497 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1501 if (server
.replstate
!= REDIS_REPL_CONNECTED
) {
1502 info
= sdscatprintf(info
,
1503 "master_link_down_since_seconds:%ld\r\n",
1504 (long)time(NULL
)-server
.repl_down_since
);
1507 info
= sdscatprintf(info
,
1508 "connected_slaves:%d\r\n",
1509 listLength(server
.slaves
));
1513 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1514 if (sections
++) info
= sdscat(info
,"\r\n");
1515 info
= sdscatprintf(info
,
1517 "used_cpu_sys:%.2f\r\n"
1518 "used_cpu_user:%.2f\r\n"
1519 "used_cpu_sys_children:%.2f\r\n"
1520 "used_cpu_user_children:%.2f\r\n",
1521 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1522 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1523 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1524 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000);
1528 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1529 if (sections
++) info
= sdscat(info
,"\r\n");
1530 info
= sdscatprintf(info
, "# Commandstats\r\n");
1531 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1532 for (j
= 0; j
< numcommands
; j
++) {
1533 struct redisCommand
*c
= redisCommandTable
+j
;
1535 if (!c
->calls
) continue;
1536 info
= sdscatprintf(info
,
1537 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1538 c
->name
, c
->calls
, c
->microseconds
,
1539 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1544 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1545 if (sections
++) info
= sdscat(info
,"\r\n");
1546 info
= sdscatprintf(info
,
1548 "cluster_enabled:%d\r\n",
1549 server
.cluster_enabled
);
1553 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1554 if (sections
++) info
= sdscat(info
,"\r\n");
1555 info
= sdscatprintf(info
, "# Keyspace\r\n");
1556 for (j
= 0; j
< server
.dbnum
; j
++) {
1557 long long keys
, vkeys
;
1559 keys
= dictSize(server
.db
[j
].dict
);
1560 vkeys
= dictSize(server
.db
[j
].expires
);
1561 if (keys
|| vkeys
) {
1562 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1570 void infoCommand(redisClient
*c
) {
1571 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1574 addReply(c
,shared
.syntaxerr
);
1577 sds info
= genRedisInfoString(section
);
1578 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1579 (unsigned long)sdslen(info
)));
1580 addReplySds(c
,info
);
1581 addReply(c
,shared
.crlf
);
1584 void monitorCommand(redisClient
*c
) {
1585 /* ignore MONITOR if aleady slave or in monitor mode */
1586 if (c
->flags
& REDIS_SLAVE
) return;
1588 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1590 listAddNodeTail(server
.monitors
,c
);
1591 addReply(c
,shared
.ok
);
1594 /* ============================ Maxmemory directive ======================== */
1596 /* This function gets called when 'maxmemory' is set on the config file to limit
1597 * the max memory used by the server, and we are out of memory.
1598 * This function will try to, in order:
1600 * - Free objects from the free list
1601 * - Try to remove keys with an EXPIRE set
1603 * It is not possible to free enough memory to reach used-memory < maxmemory
1604 * the server will start refusing commands that will enlarge even more the
1607 void freeMemoryIfNeeded(void) {
1608 /* Remove keys accordingly to the active policy as long as we are
1609 * over the memory limit. */
1610 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1612 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1613 int j
, k
, freed
= 0;
1615 for (j
= 0; j
< server
.dbnum
; j
++) {
1616 long bestval
= 0; /* just to prevent warning */
1618 struct dictEntry
*de
;
1619 redisDb
*db
= server
.db
+j
;
1622 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1623 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1625 dict
= server
.db
[j
].dict
;
1627 dict
= server
.db
[j
].expires
;
1629 if (dictSize(dict
) == 0) continue;
1631 /* volatile-random and allkeys-random policy */
1632 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1633 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1635 de
= dictGetRandomKey(dict
);
1636 bestkey
= dictGetEntryKey(de
);
1639 /* volatile-lru and allkeys-lru policy */
1640 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1641 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1643 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1648 de
= dictGetRandomKey(dict
);
1649 thiskey
= dictGetEntryKey(de
);
1650 /* When policy is volatile-lru we need an additonal lookup
1651 * to locate the real key, as dict is set to db->expires. */
1652 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1653 de
= dictFind(db
->dict
, thiskey
);
1654 o
= dictGetEntryVal(de
);
1655 thisval
= estimateObjectIdleTime(o
);
1657 /* Higher idle time is better candidate for deletion */
1658 if (bestkey
== NULL
|| thisval
> bestval
) {
1666 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1667 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1671 de
= dictGetRandomKey(dict
);
1672 thiskey
= dictGetEntryKey(de
);
1673 thisval
= (long) dictGetEntryVal(de
);
1675 /* Expire sooner (minor expire unix timestamp) is better
1676 * candidate for deletion */
1677 if (bestkey
== NULL
|| thisval
< bestval
) {
1684 /* Finally remove the selected key. */
1686 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1687 propagateExpire(db
,keyobj
);
1688 dbDelete(db
,keyobj
);
1689 server
.stat_evictedkeys
++;
1690 decrRefCount(keyobj
);
1694 if (!freed
) return; /* nothing to free... */
1698 /* =================================== Main! ================================ */
1701 int linuxOvercommitMemoryValue(void) {
1702 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1706 if (fgets(buf
,64,fp
) == NULL
) {
1715 void linuxOvercommitMemoryWarning(void) {
1716 if (linuxOvercommitMemoryValue() == 0) {
1717 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.");
1720 #endif /* __linux__ */
1722 void createPidFile(void) {
1723 /* Try to write the pid file in a best-effort way. */
1724 FILE *fp
= fopen(server
.pidfile
,"w");
1726 fprintf(fp
,"%d\n",(int)getpid());
1731 void daemonize(void) {
1734 if (fork() != 0) exit(0); /* parent exits */
1735 setsid(); /* create a new session */
1737 /* Every output goes to /dev/null. If Redis is daemonized but
1738 * the 'logfile' is set to 'stdout' in the configuration file
1739 * it will not log at all. */
1740 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1741 dup2(fd
, STDIN_FILENO
);
1742 dup2(fd
, STDOUT_FILENO
);
1743 dup2(fd
, STDERR_FILENO
);
1744 if (fd
> STDERR_FILENO
) close(fd
);
1749 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1750 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1755 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1756 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1760 void redisAsciiArt(void) {
1761 #include "asciilogo.h"
1762 char *buf
= zmalloc(1024*16);
1764 snprintf(buf
,1024*16,ascii_logo
,
1767 strtol(redisGitDirty(),NULL
,10) > 0,
1768 (sizeof(long) == 8) ? "64" : "32",
1769 server
.cluster_enabled
? "cluster" : "stand alone",
1773 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1777 int main(int argc
, char **argv
) {
1780 zmalloc_enable_thread_safeness();
1783 if (strcmp(argv
[1], "-v") == 0 ||
1784 strcmp(argv
[1], "--version") == 0) version();
1785 if (strcmp(argv
[1], "--help") == 0) usage();
1786 resetServerSaveParams();
1787 loadServerConfig(argv
[1]);
1788 } else if ((argc
> 2)) {
1791 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'");
1793 if (server
.daemonize
) daemonize();
1795 if (server
.daemonize
) createPidFile();
1797 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1799 linuxOvercommitMemoryWarning();
1802 if (server
.appendonly
) {
1803 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1804 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1806 if (rdbLoad(server
.dbfilename
) == REDIS_OK
) {
1807 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",
1808 (float)(ustime()-start
)/1000000);
1809 } else if (errno
!= ENOENT
) {
1810 redisLog(REDIS_WARNING
,"Fatal error loading the DB. Exiting.");
1814 if (server
.ipfd
> 0)
1815 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1816 if (server
.sofd
> 0)
1817 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1818 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1820 aeDeleteEventLoop(server
.el
);
1824 #ifdef HAVE_BACKTRACE
1825 static void *getMcontextEip(ucontext_t
*uc
) {
1826 #if defined(__FreeBSD__)
1827 return (void*) uc
->uc_mcontext
.mc_eip
;
1828 #elif defined(__dietlibc__)
1829 return (void*) uc
->uc_mcontext
.eip
;
1830 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1832 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1834 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1836 return (void*) uc
->uc_mcontext
->__ss
.__srr0
;
1838 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1839 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1840 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1842 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1844 #elif defined(__i386__)
1845 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1846 #elif defined(__X86_64__) || defined(__x86_64__)
1847 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1848 #elif defined(__ia64__) /* Linux IA64 */
1849 return (void*) uc
->uc_mcontext
.sc_ip
;
1855 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1857 char **messages
= NULL
;
1858 int i
, trace_size
= 0;
1859 ucontext_t
*uc
= (ucontext_t
*) secret
;
1861 struct sigaction act
;
1862 REDIS_NOTUSED(info
);
1864 redisLog(REDIS_WARNING
,
1865 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1866 infostring
= genRedisInfoString("all");
1867 redisLogRaw(REDIS_WARNING
, infostring
);
1868 /* It's not safe to sdsfree() the returned string under memory
1869 * corruption conditions. Let it leak as we are going to abort */
1871 trace_size
= backtrace(trace
, 100);
1872 /* overwrite sigaction with caller's address */
1873 if (getMcontextEip(uc
) != NULL
) {
1874 trace
[1] = getMcontextEip(uc
);
1876 messages
= backtrace_symbols(trace
, trace_size
);
1878 for (i
=1; i
<trace_size
; ++i
)
1879 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1881 /* free(messages); Don't call free() with possibly corrupted memory. */
1882 if (server
.daemonize
) unlink(server
.pidfile
);
1884 /* Make sure we exit with the right signal at the end. So for instance
1885 * the core will be dumped if enabled. */
1886 sigemptyset (&act
.sa_mask
);
1887 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1888 * is used. Otherwise, sa_handler is used */
1889 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1890 act
.sa_handler
= SIG_DFL
;
1891 sigaction (sig
, &act
, NULL
);
1894 #endif /* HAVE_BACKTRACE */
1896 static void sigtermHandler(int sig
) {
1899 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1900 server
.shutdown_asap
= 1;
1903 void setupSignalHandlers(void) {
1904 struct sigaction act
;
1906 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1907 * Otherwise, sa_handler is used. */
1908 sigemptyset(&act
.sa_mask
);
1909 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1910 act
.sa_handler
= sigtermHandler
;
1911 sigaction(SIGTERM
, &act
, NULL
);
1913 #ifdef HAVE_BACKTRACE
1914 sigemptyset(&act
.sa_mask
);
1915 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1916 act
.sa_sigaction
= sigsegvHandler
;
1917 sigaction(SIGSEGV
, &act
, NULL
);
1918 sigaction(SIGBUS
, &act
, NULL
);
1919 sigaction(SIGFPE
, &act
, NULL
);
1920 sigaction(SIGILL
, &act
, NULL
);