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 {"dump",dumpCommand
,2,"ar",0,NULL
,0,0,0,0,0},
213 {"object",objectCommand
,-2,"r",0,NULL
,0,0,0,0,0},
214 {"client",clientCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
215 {"eval",evalCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
216 {"evalsha",evalShaCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
217 {"slowlog",slowlogCommand
,-2,"r",0,NULL
,0,0,0,0,0}
220 /*============================ Utility functions ============================ */
222 /* Low level logging. To use only for very big messages, otherwise
223 * redisLog() is to prefer. */
224 void redisLogRaw(int level
, const char *msg
) {
225 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
226 const char *c
= ".-*#";
227 time_t now
= time(NULL
);
230 int rawmode
= (level
& REDIS_LOG_RAW
);
232 level
&= 0xff; /* clear flags */
233 if (level
< server
.verbosity
) return;
235 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
239 fprintf(fp
,"%s",msg
);
241 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
242 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
246 if (server
.logfile
) fclose(fp
);
248 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
251 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
252 * is used across the code. The raw version is only used in order to dump
253 * the INFO output on crash. */
254 void redisLog(int level
, const char *fmt
, ...) {
256 char msg
[REDIS_MAX_LOGMSG_LEN
];
258 if ((level
&0xff) < server
.verbosity
) return;
261 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
264 redisLogRaw(level
,msg
);
267 /* Redis generally does not try to recover from out of memory conditions
268 * when allocating objects or strings, it is not clear if it will be possible
269 * to report this condition to the client since the networking layer itself
270 * is based on heap allocation for send buffers, so we simply abort.
271 * At least the code will be simpler to read... */
272 void oom(const char *msg
) {
273 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
278 /* Return the UNIX time in microseconds */
279 long long ustime(void) {
283 gettimeofday(&tv
, NULL
);
284 ust
= ((long long)tv
.tv_sec
)*1000000;
289 /*====================== Hash table type implementation ==================== */
291 /* This is an hash table type that uses the SDS dynamic strings libary as
292 * keys and radis objects as values (objects can hold SDS strings,
295 void dictVanillaFree(void *privdata
, void *val
)
297 DICT_NOTUSED(privdata
);
301 void dictListDestructor(void *privdata
, void *val
)
303 DICT_NOTUSED(privdata
);
304 listRelease((list
*)val
);
307 int dictSdsKeyCompare(void *privdata
, const void *key1
,
311 DICT_NOTUSED(privdata
);
313 l1
= sdslen((sds
)key1
);
314 l2
= sdslen((sds
)key2
);
315 if (l1
!= l2
) return 0;
316 return memcmp(key1
, key2
, l1
) == 0;
319 /* A case insensitive version used for the command lookup table. */
320 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
323 DICT_NOTUSED(privdata
);
325 return strcasecmp(key1
, key2
) == 0;
328 void dictRedisObjectDestructor(void *privdata
, void *val
)
330 DICT_NOTUSED(privdata
);
332 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
336 void dictSdsDestructor(void *privdata
, void *val
)
338 DICT_NOTUSED(privdata
);
343 int dictObjKeyCompare(void *privdata
, const void *key1
,
346 const robj
*o1
= key1
, *o2
= key2
;
347 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
350 unsigned int dictObjHash(const void *key
) {
352 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
355 unsigned int dictSdsHash(const void *key
) {
356 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
359 unsigned int dictSdsCaseHash(const void *key
) {
360 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
363 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
366 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
369 if (o1
->encoding
== REDIS_ENCODING_INT
&&
370 o2
->encoding
== REDIS_ENCODING_INT
)
371 return o1
->ptr
== o2
->ptr
;
373 o1
= getDecodedObject(o1
);
374 o2
= getDecodedObject(o2
);
375 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
381 unsigned int dictEncObjHash(const void *key
) {
382 robj
*o
= (robj
*) key
;
384 if (o
->encoding
== REDIS_ENCODING_RAW
) {
385 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
387 if (o
->encoding
== REDIS_ENCODING_INT
) {
391 len
= ll2string(buf
,32,(long)o
->ptr
);
392 return dictGenHashFunction((unsigned char*)buf
, len
);
396 o
= getDecodedObject(o
);
397 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
404 /* Sets type hash table */
405 dictType setDictType
= {
406 dictEncObjHash
, /* hash function */
409 dictEncObjKeyCompare
, /* key compare */
410 dictRedisObjectDestructor
, /* key destructor */
411 NULL
/* val destructor */
414 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
415 dictType zsetDictType
= {
416 dictEncObjHash
, /* hash function */
419 dictEncObjKeyCompare
, /* key compare */
420 dictRedisObjectDestructor
, /* key destructor */
421 NULL
/* val destructor */
424 /* Db->dict, keys are sds strings, vals are Redis objects. */
425 dictType dbDictType
= {
426 dictSdsHash
, /* hash function */
429 dictSdsKeyCompare
, /* key compare */
430 dictSdsDestructor
, /* key destructor */
431 dictRedisObjectDestructor
/* val destructor */
435 dictType keyptrDictType
= {
436 dictSdsHash
, /* hash function */
439 dictSdsKeyCompare
, /* key compare */
440 NULL
, /* key destructor */
441 NULL
/* val destructor */
444 /* Command table. sds string -> command struct pointer. */
445 dictType commandTableDictType
= {
446 dictSdsCaseHash
, /* hash function */
449 dictSdsKeyCaseCompare
, /* key compare */
450 dictSdsDestructor
, /* key destructor */
451 NULL
/* val destructor */
454 /* Hash type hash table (note that small hashes are represented with zimpaps) */
455 dictType hashDictType
= {
456 dictEncObjHash
, /* hash function */
459 dictEncObjKeyCompare
, /* key compare */
460 dictRedisObjectDestructor
, /* key destructor */
461 dictRedisObjectDestructor
/* val destructor */
464 /* Keylist hash table type has unencoded redis objects as keys and
465 * lists as values. It's used for blocking operations (BLPOP) and to
466 * map swapped keys to a list of clients waiting for this keys to be loaded. */
467 dictType keylistDictType
= {
468 dictObjHash
, /* hash function */
471 dictObjKeyCompare
, /* key compare */
472 dictRedisObjectDestructor
, /* key destructor */
473 dictListDestructor
/* val destructor */
476 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
477 * clusterNode structures. */
478 dictType clusterNodesDictType
= {
479 dictSdsHash
, /* hash function */
482 dictSdsKeyCompare
, /* key compare */
483 dictSdsDestructor
, /* key destructor */
484 NULL
/* val destructor */
487 int htNeedsResize(dict
*dict
) {
488 long long size
, used
;
490 size
= dictSlots(dict
);
491 used
= dictSize(dict
);
492 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
493 (used
*100/size
< REDIS_HT_MINFILL
));
496 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
497 * we resize the hash table to save memory */
498 void tryResizeHashTables(void) {
501 for (j
= 0; j
< server
.dbnum
; j
++) {
502 if (htNeedsResize(server
.db
[j
].dict
))
503 dictResize(server
.db
[j
].dict
);
504 if (htNeedsResize(server
.db
[j
].expires
))
505 dictResize(server
.db
[j
].expires
);
509 /* Our hash table implementation performs rehashing incrementally while
510 * we write/read from the hash table. Still if the server is idle, the hash
511 * table will use two tables for a long time. So we try to use 1 millisecond
512 * of CPU time at every serverCron() loop in order to rehash some key. */
513 void incrementallyRehash(void) {
516 for (j
= 0; j
< server
.dbnum
; j
++) {
517 if (dictIsRehashing(server
.db
[j
].dict
)) {
518 dictRehashMilliseconds(server
.db
[j
].dict
,1);
519 break; /* already used our millisecond for this loop... */
524 /* This function is called once a background process of some kind terminates,
525 * as we want to avoid resizing the hash tables when there is a child in order
526 * to play well with copy-on-write (otherwise when a resize happens lots of
527 * memory pages are copied). The goal of this function is to update the ability
528 * for dict.c to resize the hash tables accordingly to the fact we have o not
530 void updateDictResizePolicy(void) {
531 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
537 /* ======================= Cron: called every 100 ms ======================== */
539 /* Try to expire a few timed out keys. The algorithm used is adaptive and
540 * will use few CPU cycles if there are few expiring keys, otherwise
541 * it will get more aggressive to avoid that too much memory is used by
542 * keys that can be removed from the keyspace. */
543 void activeExpireCycle(void) {
546 for (j
= 0; j
< server
.dbnum
; j
++) {
548 redisDb
*db
= server
.db
+j
;
550 /* Continue to expire if at the end of the cycle more than 25%
551 * of the keys were expired. */
553 long num
= dictSize(db
->expires
);
554 time_t now
= time(NULL
);
557 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
558 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
563 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
564 t
= (time_t) dictGetEntryVal(de
);
566 sds key
= dictGetEntryKey(de
);
567 robj
*keyobj
= createStringObject(key
,sdslen(key
));
569 propagateExpire(db
,keyobj
);
571 decrRefCount(keyobj
);
573 server
.stat_expiredkeys
++;
576 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
580 void updateLRUClock(void) {
581 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
585 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
586 int j
, loops
= server
.cronloops
;
587 REDIS_NOTUSED(eventLoop
);
589 REDIS_NOTUSED(clientData
);
591 /* We take a cached value of the unix time in the global state because
592 * with virtual memory and aging there is to store the current time
593 * in objects at every object access, and accuracy is not needed.
594 * To access a global var is faster than calling time(NULL) */
595 server
.unixtime
= time(NULL
);
597 /* We have just 22 bits per object for LRU information.
598 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
599 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
601 * Note that even if this will wrap after 1.5 years it's not a problem,
602 * everything will still work but just some object will appear younger
603 * to Redis. But for this to happen a given object should never be touched
606 * Note that you can change the resolution altering the
607 * REDIS_LRU_CLOCK_RESOLUTION define.
611 /* Record the max memory used since the server was started. */
612 if (zmalloc_used_memory() > server
.stat_peak_memory
)
613 server
.stat_peak_memory
= zmalloc_used_memory();
615 /* We received a SIGTERM, shutting down here in a safe way, as it is
616 * not ok doing so inside the signal handler. */
617 if (server
.shutdown_asap
) {
618 if (prepareForShutdown() == REDIS_OK
) exit(0);
619 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
622 /* Show some info about non-empty databases */
623 for (j
= 0; j
< server
.dbnum
; j
++) {
624 long long size
, used
, vkeys
;
626 size
= dictSlots(server
.db
[j
].dict
);
627 used
= dictSize(server
.db
[j
].dict
);
628 vkeys
= dictSize(server
.db
[j
].expires
);
629 if (!(loops
% 50) && (used
|| vkeys
)) {
630 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
631 /* dictPrintStats(server.dict); */
635 /* We don't want to resize the hash tables while a bacground saving
636 * is in progress: the saving child is created using fork() that is
637 * implemented with a copy-on-write semantic in most modern systems, so
638 * if we resize the HT while there is the saving child at work actually
639 * a lot of memory movements in the parent will cause a lot of pages
641 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
642 if (!(loops
% 10)) tryResizeHashTables();
643 if (server
.activerehashing
) incrementallyRehash();
646 /* Show information about connected clients */
648 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
649 listLength(server
.clients
)-listLength(server
.slaves
),
650 listLength(server
.slaves
),
651 zmalloc_used_memory());
654 /* Close connections of timedout clients */
655 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
656 closeTimedoutClients();
658 /* Start a scheduled AOF rewrite if this was requested by the user while
659 * a BGSAVE was in progress. */
660 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1 &&
661 server
.aofrewrite_scheduled
)
663 rewriteAppendOnlyFileBackground();
666 /* Check if a background saving or AOF rewrite in progress terminated. */
667 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
671 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
672 int exitcode
= WEXITSTATUS(statloc
);
675 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
677 if (pid
== server
.bgsavechildpid
) {
678 backgroundSaveDoneHandler(exitcode
,bysignal
);
680 backgroundRewriteDoneHandler(exitcode
,bysignal
);
682 updateDictResizePolicy();
685 time_t now
= time(NULL
);
687 /* If there is not a background saving/rewrite in progress check if
688 * we have to save/rewrite now */
689 for (j
= 0; j
< server
.saveparamslen
; j
++) {
690 struct saveparam
*sp
= server
.saveparams
+j
;
692 if (server
.dirty
>= sp
->changes
&&
693 now
-server
.lastsave
> sp
->seconds
) {
694 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
695 sp
->changes
, sp
->seconds
);
696 rdbSaveBackground(server
.dbfilename
);
701 /* Trigger an AOF rewrite if needed */
702 if (server
.bgsavechildpid
== -1 &&
703 server
.bgrewritechildpid
== -1 &&
704 server
.auto_aofrewrite_perc
&&
705 server
.appendonly_current_size
> server
.auto_aofrewrite_min_size
)
707 long long base
= server
.auto_aofrewrite_base_size
?
708 server
.auto_aofrewrite_base_size
: 1;
709 long long growth
= (server
.appendonly_current_size
*100/base
) - 100;
710 if (growth
>= server
.auto_aofrewrite_perc
) {
711 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
712 rewriteAppendOnlyFileBackground();
718 /* If we postponed an AOF buffer flush, let's try to do it every time the
719 * cron function is called. */
720 if (server
.aof_flush_postponed_start
) flushAppendOnlyFile(0);
722 /* Expire a few keys per cycle, only if this is a master.
723 * On slaves we wait for DEL operations synthesized by the master
724 * in order to guarantee a strict consistency. */
725 if (server
.masterhost
== NULL
) activeExpireCycle();
727 /* Replication cron function -- used to reconnect to master and
728 * to detect transfer failures. */
729 if (!(loops
% 10)) replicationCron();
731 /* Run other sub-systems specific cron jobs */
732 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
738 /* This function gets called every time Redis is entering the
739 * main loop of the event driven library, that is, before to sleep
740 * for ready file descriptors. */
741 void beforeSleep(struct aeEventLoop
*eventLoop
) {
742 REDIS_NOTUSED(eventLoop
);
746 /* Try to process pending commands for clients that were just unblocked. */
747 while (listLength(server
.unblocked_clients
)) {
748 ln
= listFirst(server
.unblocked_clients
);
749 redisAssert(ln
!= NULL
);
751 listDelNode(server
.unblocked_clients
,ln
);
752 c
->flags
&= ~REDIS_UNBLOCKED
;
754 /* Process remaining data in the input buffer. */
755 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
756 processInputBuffer(c
);
759 /* Write the AOF buffer on disk */
760 flushAppendOnlyFile(0);
763 /* =========================== Server initialization ======================== */
765 void createSharedObjects(void) {
768 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
769 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
770 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
771 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
772 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
773 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
774 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
775 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
776 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
777 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
778 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
779 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
780 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
781 "-ERR Operation against a key holding the wrong kind of value\r\n"));
782 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
783 "-ERR no such key\r\n"));
784 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
785 "-ERR syntax error\r\n"));
786 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
787 "-ERR source and destination objects are the same\r\n"));
788 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
789 "-ERR index out of range\r\n"));
790 shared
.noscripterr
= createObject(REDIS_STRING
,sdsnew(
791 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
792 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
793 "-LOADING Redis is loading the dataset in memory\r\n"));
794 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
795 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
796 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
797 shared
.select0
= createStringObject("select 0\r\n",10);
798 shared
.select1
= createStringObject("select 1\r\n",10);
799 shared
.select2
= createStringObject("select 2\r\n",10);
800 shared
.select3
= createStringObject("select 3\r\n",10);
801 shared
.select4
= createStringObject("select 4\r\n",10);
802 shared
.select5
= createStringObject("select 5\r\n",10);
803 shared
.select6
= createStringObject("select 6\r\n",10);
804 shared
.select7
= createStringObject("select 7\r\n",10);
805 shared
.select8
= createStringObject("select 8\r\n",10);
806 shared
.select9
= createStringObject("select 9\r\n",10);
807 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
808 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
809 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
810 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
811 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
812 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
813 shared
.mbulk3
= createStringObject("*3\r\n",4);
814 shared
.mbulk4
= createStringObject("*4\r\n",4);
815 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
816 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
817 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
821 void initServerConfig() {
822 server
.port
= REDIS_SERVERPORT
;
823 server
.bindaddr
= NULL
;
824 server
.unixsocket
= NULL
;
827 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
828 server
.verbosity
= REDIS_VERBOSE
;
829 server
.maxidletime
= REDIS_MAXIDLETIME
;
830 server
.saveparams
= NULL
;
832 server
.logfile
= NULL
; /* NULL = log on standard output */
833 server
.syslog_enabled
= 0;
834 server
.syslog_ident
= zstrdup("redis");
835 server
.syslog_facility
= LOG_LOCAL0
;
836 server
.daemonize
= 0;
837 server
.appendonly
= 0;
838 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
839 server
.no_appendfsync_on_rewrite
= 0;
840 server
.auto_aofrewrite_perc
= REDIS_AUTO_AOFREWRITE_PERC
;
841 server
.auto_aofrewrite_min_size
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
;
842 server
.auto_aofrewrite_base_size
= 0;
843 server
.aofrewrite_scheduled
= 0;
844 server
.lastfsync
= time(NULL
);
845 server
.appendfd
= -1;
846 server
.appendseldb
= -1; /* Make sure the first time will not match */
847 server
.aof_flush_postponed_start
= 0;
848 server
.pidfile
= zstrdup("/var/run/redis.pid");
849 server
.dbfilename
= zstrdup("dump.rdb");
850 server
.appendfilename
= zstrdup("appendonly.aof");
851 server
.requirepass
= NULL
;
852 server
.rdbcompression
= 1;
853 server
.activerehashing
= 1;
854 server
.maxclients
= 0;
855 server
.bpop_blocked_clients
= 0;
856 server
.maxmemory
= 0;
857 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
858 server
.maxmemory_samples
= 3;
859 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
860 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
861 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
862 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
863 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
864 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
865 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
866 server
.shutdown_asap
= 0;
867 server
.cluster_enabled
= 0;
868 server
.cluster
.configfile
= zstrdup("nodes.conf");
869 server
.lua_time_limit
= REDIS_LUA_TIME_LIMIT
;
872 resetServerSaveParams();
874 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
875 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
876 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
877 /* Replication related */
879 server
.masterauth
= NULL
;
880 server
.masterhost
= NULL
;
881 server
.masterport
= 6379;
882 server
.master
= NULL
;
883 server
.replstate
= REDIS_REPL_NONE
;
884 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
885 server
.repl_serve_stale_data
= 1;
886 server
.repl_down_since
= -1;
888 /* Double constants initialization */
890 R_PosInf
= 1.0/R_Zero
;
891 R_NegInf
= -1.0/R_Zero
;
892 R_Nan
= R_Zero
/R_Zero
;
894 /* Command table -- we intiialize it here as it is part of the
895 * initial configuration, since command names may be changed via
896 * redis.conf using the rename-command directive. */
897 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
898 populateCommandTable();
899 server
.delCommand
= lookupCommandByCString("del");
900 server
.multiCommand
= lookupCommandByCString("multi");
903 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
904 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
910 signal(SIGHUP
, SIG_IGN
);
911 signal(SIGPIPE
, SIG_IGN
);
912 setupSignalHandlers();
914 if (server
.syslog_enabled
) {
915 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
916 server
.syslog_facility
);
919 server
.clients
= listCreate();
920 server
.slaves
= listCreate();
921 server
.monitors
= listCreate();
922 server
.unblocked_clients
= listCreate();
924 createSharedObjects();
925 server
.el
= aeCreateEventLoop();
926 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
928 if (server
.port
!= 0) {
929 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
930 if (server
.ipfd
== ANET_ERR
) {
931 redisLog(REDIS_WARNING
, "Opening port %d: %s",
932 server
.port
, server
.neterr
);
936 if (server
.unixsocket
!= NULL
) {
937 unlink(server
.unixsocket
); /* don't care if this fails */
938 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
939 if (server
.sofd
== ANET_ERR
) {
940 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
944 if (server
.ipfd
< 0 && server
.sofd
< 0) {
945 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
948 for (j
= 0; j
< server
.dbnum
; j
++) {
949 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
950 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
951 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
952 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
955 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
956 server
.pubsub_patterns
= listCreate();
957 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
958 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
959 server
.cronloops
= 0;
960 server
.bgsavechildpid
= -1;
961 server
.bgrewritechildpid
= -1;
962 server
.bgrewritebuf
= sdsempty();
963 server
.aofbuf
= sdsempty();
964 server
.lastsave
= time(NULL
);
966 server
.stat_numcommands
= 0;
967 server
.stat_numconnections
= 0;
968 server
.stat_expiredkeys
= 0;
969 server
.stat_evictedkeys
= 0;
970 server
.stat_starttime
= time(NULL
);
971 server
.stat_keyspace_misses
= 0;
972 server
.stat_keyspace_hits
= 0;
973 server
.stat_peak_memory
= 0;
974 server
.stat_fork_time
= 0;
975 server
.unixtime
= time(NULL
);
976 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
977 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
978 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
979 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
980 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
982 if (server
.appendonly
) {
983 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
984 if (server
.appendfd
== -1) {
985 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
991 if (server
.cluster_enabled
) clusterInit();
995 srand(time(NULL
)^getpid());
998 /* Populates the Redis Command Table starting from the hard coded list
999 * we have on top of redis.c file. */
1000 void populateCommandTable(void) {
1002 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1004 for (j
= 0; j
< numcommands
; j
++) {
1005 struct redisCommand
*c
= redisCommandTable
+j
;
1006 char *f
= c
->sflags
;
1011 case 'w': c
->flags
|= REDIS_CMD_WRITE
; break;
1012 case 'r': c
->flags
|= REDIS_CMD_READONLY
; break;
1013 case 'm': c
->flags
|= REDIS_CMD_DENYOOM
; break;
1014 case 'a': c
->flags
|= REDIS_CMD_ADMIN
; break;
1015 case 'p': c
->flags
|= REDIS_CMD_PUBSUB
; break;
1016 case 'f': c
->flags
|= REDIS_CMD_FORCE_REPLICATION
; break;
1017 case 's': c
->flags
|= REDIS_CMD_NOSCRIPT
; break;
1018 case 'R': c
->flags
|= REDIS_CMD_RANDOM
; break;
1019 default: redisPanic("Unsupported command flag"); break;
1024 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
1025 assert(retval
== DICT_OK
);
1029 void resetCommandTableStats(void) {
1030 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1033 for (j
= 0; j
< numcommands
; j
++) {
1034 struct redisCommand
*c
= redisCommandTable
+j
;
1036 c
->microseconds
= 0;
1041 /* ====================== Commands lookup and execution ===================== */
1043 struct redisCommand
*lookupCommand(sds name
) {
1044 return dictFetchValue(server
.commands
, name
);
1047 struct redisCommand
*lookupCommandByCString(char *s
) {
1048 struct redisCommand
*cmd
;
1049 sds name
= sdsnew(s
);
1051 cmd
= dictFetchValue(server
.commands
, name
);
1056 /* Call() is the core of Redis execution of a command */
1057 void call(redisClient
*c
) {
1058 long long dirty
, start
= ustime(), duration
;
1060 dirty
= server
.dirty
;
1062 dirty
= server
.dirty
-dirty
;
1063 duration
= ustime()-start
;
1064 c
->cmd
->microseconds
+= duration
;
1065 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1068 if (server
.appendonly
&& dirty
> 0)
1069 feedAppendOnlyFile(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1070 if ((dirty
> 0 || c
->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 /* The QUIT command is handled separately. Normal command procs will
1088 * go through checking for replication and QUIT will cause trouble
1089 * when FORCE_REPLICATION is enabled and would be implemented in
1090 * a regular command proc. */
1091 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1092 addReply(c
,shared
.ok
);
1093 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1097 /* Now lookup the command and check ASAP about trivial error conditions
1098 * such as wrong arity, bad command name and so forth. */
1099 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1101 addReplyErrorFormat(c
,"unknown command '%s'",
1102 (char*)c
->argv
[0]->ptr
);
1104 } else if ((c
->cmd
->arity
> 0 && c
->cmd
->arity
!= c
->argc
) ||
1105 (c
->argc
< -c
->cmd
->arity
)) {
1106 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1111 /* Check if the user is authenticated */
1112 if (server
.requirepass
&& !c
->authenticated
&& c
->cmd
->proc
!= authCommand
)
1114 addReplyError(c
,"operation not permitted");
1118 /* If cluster is enabled, redirect here */
1119 if (server
.cluster_enabled
&&
1120 !(c
->cmd
->getkeys_proc
== NULL
&& c
->cmd
->firstkey
== 0)) {
1123 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1124 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1128 clusterNode
*n
= getNodeByQuery(c
,c
->cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1130 addReplyError(c
,"Multi keys request invalid in cluster");
1132 } else if (n
!= server
.cluster
.myself
) {
1133 addReplySds(c
,sdscatprintf(sdsempty(),
1134 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1135 hashslot
,n
->ip
,n
->port
));
1141 /* Handle the maxmemory directive.
1143 * First we try to free some memory if possible (if there are volatile
1144 * keys in the dataset). If there are not the only thing we can do
1145 * is returning an error. */
1146 if (server
.maxmemory
) freeMemoryIfNeeded();
1147 if (server
.maxmemory
&& (c
->cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1148 zmalloc_used_memory() > server
.maxmemory
)
1150 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1154 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1155 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1157 c
->cmd
->proc
!= subscribeCommand
&&
1158 c
->cmd
->proc
!= unsubscribeCommand
&&
1159 c
->cmd
->proc
!= psubscribeCommand
&&
1160 c
->cmd
->proc
!= punsubscribeCommand
) {
1161 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1165 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1166 * we are a slave with a broken link with master. */
1167 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1168 server
.repl_serve_stale_data
== 0 &&
1169 c
->cmd
->proc
!= infoCommand
&& c
->cmd
->proc
!= slaveofCommand
)
1172 "link with MASTER is down and slave-serve-stale-data is set to no");
1176 /* Loading DB? Return an error if the command is not INFO */
1177 if (server
.loading
&& c
->cmd
->proc
!= infoCommand
) {
1178 addReply(c
, shared
.loadingerr
);
1182 /* Exec the command */
1183 if (c
->flags
& REDIS_MULTI
&&
1184 c
->cmd
->proc
!= execCommand
&& c
->cmd
->proc
!= discardCommand
&&
1185 c
->cmd
->proc
!= multiCommand
&& c
->cmd
->proc
!= watchCommand
)
1187 queueMultiCommand(c
);
1188 addReply(c
,shared
.queued
);
1195 /*================================== Shutdown =============================== */
1197 int prepareForShutdown() {
1198 redisLog(REDIS_WARNING
,"User requested shutdown...");
1199 /* Kill the saving child if there is a background saving in progress.
1200 We want to avoid race conditions, for instance our saving child may
1201 overwrite the synchronous saving did by SHUTDOWN. */
1202 if (server
.bgsavechildpid
!= -1) {
1203 redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!");
1204 kill(server
.bgsavechildpid
,SIGKILL
);
1205 rdbRemoveTempFile(server
.bgsavechildpid
);
1207 if (server
.appendonly
) {
1208 /* Kill the AOF saving child as the AOF we already have may be longer
1209 * but contains the full dataset anyway. */
1210 if (server
.bgrewritechildpid
!= -1) {
1211 redisLog(REDIS_WARNING
,
1212 "There is a child rewriting the AOF. Killing it!");
1213 kill(server
.bgrewritechildpid
,SIGKILL
);
1215 /* Append only file: fsync() the AOF and exit */
1216 redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file.");
1217 aof_fsync(server
.appendfd
);
1219 if (server
.saveparamslen
> 0) {
1220 redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting.");
1221 /* Snapshotting. Perform a SYNC SAVE and exit */
1222 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1223 /* Ooops.. error saving! The best we can do is to continue
1224 * operating. Note that if there was a background saving process,
1225 * in the next cron() Redis will be notified that the background
1226 * saving aborted, handling special stuff like slaves pending for
1227 * synchronization... */
1228 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit.");
1232 if (server
.daemonize
) {
1233 redisLog(REDIS_NOTICE
,"Removing the pid file.");
1234 unlink(server
.pidfile
);
1236 /* Close the listening sockets. Apparently this allows faster restarts. */
1237 if (server
.ipfd
!= -1) close(server
.ipfd
);
1238 if (server
.sofd
!= -1) close(server
.sofd
);
1240 redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye...");
1244 /*================================== Commands =============================== */
1246 void authCommand(redisClient
*c
) {
1247 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1248 c
->authenticated
= 1;
1249 addReply(c
,shared
.ok
);
1251 c
->authenticated
= 0;
1252 addReplyError(c
,"invalid password");
1256 void pingCommand(redisClient
*c
) {
1257 addReply(c
,shared
.pong
);
1260 void echoCommand(redisClient
*c
) {
1261 addReplyBulk(c
,c
->argv
[1]);
1264 /* Convert an amount of bytes into a human readable string in the form
1265 * of 100B, 2G, 100M, 4K, and so forth. */
1266 void bytesToHuman(char *s
, unsigned long long n
) {
1271 sprintf(s
,"%lluB",n
);
1273 } else if (n
< (1024*1024)) {
1274 d
= (double)n
/(1024);
1275 sprintf(s
,"%.2fK",d
);
1276 } else if (n
< (1024LL*1024*1024)) {
1277 d
= (double)n
/(1024*1024);
1278 sprintf(s
,"%.2fM",d
);
1279 } else if (n
< (1024LL*1024*1024*1024)) {
1280 d
= (double)n
/(1024LL*1024*1024);
1281 sprintf(s
,"%.2fG",d
);
1285 /* Create the string returned by the INFO command. This is decoupled
1286 * by the INFO command itself as we need to report the same information
1287 * on memory corruption problems. */
1288 sds
genRedisInfoString(char *section
) {
1289 sds info
= sdsempty();
1290 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1292 struct rusage self_ru
, c_ru
;
1293 unsigned long lol
, bib
;
1294 int allsections
= 0, defsections
= 0;
1298 allsections
= strcasecmp(section
,"all") == 0;
1299 defsections
= strcasecmp(section
,"default") == 0;
1302 getrusage(RUSAGE_SELF
, &self_ru
);
1303 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1304 getClientsMaxBuffers(&lol
,&bib
);
1307 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1308 if (sections
++) info
= sdscat(info
,"\r\n");
1309 info
= sdscatprintf(info
,
1311 "redis_version:%s\r\n"
1312 "redis_git_sha1:%s\r\n"
1313 "redis_git_dirty:%d\r\n"
1315 "multiplexing_api:%s\r\n"
1316 "process_id:%ld\r\n"
1318 "uptime_in_seconds:%ld\r\n"
1319 "uptime_in_days:%ld\r\n"
1320 "lru_clock:%ld\r\n",
1323 strtol(redisGitDirty(),NULL
,10) > 0,
1324 (sizeof(long) == 8) ? "64" : "32",
1330 (unsigned long) server
.lruclock
);
1334 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1335 if (sections
++) info
= sdscat(info
,"\r\n");
1336 info
= sdscatprintf(info
,
1338 "connected_clients:%d\r\n"
1339 "client_longest_output_list:%lu\r\n"
1340 "client_biggest_input_buf:%lu\r\n"
1341 "blocked_clients:%d\r\n",
1342 listLength(server
.clients
)-listLength(server
.slaves
),
1344 server
.bpop_blocked_clients
);
1348 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1352 bytesToHuman(hmem
,zmalloc_used_memory());
1353 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1354 if (sections
++) info
= sdscat(info
,"\r\n");
1355 info
= sdscatprintf(info
,
1357 "used_memory:%zu\r\n"
1358 "used_memory_human:%s\r\n"
1359 "used_memory_rss:%zu\r\n"
1360 "used_memory_peak:%zu\r\n"
1361 "used_memory_peak_human:%s\r\n"
1362 "used_memory_lua:%lld\r\n"
1363 "mem_fragmentation_ratio:%.2f\r\n"
1364 "mem_allocator:%s\r\n",
1365 zmalloc_used_memory(),
1368 server
.stat_peak_memory
,
1370 ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL,
1371 zmalloc_get_fragmentation_ratio(),
1377 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1378 if (sections
++) info
= sdscat(info
,"\r\n");
1379 info
= sdscatprintf(info
,
1382 "aof_enabled:%d\r\n"
1383 "changes_since_last_save:%lld\r\n"
1384 "bgsave_in_progress:%d\r\n"
1385 "last_save_time:%ld\r\n"
1386 "bgrewriteaof_in_progress:%d\r\n",
1390 server
.bgsavechildpid
!= -1,
1392 server
.bgrewritechildpid
!= -1);
1394 if (server
.appendonly
) {
1395 info
= sdscatprintf(info
,
1396 "aof_current_size:%lld\r\n"
1397 "aof_base_size:%lld\r\n"
1398 "aof_pending_rewrite:%d\r\n",
1399 (long long) server
.appendonly_current_size
,
1400 (long long) server
.auto_aofrewrite_base_size
,
1401 server
.aofrewrite_scheduled
);
1404 if (server
.loading
) {
1406 time_t eta
, elapsed
;
1407 off_t remaining_bytes
= server
.loading_total_bytes
-
1408 server
.loading_loaded_bytes
;
1410 perc
= ((double)server
.loading_loaded_bytes
/
1411 server
.loading_total_bytes
) * 100;
1413 elapsed
= time(NULL
)-server
.loading_start_time
;
1415 eta
= 1; /* A fake 1 second figure if we don't have
1418 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1421 info
= sdscatprintf(info
,
1422 "loading_start_time:%ld\r\n"
1423 "loading_total_bytes:%llu\r\n"
1424 "loading_loaded_bytes:%llu\r\n"
1425 "loading_loaded_perc:%.2f\r\n"
1426 "loading_eta_seconds:%ld\r\n"
1427 ,(unsigned long) server
.loading_start_time
,
1428 (unsigned long long) server
.loading_total_bytes
,
1429 (unsigned long long) server
.loading_loaded_bytes
,
1437 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1438 if (sections
++) info
= sdscat(info
,"\r\n");
1439 info
= sdscatprintf(info
,
1441 "total_connections_received:%lld\r\n"
1442 "total_commands_processed:%lld\r\n"
1443 "expired_keys:%lld\r\n"
1444 "evicted_keys:%lld\r\n"
1445 "keyspace_hits:%lld\r\n"
1446 "keyspace_misses:%lld\r\n"
1447 "pubsub_channels:%ld\r\n"
1448 "pubsub_patterns:%u\r\n"
1449 "latest_fork_usec:%lld\r\n",
1450 server
.stat_numconnections
,
1451 server
.stat_numcommands
,
1452 server
.stat_expiredkeys
,
1453 server
.stat_evictedkeys
,
1454 server
.stat_keyspace_hits
,
1455 server
.stat_keyspace_misses
,
1456 dictSize(server
.pubsub_channels
),
1457 listLength(server
.pubsub_patterns
),
1458 server
.stat_fork_time
);
1462 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1463 if (sections
++) info
= sdscat(info
,"\r\n");
1464 info
= sdscatprintf(info
,
1467 server
.masterhost
== NULL
? "master" : "slave");
1468 if (server
.masterhost
) {
1469 info
= sdscatprintf(info
,
1470 "master_host:%s\r\n"
1471 "master_port:%d\r\n"
1472 "master_link_status:%s\r\n"
1473 "master_last_io_seconds_ago:%d\r\n"
1474 "master_sync_in_progress:%d\r\n"
1477 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1480 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1481 server
.replstate
== REDIS_REPL_TRANSFER
1484 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1485 info
= sdscatprintf(info
,
1486 "master_sync_left_bytes:%ld\r\n"
1487 "master_sync_last_io_seconds_ago:%d\r\n"
1488 ,(long)server
.repl_transfer_left
,
1489 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1493 if (server
.replstate
!= REDIS_REPL_CONNECTED
) {
1494 info
= sdscatprintf(info
,
1495 "master_link_down_since_seconds:%ld\r\n",
1496 (long)time(NULL
)-server
.repl_down_since
);
1499 info
= sdscatprintf(info
,
1500 "connected_slaves:%d\r\n",
1501 listLength(server
.slaves
));
1505 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1506 if (sections
++) info
= sdscat(info
,"\r\n");
1507 info
= sdscatprintf(info
,
1509 "used_cpu_sys:%.2f\r\n"
1510 "used_cpu_user:%.2f\r\n"
1511 "used_cpu_sys_children:%.2f\r\n"
1512 "used_cpu_user_children:%.2f\r\n",
1513 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1514 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1515 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1516 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000);
1520 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1521 if (sections
++) info
= sdscat(info
,"\r\n");
1522 info
= sdscatprintf(info
, "# Commandstats\r\n");
1523 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1524 for (j
= 0; j
< numcommands
; j
++) {
1525 struct redisCommand
*c
= redisCommandTable
+j
;
1527 if (!c
->calls
) continue;
1528 info
= sdscatprintf(info
,
1529 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1530 c
->name
, c
->calls
, c
->microseconds
,
1531 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1536 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1537 if (sections
++) info
= sdscat(info
,"\r\n");
1538 info
= sdscatprintf(info
,
1540 "cluster_enabled:%d\r\n",
1541 server
.cluster_enabled
);
1545 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1546 if (sections
++) info
= sdscat(info
,"\r\n");
1547 info
= sdscatprintf(info
, "# Keyspace\r\n");
1548 for (j
= 0; j
< server
.dbnum
; j
++) {
1549 long long keys
, vkeys
;
1551 keys
= dictSize(server
.db
[j
].dict
);
1552 vkeys
= dictSize(server
.db
[j
].expires
);
1553 if (keys
|| vkeys
) {
1554 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1562 void infoCommand(redisClient
*c
) {
1563 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1566 addReply(c
,shared
.syntaxerr
);
1569 sds info
= genRedisInfoString(section
);
1570 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1571 (unsigned long)sdslen(info
)));
1572 addReplySds(c
,info
);
1573 addReply(c
,shared
.crlf
);
1576 void monitorCommand(redisClient
*c
) {
1577 /* ignore MONITOR if aleady slave or in monitor mode */
1578 if (c
->flags
& REDIS_SLAVE
) return;
1580 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1582 listAddNodeTail(server
.monitors
,c
);
1583 addReply(c
,shared
.ok
);
1586 /* ============================ Maxmemory directive ======================== */
1588 /* This function gets called when 'maxmemory' is set on the config file to limit
1589 * the max memory used by the server, and we are out of memory.
1590 * This function will try to, in order:
1592 * - Free objects from the free list
1593 * - Try to remove keys with an EXPIRE set
1595 * It is not possible to free enough memory to reach used-memory < maxmemory
1596 * the server will start refusing commands that will enlarge even more the
1599 void freeMemoryIfNeeded(void) {
1600 /* Remove keys accordingly to the active policy as long as we are
1601 * over the memory limit. */
1602 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1604 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1605 int j
, k
, freed
= 0;
1607 for (j
= 0; j
< server
.dbnum
; j
++) {
1608 long bestval
= 0; /* just to prevent warning */
1610 struct dictEntry
*de
;
1611 redisDb
*db
= server
.db
+j
;
1614 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1615 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1617 dict
= server
.db
[j
].dict
;
1619 dict
= server
.db
[j
].expires
;
1621 if (dictSize(dict
) == 0) continue;
1623 /* volatile-random and allkeys-random policy */
1624 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1625 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1627 de
= dictGetRandomKey(dict
);
1628 bestkey
= dictGetEntryKey(de
);
1631 /* volatile-lru and allkeys-lru policy */
1632 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1633 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1635 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1640 de
= dictGetRandomKey(dict
);
1641 thiskey
= dictGetEntryKey(de
);
1642 /* When policy is volatile-lru we need an additonal lookup
1643 * to locate the real key, as dict is set to db->expires. */
1644 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1645 de
= dictFind(db
->dict
, thiskey
);
1646 o
= dictGetEntryVal(de
);
1647 thisval
= estimateObjectIdleTime(o
);
1649 /* Higher idle time is better candidate for deletion */
1650 if (bestkey
== NULL
|| thisval
> bestval
) {
1658 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1659 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1663 de
= dictGetRandomKey(dict
);
1664 thiskey
= dictGetEntryKey(de
);
1665 thisval
= (long) dictGetEntryVal(de
);
1667 /* Expire sooner (minor expire unix timestamp) is better
1668 * candidate for deletion */
1669 if (bestkey
== NULL
|| thisval
< bestval
) {
1676 /* Finally remove the selected key. */
1678 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1679 propagateExpire(db
,keyobj
);
1680 dbDelete(db
,keyobj
);
1681 server
.stat_evictedkeys
++;
1682 decrRefCount(keyobj
);
1686 if (!freed
) return; /* nothing to free... */
1690 /* =================================== Main! ================================ */
1693 int linuxOvercommitMemoryValue(void) {
1694 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1698 if (fgets(buf
,64,fp
) == NULL
) {
1707 void linuxOvercommitMemoryWarning(void) {
1708 if (linuxOvercommitMemoryValue() == 0) {
1709 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.");
1712 #endif /* __linux__ */
1714 void createPidFile(void) {
1715 /* Try to write the pid file in a best-effort way. */
1716 FILE *fp
= fopen(server
.pidfile
,"w");
1718 fprintf(fp
,"%d\n",(int)getpid());
1723 void daemonize(void) {
1726 if (fork() != 0) exit(0); /* parent exits */
1727 setsid(); /* create a new session */
1729 /* Every output goes to /dev/null. If Redis is daemonized but
1730 * the 'logfile' is set to 'stdout' in the configuration file
1731 * it will not log at all. */
1732 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1733 dup2(fd
, STDIN_FILENO
);
1734 dup2(fd
, STDOUT_FILENO
);
1735 dup2(fd
, STDERR_FILENO
);
1736 if (fd
> STDERR_FILENO
) close(fd
);
1741 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1742 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1747 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1748 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1752 void redisAsciiArt(void) {
1753 #include "asciilogo.h"
1754 char *buf
= zmalloc(1024*16);
1756 snprintf(buf
,1024*16,ascii_logo
,
1759 strtol(redisGitDirty(),NULL
,10) > 0,
1760 (sizeof(long) == 8) ? "64" : "32",
1761 server
.cluster_enabled
? "cluster" : "stand alone",
1765 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1769 int main(int argc
, char **argv
) {
1772 zmalloc_enable_thread_safeness();
1775 if (strcmp(argv
[1], "-v") == 0 ||
1776 strcmp(argv
[1], "--version") == 0) version();
1777 if (strcmp(argv
[1], "--help") == 0) usage();
1778 resetServerSaveParams();
1779 loadServerConfig(argv
[1]);
1780 } else if ((argc
> 2)) {
1783 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'");
1785 if (server
.daemonize
) daemonize();
1787 if (server
.daemonize
) createPidFile();
1789 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1791 linuxOvercommitMemoryWarning();
1794 if (server
.appendonly
) {
1795 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1796 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1798 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1799 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",(float)(ustime()-start
)/1000000);
1801 if (server
.ipfd
> 0)
1802 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1803 if (server
.sofd
> 0)
1804 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1805 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1807 aeDeleteEventLoop(server
.el
);
1811 #ifdef HAVE_BACKTRACE
1812 static void *getMcontextEip(ucontext_t
*uc
) {
1813 #if defined(__FreeBSD__)
1814 return (void*) uc
->uc_mcontext
.mc_eip
;
1815 #elif defined(__dietlibc__)
1816 return (void*) uc
->uc_mcontext
.eip
;
1817 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1819 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1821 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1823 return (void*) uc
->uc_mcontext
->__ss
.__srr0
;
1825 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1826 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1827 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1829 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1831 #elif defined(__i386__)
1832 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1833 #elif defined(__X86_64__) || defined(__x86_64__)
1834 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1835 #elif defined(__ia64__) /* Linux IA64 */
1836 return (void*) uc
->uc_mcontext
.sc_ip
;
1842 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1844 char **messages
= NULL
;
1845 int i
, trace_size
= 0;
1846 ucontext_t
*uc
= (ucontext_t
*) secret
;
1848 struct sigaction act
;
1849 REDIS_NOTUSED(info
);
1851 redisLog(REDIS_WARNING
,
1852 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1853 infostring
= genRedisInfoString("all");
1854 redisLogRaw(REDIS_WARNING
, infostring
);
1855 /* It's not safe to sdsfree() the returned string under memory
1856 * corruption conditions. Let it leak as we are going to abort */
1858 trace_size
= backtrace(trace
, 100);
1859 /* overwrite sigaction with caller's address */
1860 if (getMcontextEip(uc
) != NULL
) {
1861 trace
[1] = getMcontextEip(uc
);
1863 messages
= backtrace_symbols(trace
, trace_size
);
1865 for (i
=1; i
<trace_size
; ++i
)
1866 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1868 /* free(messages); Don't call free() with possibly corrupted memory. */
1869 if (server
.daemonize
) unlink(server
.pidfile
);
1871 /* Make sure we exit with the right signal at the end. So for instance
1872 * the core will be dumped if enabled. */
1873 sigemptyset (&act
.sa_mask
);
1874 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1875 * is used. Otherwise, sa_handler is used */
1876 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1877 act
.sa_handler
= SIG_DFL
;
1878 sigaction (sig
, &act
, NULL
);
1881 #endif /* HAVE_BACKTRACE */
1883 static void sigtermHandler(int sig
) {
1886 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1887 server
.shutdown_asap
= 1;
1890 void setupSignalHandlers(void) {
1891 struct sigaction act
;
1893 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1894 * Otherwise, sa_handler is used. */
1895 sigemptyset(&act
.sa_mask
);
1896 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1897 act
.sa_handler
= sigtermHandler
;
1898 sigaction(SIGTERM
, &act
, NULL
);
1900 #ifdef HAVE_BACKTRACE
1901 sigemptyset(&act
.sa_mask
);
1902 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1903 act
.sa_sigaction
= sigsegvHandler
;
1904 sigaction(SIGSEGV
, &act
, NULL
);
1905 sigaction(SIGBUS
, &act
, NULL
);
1906 sigaction(SIGFPE
, &act
, NULL
);
1907 sigaction(SIGILL
, &act
, NULL
);