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 {"psetex",psetexCommand
,4,"wm",0,noPreloadGetKeys
,2,2,1,0,0},
95 {"append",appendCommand
,3,"wm",0,NULL
,1,1,1,0,0},
96 {"strlen",strlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
97 {"del",delCommand
,-2,"w",0,noPreloadGetKeys
,1,-1,1,0,0},
98 {"exists",existsCommand
,2,"r",0,NULL
,1,1,1,0,0},
99 {"setbit",setbitCommand
,4,"wm",0,NULL
,1,1,1,0,0},
100 {"getbit",getbitCommand
,3,"r",0,NULL
,1,1,1,0,0},
101 {"setrange",setrangeCommand
,4,"wm",0,NULL
,1,1,1,0,0},
102 {"getrange",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
103 {"substr",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
104 {"incr",incrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
105 {"decr",decrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
106 {"mget",mgetCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
107 {"rpush",rpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
108 {"lpush",lpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
109 {"rpushx",rpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
110 {"lpushx",lpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
111 {"linsert",linsertCommand
,5,"wm",0,NULL
,1,1,1,0,0},
112 {"rpop",rpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
113 {"lpop",lpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
114 {"brpop",brpopCommand
,-3,"w",0,NULL
,1,1,1,0,0},
115 {"brpoplpush",brpoplpushCommand
,4,"wm",0,NULL
,1,2,1,0,0},
116 {"blpop",blpopCommand
,-3,"w",0,NULL
,1,-2,1,0,0},
117 {"llen",llenCommand
,2,"r",0,NULL
,1,1,1,0,0},
118 {"lindex",lindexCommand
,3,"r",0,NULL
,1,1,1,0,0},
119 {"lset",lsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
120 {"lrange",lrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
121 {"ltrim",ltrimCommand
,4,"w",0,NULL
,1,1,1,0,0},
122 {"lrem",lremCommand
,4,"w",0,NULL
,1,1,1,0,0},
123 {"rpoplpush",rpoplpushCommand
,3,"wm",0,NULL
,1,2,1,0,0},
124 {"sadd",saddCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
125 {"srem",sremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
126 {"smove",smoveCommand
,4,"w",0,NULL
,1,2,1,0,0},
127 {"sismember",sismemberCommand
,3,"r",0,NULL
,1,1,1,0,0},
128 {"scard",scardCommand
,2,"r",0,NULL
,1,1,1,0,0},
129 {"spop",spopCommand
,2,"wRs",0,NULL
,1,1,1,0,0},
130 {"srandmember",srandmemberCommand
,2,"rR",0,NULL
,1,1,1,0,0},
131 {"sinter",sinterCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
132 {"sinterstore",sinterstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
133 {"sunion",sunionCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
134 {"sunionstore",sunionstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
135 {"sdiff",sdiffCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
136 {"sdiffstore",sdiffstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
137 {"smembers",sinterCommand
,2,"r",0,NULL
,1,1,1,0,0},
138 {"zadd",zaddCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
139 {"zincrby",zincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
140 {"zrem",zremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
141 {"zremrangebyscore",zremrangebyscoreCommand
,4,"w",0,NULL
,1,1,1,0,0},
142 {"zremrangebyrank",zremrangebyrankCommand
,4,"w",0,NULL
,1,1,1,0,0},
143 {"zunionstore",zunionstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
144 {"zinterstore",zinterstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
145 {"zrange",zrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
146 {"zrangebyscore",zrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
147 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
148 {"zcount",zcountCommand
,4,"r",0,NULL
,1,1,1,0,0},
149 {"zrevrange",zrevrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
150 {"zcard",zcardCommand
,2,"r",0,NULL
,1,1,1,0,0},
151 {"zscore",zscoreCommand
,3,"r",0,NULL
,1,1,1,0,0},
152 {"zrank",zrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
153 {"zrevrank",zrevrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
154 {"hset",hsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
155 {"hsetnx",hsetnxCommand
,4,"wm",0,NULL
,1,1,1,0,0},
156 {"hget",hgetCommand
,3,"r",0,NULL
,1,1,1,0,0},
157 {"hmset",hmsetCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
158 {"hmget",hmgetCommand
,-3,"r",0,NULL
,1,1,1,0,0},
159 {"hincrby",hincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
160 {"hdel",hdelCommand
,-3,"w",0,NULL
,1,1,1,0,0},
161 {"hlen",hlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
162 {"hkeys",hkeysCommand
,2,"r",0,NULL
,1,1,1,0,0},
163 {"hvals",hvalsCommand
,2,"r",0,NULL
,1,1,1,0,0},
164 {"hgetall",hgetallCommand
,2,"r",0,NULL
,1,1,1,0,0},
165 {"hexists",hexistsCommand
,3,"r",0,NULL
,1,1,1,0,0},
166 {"incrby",incrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
167 {"decrby",decrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
168 {"incrbyfloat",incrbyfloatCommand
,3,"wm",0,NULL
,1,1,1,0,0},
169 {"getset",getsetCommand
,3,"wm",0,NULL
,1,1,1,0,0},
170 {"mset",msetCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
171 {"msetnx",msetnxCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
172 {"randomkey",randomkeyCommand
,1,"rR",0,NULL
,0,0,0,0,0},
173 {"select",selectCommand
,2,"r",0,NULL
,0,0,0,0,0},
174 {"move",moveCommand
,3,"w",0,NULL
,1,1,1,0,0},
175 {"rename",renameCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
176 {"renamenx",renamenxCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
177 {"expire",expireCommand
,3,"w",0,NULL
,1,1,1,0,0},
178 {"expireat",expireatCommand
,3,"w",0,NULL
,1,1,1,0,0},
179 {"pexpire",pexpireCommand
,3,"w",0,NULL
,1,1,1,0,0},
180 {"pexpireat",pexpireatCommand
,3,"w",0,NULL
,1,1,1,0,0},
181 {"keys",keysCommand
,2,"r",0,NULL
,0,0,0,0,0},
182 {"dbsize",dbsizeCommand
,1,"r",0,NULL
,0,0,0,0,0},
183 {"auth",authCommand
,2,"r",0,NULL
,0,0,0,0,0},
184 {"ping",pingCommand
,1,"r",0,NULL
,0,0,0,0,0},
185 {"echo",echoCommand
,2,"r",0,NULL
,0,0,0,0,0},
186 {"save",saveCommand
,1,"ar",0,NULL
,0,0,0,0,0},
187 {"bgsave",bgsaveCommand
,1,"ar",0,NULL
,0,0,0,0,0},
188 {"bgrewriteaof",bgrewriteaofCommand
,1,"ar",0,NULL
,0,0,0,0,0},
189 {"shutdown",shutdownCommand
,1,"ar",0,NULL
,0,0,0,0,0},
190 {"lastsave",lastsaveCommand
,1,"r",0,NULL
,0,0,0,0,0},
191 {"type",typeCommand
,2,"r",0,NULL
,1,1,1,0,0},
192 {"multi",multiCommand
,1,"rs",0,NULL
,0,0,0,0,0},
193 {"exec",execCommand
,1,"wms",0,NULL
,0,0,0,0,0},
194 {"discard",discardCommand
,1,"rs",0,NULL
,0,0,0,0,0},
195 {"sync",syncCommand
,1,"ars",0,NULL
,0,0,0,0,0},
196 {"flushdb",flushdbCommand
,1,"w",0,NULL
,0,0,0,0,0},
197 {"flushall",flushallCommand
,1,"w",0,NULL
,0,0,0,0,0},
198 {"sort",sortCommand
,-2,"wm",0,NULL
,1,1,1,0,0},
199 {"info",infoCommand
,-1,"r",0,NULL
,0,0,0,0,0},
200 {"monitor",monitorCommand
,1,"ars",0,NULL
,0,0,0,0,0},
201 {"ttl",ttlCommand
,2,"r",0,NULL
,1,1,1,0,0},
202 {"pttl",pttlCommand
,2,"r",0,NULL
,1,1,1,0,0},
203 {"persist",persistCommand
,2,"w",0,NULL
,1,1,1,0,0},
204 {"slaveof",slaveofCommand
,3,"aws",0,NULL
,0,0,0,0,0},
205 {"debug",debugCommand
,-2,"aw",0,NULL
,0,0,0,0,0},
206 {"config",configCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
207 {"subscribe",subscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
208 {"unsubscribe",unsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
209 {"psubscribe",psubscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
210 {"punsubscribe",punsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
211 {"publish",publishCommand
,3,"rpf",0,NULL
,0,0,0,0,0},
212 {"watch",watchCommand
,-2,"rs",0,noPreloadGetKeys
,1,-1,1,0,0},
213 {"unwatch",unwatchCommand
,1,"rs",0,NULL
,0,0,0,0,0},
214 {"cluster",clusterCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
215 {"restore",restoreCommand
,4,"awm",0,NULL
,1,1,1,0,0},
216 {"migrate",migrateCommand
,6,"aw",0,NULL
,0,0,0,0,0},
217 {"asking",askingCommand
,1,"r",0,NULL
,0,0,0,0,0},
218 {"dump",dumpCommand
,2,"ar",0,NULL
,0,0,0,0,0},
219 {"object",objectCommand
,-2,"r",0,NULL
,0,0,0,0,0},
220 {"client",clientCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
221 {"eval",evalCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
222 {"evalsha",evalShaCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
223 {"slowlog",slowlogCommand
,-2,"r",0,NULL
,0,0,0,0,0},
224 {"script",scriptCommand
,-2,"ras",0,NULL
,0,0,0,0,0}
227 /*============================ Utility functions ============================ */
229 /* Low level logging. To use only for very big messages, otherwise
230 * redisLog() is to prefer. */
231 void redisLogRaw(int level
, const char *msg
) {
232 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
233 const char *c
= ".-*#";
234 time_t now
= time(NULL
);
237 int rawmode
= (level
& REDIS_LOG_RAW
);
239 level
&= 0xff; /* clear flags */
240 if (level
< server
.verbosity
) return;
242 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
246 fprintf(fp
,"%s",msg
);
248 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
249 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
253 if (server
.logfile
) fclose(fp
);
255 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
258 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
259 * is used across the code. The raw version is only used in order to dump
260 * the INFO output on crash. */
261 void redisLog(int level
, const char *fmt
, ...) {
263 char msg
[REDIS_MAX_LOGMSG_LEN
];
265 if ((level
&0xff) < server
.verbosity
) return;
268 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
271 redisLogRaw(level
,msg
);
274 /* Redis generally does not try to recover from out of memory conditions
275 * when allocating objects or strings, it is not clear if it will be possible
276 * to report this condition to the client since the networking layer itself
277 * is based on heap allocation for send buffers, so we simply abort.
278 * At least the code will be simpler to read... */
279 void oom(const char *msg
) {
280 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
285 /* Return the UNIX time in microseconds */
286 long long ustime(void) {
290 gettimeofday(&tv
, NULL
);
291 ust
= ((long long)tv
.tv_sec
)*1000000;
296 /* Return the UNIX time in milliseconds */
297 long long mstime(void) {
298 return ustime()/1000;
301 /*====================== Hash table type implementation ==================== */
303 /* This is an hash table type that uses the SDS dynamic strings libary as
304 * keys and radis objects as values (objects can hold SDS strings,
307 void dictVanillaFree(void *privdata
, void *val
)
309 DICT_NOTUSED(privdata
);
313 void dictListDestructor(void *privdata
, void *val
)
315 DICT_NOTUSED(privdata
);
316 listRelease((list
*)val
);
319 int dictSdsKeyCompare(void *privdata
, const void *key1
,
323 DICT_NOTUSED(privdata
);
325 l1
= sdslen((sds
)key1
);
326 l2
= sdslen((sds
)key2
);
327 if (l1
!= l2
) return 0;
328 return memcmp(key1
, key2
, l1
) == 0;
331 /* A case insensitive version used for the command lookup table. */
332 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
335 DICT_NOTUSED(privdata
);
337 return strcasecmp(key1
, key2
) == 0;
340 void dictRedisObjectDestructor(void *privdata
, void *val
)
342 DICT_NOTUSED(privdata
);
344 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
348 void dictSdsDestructor(void *privdata
, void *val
)
350 DICT_NOTUSED(privdata
);
355 int dictObjKeyCompare(void *privdata
, const void *key1
,
358 const robj
*o1
= key1
, *o2
= key2
;
359 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
362 unsigned int dictObjHash(const void *key
) {
364 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
367 unsigned int dictSdsHash(const void *key
) {
368 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
371 unsigned int dictSdsCaseHash(const void *key
) {
372 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
375 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
378 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
381 if (o1
->encoding
== REDIS_ENCODING_INT
&&
382 o2
->encoding
== REDIS_ENCODING_INT
)
383 return o1
->ptr
== o2
->ptr
;
385 o1
= getDecodedObject(o1
);
386 o2
= getDecodedObject(o2
);
387 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
393 unsigned int dictEncObjHash(const void *key
) {
394 robj
*o
= (robj
*) key
;
396 if (o
->encoding
== REDIS_ENCODING_RAW
) {
397 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
399 if (o
->encoding
== REDIS_ENCODING_INT
) {
403 len
= ll2string(buf
,32,(long)o
->ptr
);
404 return dictGenHashFunction((unsigned char*)buf
, len
);
408 o
= getDecodedObject(o
);
409 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
416 /* Sets type hash table */
417 dictType setDictType
= {
418 dictEncObjHash
, /* hash function */
421 dictEncObjKeyCompare
, /* key compare */
422 dictRedisObjectDestructor
, /* key destructor */
423 NULL
/* val destructor */
426 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
427 dictType zsetDictType
= {
428 dictEncObjHash
, /* hash function */
431 dictEncObjKeyCompare
, /* key compare */
432 dictRedisObjectDestructor
, /* key destructor */
433 NULL
/* val destructor */
436 /* Db->dict, keys are sds strings, vals are Redis objects. */
437 dictType dbDictType
= {
438 dictSdsHash
, /* hash function */
441 dictSdsKeyCompare
, /* key compare */
442 dictSdsDestructor
, /* key destructor */
443 dictRedisObjectDestructor
/* val destructor */
447 dictType keyptrDictType
= {
448 dictSdsHash
, /* hash function */
451 dictSdsKeyCompare
, /* key compare */
452 NULL
, /* key destructor */
453 NULL
/* val destructor */
456 /* Command table. sds string -> command struct pointer. */
457 dictType commandTableDictType
= {
458 dictSdsCaseHash
, /* hash function */
461 dictSdsKeyCaseCompare
, /* key compare */
462 dictSdsDestructor
, /* key destructor */
463 NULL
/* val destructor */
466 /* Hash type hash table (note that small hashes are represented with zimpaps) */
467 dictType hashDictType
= {
468 dictEncObjHash
, /* hash function */
471 dictEncObjKeyCompare
, /* key compare */
472 dictRedisObjectDestructor
, /* key destructor */
473 dictRedisObjectDestructor
/* val destructor */
476 /* Keylist hash table type has unencoded redis objects as keys and
477 * lists as values. It's used for blocking operations (BLPOP) and to
478 * map swapped keys to a list of clients waiting for this keys to be loaded. */
479 dictType keylistDictType
= {
480 dictObjHash
, /* hash function */
483 dictObjKeyCompare
, /* key compare */
484 dictRedisObjectDestructor
, /* key destructor */
485 dictListDestructor
/* val destructor */
488 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
489 * clusterNode structures. */
490 dictType clusterNodesDictType
= {
491 dictSdsHash
, /* hash function */
494 dictSdsKeyCompare
, /* key compare */
495 dictSdsDestructor
, /* key destructor */
496 NULL
/* val destructor */
499 int htNeedsResize(dict
*dict
) {
500 long long size
, used
;
502 size
= dictSlots(dict
);
503 used
= dictSize(dict
);
504 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
505 (used
*100/size
< REDIS_HT_MINFILL
));
508 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
509 * we resize the hash table to save memory */
510 void tryResizeHashTables(void) {
513 for (j
= 0; j
< server
.dbnum
; j
++) {
514 if (htNeedsResize(server
.db
[j
].dict
))
515 dictResize(server
.db
[j
].dict
);
516 if (htNeedsResize(server
.db
[j
].expires
))
517 dictResize(server
.db
[j
].expires
);
521 /* Our hash table implementation performs rehashing incrementally while
522 * we write/read from the hash table. Still if the server is idle, the hash
523 * table will use two tables for a long time. So we try to use 1 millisecond
524 * of CPU time at every serverCron() loop in order to rehash some key. */
525 void incrementallyRehash(void) {
528 for (j
= 0; j
< server
.dbnum
; j
++) {
529 if (dictIsRehashing(server
.db
[j
].dict
)) {
530 dictRehashMilliseconds(server
.db
[j
].dict
,1);
531 break; /* already used our millisecond for this loop... */
536 /* This function is called once a background process of some kind terminates,
537 * as we want to avoid resizing the hash tables when there is a child in order
538 * to play well with copy-on-write (otherwise when a resize happens lots of
539 * memory pages are copied). The goal of this function is to update the ability
540 * for dict.c to resize the hash tables accordingly to the fact we have o not
542 void updateDictResizePolicy(void) {
543 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
549 /* ======================= Cron: called every 100 ms ======================== */
551 /* Try to expire a few timed out keys. The algorithm used is adaptive and
552 * will use few CPU cycles if there are few expiring keys, otherwise
553 * it will get more aggressive to avoid that too much memory is used by
554 * keys that can be removed from the keyspace. */
555 void activeExpireCycle(void) {
558 for (j
= 0; j
< server
.dbnum
; j
++) {
560 redisDb
*db
= server
.db
+j
;
562 /* Continue to expire if at the end of the cycle more than 25%
563 * of the keys were expired. */
565 long num
= dictSize(db
->expires
);
566 time_t now
= time(NULL
);
569 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
570 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
575 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
576 t
= (time_t) dictGetVal(de
);
578 sds key
= dictGetKey(de
);
579 robj
*keyobj
= createStringObject(key
,sdslen(key
));
581 propagateExpire(db
,keyobj
);
583 decrRefCount(keyobj
);
585 server
.stat_expiredkeys
++;
588 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
592 void updateLRUClock(void) {
593 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
597 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
598 int j
, loops
= server
.cronloops
;
599 REDIS_NOTUSED(eventLoop
);
601 REDIS_NOTUSED(clientData
);
603 /* We take a cached value of the unix time in the global state because
604 * with virtual memory and aging there is to store the current time
605 * in objects at every object access, and accuracy is not needed.
606 * To access a global var is faster than calling time(NULL) */
607 server
.unixtime
= time(NULL
);
609 /* We have just 22 bits per object for LRU information.
610 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
611 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
613 * Note that even if this will wrap after 1.5 years it's not a problem,
614 * everything will still work but just some object will appear younger
615 * to Redis. But for this to happen a given object should never be touched
618 * Note that you can change the resolution altering the
619 * REDIS_LRU_CLOCK_RESOLUTION define.
623 /* Record the max memory used since the server was started. */
624 if (zmalloc_used_memory() > server
.stat_peak_memory
)
625 server
.stat_peak_memory
= zmalloc_used_memory();
627 /* We received a SIGTERM, shutting down here in a safe way, as it is
628 * not ok doing so inside the signal handler. */
629 if (server
.shutdown_asap
) {
630 if (prepareForShutdown() == REDIS_OK
) exit(0);
631 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
634 /* Show some info about non-empty databases */
635 for (j
= 0; j
< server
.dbnum
; j
++) {
636 long long size
, used
, vkeys
;
638 size
= dictSlots(server
.db
[j
].dict
);
639 used
= dictSize(server
.db
[j
].dict
);
640 vkeys
= dictSize(server
.db
[j
].expires
);
641 if (!(loops
% 50) && (used
|| vkeys
)) {
642 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
643 /* dictPrintStats(server.dict); */
647 /* We don't want to resize the hash tables while a bacground saving
648 * is in progress: the saving child is created using fork() that is
649 * implemented with a copy-on-write semantic in most modern systems, so
650 * if we resize the HT while there is the saving child at work actually
651 * a lot of memory movements in the parent will cause a lot of pages
653 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
654 if (!(loops
% 10)) tryResizeHashTables();
655 if (server
.activerehashing
) incrementallyRehash();
658 /* Show information about connected clients */
660 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
661 listLength(server
.clients
)-listLength(server
.slaves
),
662 listLength(server
.slaves
),
663 zmalloc_used_memory());
666 /* Close connections of timedout clients */
667 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
668 closeTimedoutClients();
670 /* Start a scheduled AOF rewrite if this was requested by the user while
671 * a BGSAVE was in progress. */
672 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1 &&
673 server
.aofrewrite_scheduled
)
675 rewriteAppendOnlyFileBackground();
678 /* Check if a background saving or AOF rewrite in progress terminated. */
679 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
683 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
684 int exitcode
= WEXITSTATUS(statloc
);
687 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
689 if (pid
== server
.bgsavechildpid
) {
690 backgroundSaveDoneHandler(exitcode
,bysignal
);
692 backgroundRewriteDoneHandler(exitcode
,bysignal
);
694 updateDictResizePolicy();
697 time_t now
= time(NULL
);
699 /* If there is not a background saving/rewrite in progress check if
700 * we have to save/rewrite now */
701 for (j
= 0; j
< server
.saveparamslen
; j
++) {
702 struct saveparam
*sp
= server
.saveparams
+j
;
704 if (server
.dirty
>= sp
->changes
&&
705 now
-server
.lastsave
> sp
->seconds
) {
706 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
707 sp
->changes
, sp
->seconds
);
708 rdbSaveBackground(server
.dbfilename
);
713 /* Trigger an AOF rewrite if needed */
714 if (server
.bgsavechildpid
== -1 &&
715 server
.bgrewritechildpid
== -1 &&
716 server
.auto_aofrewrite_perc
&&
717 server
.appendonly_current_size
> server
.auto_aofrewrite_min_size
)
719 long long base
= server
.auto_aofrewrite_base_size
?
720 server
.auto_aofrewrite_base_size
: 1;
721 long long growth
= (server
.appendonly_current_size
*100/base
) - 100;
722 if (growth
>= server
.auto_aofrewrite_perc
) {
723 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
724 rewriteAppendOnlyFileBackground();
730 /* If we postponed an AOF buffer flush, let's try to do it every time the
731 * cron function is called. */
732 if (server
.aof_flush_postponed_start
) flushAppendOnlyFile(0);
734 /* Expire a few keys per cycle, only if this is a master.
735 * On slaves we wait for DEL operations synthesized by the master
736 * in order to guarantee a strict consistency. */
737 if (server
.masterhost
== NULL
) activeExpireCycle();
739 /* Replication cron function -- used to reconnect to master and
740 * to detect transfer failures. */
741 if (!(loops
% 10)) replicationCron();
743 /* Run other sub-systems specific cron jobs */
744 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
750 /* This function gets called every time Redis is entering the
751 * main loop of the event driven library, that is, before to sleep
752 * for ready file descriptors. */
753 void beforeSleep(struct aeEventLoop
*eventLoop
) {
754 REDIS_NOTUSED(eventLoop
);
758 /* Try to process pending commands for clients that were just unblocked. */
759 while (listLength(server
.unblocked_clients
)) {
760 ln
= listFirst(server
.unblocked_clients
);
761 redisAssert(ln
!= NULL
);
763 listDelNode(server
.unblocked_clients
,ln
);
764 c
->flags
&= ~REDIS_UNBLOCKED
;
766 /* Process remaining data in the input buffer. */
767 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
768 processInputBuffer(c
);
771 /* Write the AOF buffer on disk */
772 flushAppendOnlyFile(0);
775 /* =========================== Server initialization ======================== */
777 void createSharedObjects(void) {
780 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
781 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
782 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
783 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
784 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
785 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
786 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
787 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
788 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
789 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
790 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
791 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
792 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
793 "-ERR Operation against a key holding the wrong kind of value\r\n"));
794 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
795 "-ERR no such key\r\n"));
796 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
797 "-ERR syntax error\r\n"));
798 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
799 "-ERR source and destination objects are the same\r\n"));
800 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
801 "-ERR index out of range\r\n"));
802 shared
.noscripterr
= createObject(REDIS_STRING
,sdsnew(
803 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
804 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
805 "-LOADING Redis is loading the dataset in memory\r\n"));
806 shared
.slowscripterr
= createObject(REDIS_STRING
,sdsnew(
807 "-BUSY Redis is busy running a script. Please wait or stop the server with SHUTDOWN.\r\n"));
808 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
809 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
810 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
811 shared
.select0
= createStringObject("select 0\r\n",10);
812 shared
.select1
= createStringObject("select 1\r\n",10);
813 shared
.select2
= createStringObject("select 2\r\n",10);
814 shared
.select3
= createStringObject("select 3\r\n",10);
815 shared
.select4
= createStringObject("select 4\r\n",10);
816 shared
.select5
= createStringObject("select 5\r\n",10);
817 shared
.select6
= createStringObject("select 6\r\n",10);
818 shared
.select7
= createStringObject("select 7\r\n",10);
819 shared
.select8
= createStringObject("select 8\r\n",10);
820 shared
.select9
= createStringObject("select 9\r\n",10);
821 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
822 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
823 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
824 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
825 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
826 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
827 shared
.mbulk3
= createStringObject("*3\r\n",4);
828 shared
.mbulk4
= createStringObject("*4\r\n",4);
829 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
830 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
831 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
835 void initServerConfig() {
836 server
.port
= REDIS_SERVERPORT
;
837 server
.bindaddr
= NULL
;
838 server
.unixsocket
= NULL
;
839 server
.unixsocketperm
= 0;
842 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
843 server
.verbosity
= REDIS_VERBOSE
;
844 server
.maxidletime
= REDIS_MAXIDLETIME
;
845 server
.saveparams
= NULL
;
847 server
.logfile
= NULL
; /* NULL = log on standard output */
848 server
.syslog_enabled
= 0;
849 server
.syslog_ident
= zstrdup("redis");
850 server
.syslog_facility
= LOG_LOCAL0
;
851 server
.daemonize
= 0;
852 server
.appendonly
= 0;
853 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
854 server
.no_appendfsync_on_rewrite
= 0;
855 server
.auto_aofrewrite_perc
= REDIS_AUTO_AOFREWRITE_PERC
;
856 server
.auto_aofrewrite_min_size
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
;
857 server
.auto_aofrewrite_base_size
= 0;
858 server
.aofrewrite_scheduled
= 0;
859 server
.lastfsync
= time(NULL
);
860 server
.appendfd
= -1;
861 server
.appendseldb
= -1; /* Make sure the first time will not match */
862 server
.aof_flush_postponed_start
= 0;
863 server
.pidfile
= zstrdup("/var/run/redis.pid");
864 server
.dbfilename
= zstrdup("dump.rdb");
865 server
.appendfilename
= zstrdup("appendonly.aof");
866 server
.requirepass
= NULL
;
867 server
.rdbcompression
= 1;
868 server
.activerehashing
= 1;
869 server
.maxclients
= REDIS_MAX_CLIENTS
;
870 server
.bpop_blocked_clients
= 0;
871 server
.maxmemory
= 0;
872 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
873 server
.maxmemory_samples
= 3;
874 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
875 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
876 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
877 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
878 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
879 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
880 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
881 server
.shutdown_asap
= 0;
882 server
.repl_ping_slave_period
= REDIS_REPL_PING_SLAVE_PERIOD
;
883 server
.repl_timeout
= REDIS_REPL_TIMEOUT
;
884 server
.cluster_enabled
= 0;
885 server
.cluster
.configfile
= zstrdup("nodes.conf");
886 server
.lua_time_limit
= REDIS_LUA_TIME_LIMIT
;
887 server
.lua_client
= NULL
;
888 server
.lua_timedout
= 0;
891 resetServerSaveParams();
893 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
894 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
895 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
896 /* Replication related */
898 server
.masterauth
= NULL
;
899 server
.masterhost
= NULL
;
900 server
.masterport
= 6379;
901 server
.master
= NULL
;
902 server
.replstate
= REDIS_REPL_NONE
;
903 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
904 server
.repl_serve_stale_data
= 1;
905 server
.repl_down_since
= -1;
907 /* Double constants initialization */
909 R_PosInf
= 1.0/R_Zero
;
910 R_NegInf
= -1.0/R_Zero
;
911 R_Nan
= R_Zero
/R_Zero
;
913 /* Command table -- we intiialize it here as it is part of the
914 * initial configuration, since command names may be changed via
915 * redis.conf using the rename-command directive. */
916 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
917 populateCommandTable();
918 server
.delCommand
= lookupCommandByCString("del");
919 server
.multiCommand
= lookupCommandByCString("multi");
922 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
923 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
929 signal(SIGHUP
, SIG_IGN
);
930 signal(SIGPIPE
, SIG_IGN
);
931 setupSignalHandlers();
933 if (server
.syslog_enabled
) {
934 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
935 server
.syslog_facility
);
938 server
.clients
= listCreate();
939 server
.slaves
= listCreate();
940 server
.monitors
= listCreate();
941 server
.unblocked_clients
= listCreate();
943 createSharedObjects();
944 server
.el
= aeCreateEventLoop();
945 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
947 if (server
.port
!= 0) {
948 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
949 if (server
.ipfd
== ANET_ERR
) {
950 redisLog(REDIS_WARNING
, "Opening port %d: %s",
951 server
.port
, server
.neterr
);
955 if (server
.unixsocket
!= NULL
) {
956 unlink(server
.unixsocket
); /* don't care if this fails */
957 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
,server
.unixsocketperm
);
958 if (server
.sofd
== ANET_ERR
) {
959 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
963 if (server
.ipfd
< 0 && server
.sofd
< 0) {
964 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
967 for (j
= 0; j
< server
.dbnum
; j
++) {
968 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
969 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
970 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
971 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
974 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
975 server
.pubsub_patterns
= listCreate();
976 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
977 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
978 server
.cronloops
= 0;
979 server
.bgsavechildpid
= -1;
980 server
.bgrewritechildpid
= -1;
981 server
.bgrewritebuf
= sdsempty();
982 server
.aofbuf
= sdsempty();
983 server
.lastsave
= time(NULL
);
985 server
.stat_numcommands
= 0;
986 server
.stat_numconnections
= 0;
987 server
.stat_expiredkeys
= 0;
988 server
.stat_evictedkeys
= 0;
989 server
.stat_starttime
= time(NULL
);
990 server
.stat_keyspace_misses
= 0;
991 server
.stat_keyspace_hits
= 0;
992 server
.stat_peak_memory
= 0;
993 server
.stat_fork_time
= 0;
994 server
.unixtime
= time(NULL
);
995 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
996 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
997 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
998 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
999 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
1001 if (server
.appendonly
) {
1002 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1003 if (server
.appendfd
== -1) {
1004 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1010 if (server
.cluster_enabled
) clusterInit();
1014 srand(time(NULL
)^getpid());
1016 /* Try to raise the max number of open files accordingly to the
1017 * configured max number of clients. Also account for 32 additional
1018 * file descriptors as we need a few more for persistence, listening
1019 * sockets, log files and so forth. */
1021 rlim_t maxfiles
= server
.maxclients
+32;
1022 struct rlimit limit
;
1024 if (maxfiles
< 1024) maxfiles
= 1024;
1025 if (getrlimit(RLIMIT_NOFILE
,&limit
) == -1) {
1026 redisLog(REDIS_WARNING
,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.",
1028 server
.maxclients
= 1024-32;
1030 rlim_t oldlimit
= limit
.rlim_cur
;
1032 /* Set the max number of files if the current limit is not enough
1034 if (oldlimit
< maxfiles
) {
1035 limit
.rlim_cur
= maxfiles
;
1036 limit
.rlim_max
= maxfiles
;
1037 if (setrlimit(RLIMIT_NOFILE
,&limit
) == -1) {
1038 server
.maxclients
= oldlimit
-32;
1039 redisLog(REDIS_WARNING
,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.",
1040 (int) maxfiles
, strerror(errno
), (int) server
.maxclients
);
1042 redisLog(REDIS_NOTICE
,"Max number of open files set to %d",
1050 /* Populates the Redis Command Table starting from the hard coded list
1051 * we have on top of redis.c file. */
1052 void populateCommandTable(void) {
1054 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1056 for (j
= 0; j
< numcommands
; j
++) {
1057 struct redisCommand
*c
= redisCommandTable
+j
;
1058 char *f
= c
->sflags
;
1063 case 'w': c
->flags
|= REDIS_CMD_WRITE
; break;
1064 case 'r': c
->flags
|= REDIS_CMD_READONLY
; break;
1065 case 'm': c
->flags
|= REDIS_CMD_DENYOOM
; break;
1066 case 'a': c
->flags
|= REDIS_CMD_ADMIN
; break;
1067 case 'p': c
->flags
|= REDIS_CMD_PUBSUB
; break;
1068 case 'f': c
->flags
|= REDIS_CMD_FORCE_REPLICATION
; break;
1069 case 's': c
->flags
|= REDIS_CMD_NOSCRIPT
; break;
1070 case 'R': c
->flags
|= REDIS_CMD_RANDOM
; break;
1071 default: redisPanic("Unsupported command flag"); break;
1076 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
1077 assert(retval
== DICT_OK
);
1081 void resetCommandTableStats(void) {
1082 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1085 for (j
= 0; j
< numcommands
; j
++) {
1086 struct redisCommand
*c
= redisCommandTable
+j
;
1088 c
->microseconds
= 0;
1093 /* ====================== Commands lookup and execution ===================== */
1095 struct redisCommand
*lookupCommand(sds name
) {
1096 return dictFetchValue(server
.commands
, name
);
1099 struct redisCommand
*lookupCommandByCString(char *s
) {
1100 struct redisCommand
*cmd
;
1101 sds name
= sdsnew(s
);
1103 cmd
= dictFetchValue(server
.commands
, name
);
1108 /* Call() is the core of Redis execution of a command */
1109 void call(redisClient
*c
) {
1110 long long dirty
, start
= ustime(), duration
;
1112 dirty
= server
.dirty
;
1114 dirty
= server
.dirty
-dirty
;
1115 duration
= ustime()-start
;
1116 c
->cmd
->microseconds
+= duration
;
1117 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1120 if (server
.appendonly
&& dirty
> 0)
1121 feedAppendOnlyFile(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1122 if ((dirty
> 0 || c
->cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1123 listLength(server
.slaves
))
1124 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1125 if (listLength(server
.monitors
))
1126 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1127 server
.stat_numcommands
++;
1130 /* If this function gets called we already read a whole
1131 * command, argments are in the client argv/argc fields.
1132 * processCommand() execute the command or prepare the
1133 * server for a bulk read from the client.
1135 * If 1 is returned the client is still alive and valid and
1136 * and other operations can be performed by the caller. Otherwise
1137 * if 0 is returned the client was destroied (i.e. after QUIT). */
1138 int processCommand(redisClient
*c
) {
1139 /* The QUIT command is handled separately. Normal command procs will
1140 * go through checking for replication and QUIT will cause trouble
1141 * when FORCE_REPLICATION is enabled and would be implemented in
1142 * a regular command proc. */
1143 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1144 addReply(c
,shared
.ok
);
1145 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1149 /* Now lookup the command and check ASAP about trivial error conditions
1150 * such as wrong arity, bad command name and so forth. */
1151 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1153 addReplyErrorFormat(c
,"unknown command '%s'",
1154 (char*)c
->argv
[0]->ptr
);
1156 } else if ((c
->cmd
->arity
> 0 && c
->cmd
->arity
!= c
->argc
) ||
1157 (c
->argc
< -c
->cmd
->arity
)) {
1158 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1163 /* Check if the user is authenticated */
1164 if (server
.requirepass
&& !c
->authenticated
&& c
->cmd
->proc
!= authCommand
)
1166 addReplyError(c
,"operation not permitted");
1170 /* If cluster is enabled, redirect here */
1171 if (server
.cluster_enabled
&&
1172 !(c
->cmd
->getkeys_proc
== NULL
&& c
->cmd
->firstkey
== 0)) {
1175 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1176 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1180 clusterNode
*n
= getNodeByQuery(c
,c
->cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1182 addReplyError(c
,"Multi keys request invalid in cluster");
1184 } else if (n
!= server
.cluster
.myself
) {
1185 addReplySds(c
,sdscatprintf(sdsempty(),
1186 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1187 hashslot
,n
->ip
,n
->port
));
1193 /* Handle the maxmemory directive.
1195 * First we try to free some memory if possible (if there are volatile
1196 * keys in the dataset). If there are not the only thing we can do
1197 * is returning an error. */
1198 if (server
.maxmemory
) freeMemoryIfNeeded();
1199 if (server
.maxmemory
&& (c
->cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1200 zmalloc_used_memory() > server
.maxmemory
)
1202 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1206 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1207 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1209 c
->cmd
->proc
!= subscribeCommand
&&
1210 c
->cmd
->proc
!= unsubscribeCommand
&&
1211 c
->cmd
->proc
!= psubscribeCommand
&&
1212 c
->cmd
->proc
!= punsubscribeCommand
) {
1213 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1217 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1218 * we are a slave with a broken link with master. */
1219 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1220 server
.repl_serve_stale_data
== 0 &&
1221 c
->cmd
->proc
!= infoCommand
&& c
->cmd
->proc
!= slaveofCommand
)
1224 "link with MASTER is down and slave-serve-stale-data is set to no");
1228 /* Loading DB? Return an error if the command is not INFO */
1229 if (server
.loading
&& c
->cmd
->proc
!= infoCommand
) {
1230 addReply(c
, shared
.loadingerr
);
1234 /* Lua script too slow? */
1235 if (server
.lua_timedout
&& c
->cmd
->proc
!= shutdownCommand
) {
1236 addReply(c
, shared
.slowscripterr
);
1240 /* Exec the command */
1241 if (c
->flags
& REDIS_MULTI
&&
1242 c
->cmd
->proc
!= execCommand
&& c
->cmd
->proc
!= discardCommand
&&
1243 c
->cmd
->proc
!= multiCommand
&& c
->cmd
->proc
!= watchCommand
)
1245 queueMultiCommand(c
);
1246 addReply(c
,shared
.queued
);
1253 /*================================== Shutdown =============================== */
1255 int prepareForShutdown() {
1256 redisLog(REDIS_WARNING
,"User requested shutdown...");
1257 /* Kill the saving child if there is a background saving in progress.
1258 We want to avoid race conditions, for instance our saving child may
1259 overwrite the synchronous saving did by SHUTDOWN. */
1260 if (server
.bgsavechildpid
!= -1) {
1261 redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!");
1262 kill(server
.bgsavechildpid
,SIGKILL
);
1263 rdbRemoveTempFile(server
.bgsavechildpid
);
1265 if (server
.appendonly
) {
1266 /* Kill the AOF saving child as the AOF we already have may be longer
1267 * but contains the full dataset anyway. */
1268 if (server
.bgrewritechildpid
!= -1) {
1269 redisLog(REDIS_WARNING
,
1270 "There is a child rewriting the AOF. Killing it!");
1271 kill(server
.bgrewritechildpid
,SIGKILL
);
1273 /* Append only file: fsync() the AOF and exit */
1274 redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file.");
1275 aof_fsync(server
.appendfd
);
1277 if (server
.saveparamslen
> 0) {
1278 redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting.");
1279 /* Snapshotting. Perform a SYNC SAVE and exit */
1280 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1281 /* Ooops.. error saving! The best we can do is to continue
1282 * operating. Note that if there was a background saving process,
1283 * in the next cron() Redis will be notified that the background
1284 * saving aborted, handling special stuff like slaves pending for
1285 * synchronization... */
1286 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit.");
1290 if (server
.daemonize
) {
1291 redisLog(REDIS_NOTICE
,"Removing the pid file.");
1292 unlink(server
.pidfile
);
1294 /* Close the listening sockets. Apparently this allows faster restarts. */
1295 if (server
.ipfd
!= -1) close(server
.ipfd
);
1296 if (server
.sofd
!= -1) close(server
.sofd
);
1297 if (server
.unixsocket
) {
1298 redisLog(REDIS_NOTICE
,"Removing the unix socket file.");
1299 unlink(server
.unixsocket
); /* don't care if this fails */
1302 redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye...");
1306 /*================================== Commands =============================== */
1308 void authCommand(redisClient
*c
) {
1309 if (!server
.requirepass
) {
1310 addReplyError(c
,"Client sent AUTH, but no password is set");
1311 } else if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1312 c
->authenticated
= 1;
1313 addReply(c
,shared
.ok
);
1315 c
->authenticated
= 0;
1316 addReplyError(c
,"invalid password");
1320 void pingCommand(redisClient
*c
) {
1321 addReply(c
,shared
.pong
);
1324 void echoCommand(redisClient
*c
) {
1325 addReplyBulk(c
,c
->argv
[1]);
1328 /* Convert an amount of bytes into a human readable string in the form
1329 * of 100B, 2G, 100M, 4K, and so forth. */
1330 void bytesToHuman(char *s
, unsigned long long n
) {
1335 sprintf(s
,"%lluB",n
);
1337 } else if (n
< (1024*1024)) {
1338 d
= (double)n
/(1024);
1339 sprintf(s
,"%.2fK",d
);
1340 } else if (n
< (1024LL*1024*1024)) {
1341 d
= (double)n
/(1024*1024);
1342 sprintf(s
,"%.2fM",d
);
1343 } else if (n
< (1024LL*1024*1024*1024)) {
1344 d
= (double)n
/(1024LL*1024*1024);
1345 sprintf(s
,"%.2fG",d
);
1349 /* Create the string returned by the INFO command. This is decoupled
1350 * by the INFO command itself as we need to report the same information
1351 * on memory corruption problems. */
1352 sds
genRedisInfoString(char *section
) {
1353 sds info
= sdsempty();
1354 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1356 struct rusage self_ru
, c_ru
;
1357 unsigned long lol
, bib
;
1358 int allsections
= 0, defsections
= 0;
1362 allsections
= strcasecmp(section
,"all") == 0;
1363 defsections
= strcasecmp(section
,"default") == 0;
1366 getrusage(RUSAGE_SELF
, &self_ru
);
1367 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1368 getClientsMaxBuffers(&lol
,&bib
);
1371 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1372 if (sections
++) info
= sdscat(info
,"\r\n");
1373 info
= sdscatprintf(info
,
1375 "redis_version:%s\r\n"
1376 "redis_git_sha1:%s\r\n"
1377 "redis_git_dirty:%d\r\n"
1379 "multiplexing_api:%s\r\n"
1380 "process_id:%ld\r\n"
1382 "uptime_in_seconds:%ld\r\n"
1383 "uptime_in_days:%ld\r\n"
1384 "lru_clock:%ld\r\n",
1387 strtol(redisGitDirty(),NULL
,10) > 0,
1388 (sizeof(long) == 8) ? "64" : "32",
1394 (unsigned long) server
.lruclock
);
1398 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1399 if (sections
++) info
= sdscat(info
,"\r\n");
1400 info
= sdscatprintf(info
,
1402 "connected_clients:%d\r\n"
1403 "client_longest_output_list:%lu\r\n"
1404 "client_biggest_input_buf:%lu\r\n"
1405 "blocked_clients:%d\r\n",
1406 listLength(server
.clients
)-listLength(server
.slaves
),
1408 server
.bpop_blocked_clients
);
1412 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1416 bytesToHuman(hmem
,zmalloc_used_memory());
1417 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1418 if (sections
++) info
= sdscat(info
,"\r\n");
1419 info
= sdscatprintf(info
,
1421 "used_memory:%zu\r\n"
1422 "used_memory_human:%s\r\n"
1423 "used_memory_rss:%zu\r\n"
1424 "used_memory_peak:%zu\r\n"
1425 "used_memory_peak_human:%s\r\n"
1426 "used_memory_lua:%lld\r\n"
1427 "mem_fragmentation_ratio:%.2f\r\n"
1428 "mem_allocator:%s\r\n",
1429 zmalloc_used_memory(),
1432 server
.stat_peak_memory
,
1434 ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL,
1435 zmalloc_get_fragmentation_ratio(),
1441 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1442 if (sections
++) info
= sdscat(info
,"\r\n");
1443 info
= sdscatprintf(info
,
1446 "aof_enabled:%d\r\n"
1447 "changes_since_last_save:%lld\r\n"
1448 "bgsave_in_progress:%d\r\n"
1449 "last_save_time:%ld\r\n"
1450 "bgrewriteaof_in_progress:%d\r\n",
1454 server
.bgsavechildpid
!= -1,
1456 server
.bgrewritechildpid
!= -1);
1458 if (server
.appendonly
) {
1459 info
= sdscatprintf(info
,
1460 "aof_current_size:%lld\r\n"
1461 "aof_base_size:%lld\r\n"
1462 "aof_pending_rewrite:%d\r\n",
1463 (long long) server
.appendonly_current_size
,
1464 (long long) server
.auto_aofrewrite_base_size
,
1465 server
.aofrewrite_scheduled
);
1468 if (server
.loading
) {
1470 time_t eta
, elapsed
;
1471 off_t remaining_bytes
= server
.loading_total_bytes
-
1472 server
.loading_loaded_bytes
;
1474 perc
= ((double)server
.loading_loaded_bytes
/
1475 server
.loading_total_bytes
) * 100;
1477 elapsed
= time(NULL
)-server
.loading_start_time
;
1479 eta
= 1; /* A fake 1 second figure if we don't have
1482 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1485 info
= sdscatprintf(info
,
1486 "loading_start_time:%ld\r\n"
1487 "loading_total_bytes:%llu\r\n"
1488 "loading_loaded_bytes:%llu\r\n"
1489 "loading_loaded_perc:%.2f\r\n"
1490 "loading_eta_seconds:%ld\r\n"
1491 ,(unsigned long) server
.loading_start_time
,
1492 (unsigned long long) server
.loading_total_bytes
,
1493 (unsigned long long) server
.loading_loaded_bytes
,
1501 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1502 if (sections
++) info
= sdscat(info
,"\r\n");
1503 info
= sdscatprintf(info
,
1505 "total_connections_received:%lld\r\n"
1506 "total_commands_processed:%lld\r\n"
1507 "expired_keys:%lld\r\n"
1508 "evicted_keys:%lld\r\n"
1509 "keyspace_hits:%lld\r\n"
1510 "keyspace_misses:%lld\r\n"
1511 "pubsub_channels:%ld\r\n"
1512 "pubsub_patterns:%u\r\n"
1513 "latest_fork_usec:%lld\r\n",
1514 server
.stat_numconnections
,
1515 server
.stat_numcommands
,
1516 server
.stat_expiredkeys
,
1517 server
.stat_evictedkeys
,
1518 server
.stat_keyspace_hits
,
1519 server
.stat_keyspace_misses
,
1520 dictSize(server
.pubsub_channels
),
1521 listLength(server
.pubsub_patterns
),
1522 server
.stat_fork_time
);
1526 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1527 if (sections
++) info
= sdscat(info
,"\r\n");
1528 info
= sdscatprintf(info
,
1531 server
.masterhost
== NULL
? "master" : "slave");
1532 if (server
.masterhost
) {
1533 info
= sdscatprintf(info
,
1534 "master_host:%s\r\n"
1535 "master_port:%d\r\n"
1536 "master_link_status:%s\r\n"
1537 "master_last_io_seconds_ago:%d\r\n"
1538 "master_sync_in_progress:%d\r\n"
1541 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1544 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1545 server
.replstate
== REDIS_REPL_TRANSFER
1548 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1549 info
= sdscatprintf(info
,
1550 "master_sync_left_bytes:%ld\r\n"
1551 "master_sync_last_io_seconds_ago:%d\r\n"
1552 ,(long)server
.repl_transfer_left
,
1553 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1557 if (server
.replstate
!= REDIS_REPL_CONNECTED
) {
1558 info
= sdscatprintf(info
,
1559 "master_link_down_since_seconds:%ld\r\n",
1560 (long)time(NULL
)-server
.repl_down_since
);
1563 info
= sdscatprintf(info
,
1564 "connected_slaves:%d\r\n",
1565 listLength(server
.slaves
));
1569 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1570 if (sections
++) info
= sdscat(info
,"\r\n");
1571 info
= sdscatprintf(info
,
1573 "used_cpu_sys:%.2f\r\n"
1574 "used_cpu_user:%.2f\r\n"
1575 "used_cpu_sys_children:%.2f\r\n"
1576 "used_cpu_user_children:%.2f\r\n",
1577 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1578 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1579 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1580 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000);
1584 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1585 if (sections
++) info
= sdscat(info
,"\r\n");
1586 info
= sdscatprintf(info
, "# Commandstats\r\n");
1587 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1588 for (j
= 0; j
< numcommands
; j
++) {
1589 struct redisCommand
*c
= redisCommandTable
+j
;
1591 if (!c
->calls
) continue;
1592 info
= sdscatprintf(info
,
1593 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1594 c
->name
, c
->calls
, c
->microseconds
,
1595 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1600 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1601 if (sections
++) info
= sdscat(info
,"\r\n");
1602 info
= sdscatprintf(info
,
1604 "cluster_enabled:%d\r\n",
1605 server
.cluster_enabled
);
1609 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1610 if (sections
++) info
= sdscat(info
,"\r\n");
1611 info
= sdscatprintf(info
, "# Keyspace\r\n");
1612 for (j
= 0; j
< server
.dbnum
; j
++) {
1613 long long keys
, vkeys
;
1615 keys
= dictSize(server
.db
[j
].dict
);
1616 vkeys
= dictSize(server
.db
[j
].expires
);
1617 if (keys
|| vkeys
) {
1618 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1626 void infoCommand(redisClient
*c
) {
1627 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1630 addReply(c
,shared
.syntaxerr
);
1633 sds info
= genRedisInfoString(section
);
1634 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1635 (unsigned long)sdslen(info
)));
1636 addReplySds(c
,info
);
1637 addReply(c
,shared
.crlf
);
1640 void monitorCommand(redisClient
*c
) {
1641 /* ignore MONITOR if aleady slave or in monitor mode */
1642 if (c
->flags
& REDIS_SLAVE
) return;
1644 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1646 listAddNodeTail(server
.monitors
,c
);
1647 addReply(c
,shared
.ok
);
1650 /* ============================ Maxmemory directive ======================== */
1652 /* This function gets called when 'maxmemory' is set on the config file to limit
1653 * the max memory used by the server, and we are out of memory.
1654 * This function will try to, in order:
1656 * - Free objects from the free list
1657 * - Try to remove keys with an EXPIRE set
1659 * It is not possible to free enough memory to reach used-memory < maxmemory
1660 * the server will start refusing commands that will enlarge even more the
1663 void freeMemoryIfNeeded(void) {
1664 /* Remove keys accordingly to the active policy as long as we are
1665 * over the memory limit. */
1666 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1668 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1669 int j
, k
, freed
= 0;
1671 for (j
= 0; j
< server
.dbnum
; j
++) {
1672 long bestval
= 0; /* just to prevent warning */
1674 struct dictEntry
*de
;
1675 redisDb
*db
= server
.db
+j
;
1678 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1679 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1681 dict
= server
.db
[j
].dict
;
1683 dict
= server
.db
[j
].expires
;
1685 if (dictSize(dict
) == 0) continue;
1687 /* volatile-random and allkeys-random policy */
1688 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1689 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1691 de
= dictGetRandomKey(dict
);
1692 bestkey
= dictGetKey(de
);
1695 /* volatile-lru and allkeys-lru policy */
1696 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1697 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1699 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1704 de
= dictGetRandomKey(dict
);
1705 thiskey
= dictGetKey(de
);
1706 /* When policy is volatile-lru we need an additonal lookup
1707 * to locate the real key, as dict is set to db->expires. */
1708 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1709 de
= dictFind(db
->dict
, thiskey
);
1711 thisval
= estimateObjectIdleTime(o
);
1713 /* Higher idle time is better candidate for deletion */
1714 if (bestkey
== NULL
|| thisval
> bestval
) {
1722 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1723 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1727 de
= dictGetRandomKey(dict
);
1728 thiskey
= dictGetKey(de
);
1729 thisval
= (long) dictGetVal(de
);
1731 /* Expire sooner (minor expire unix timestamp) is better
1732 * candidate for deletion */
1733 if (bestkey
== NULL
|| thisval
< bestval
) {
1740 /* Finally remove the selected key. */
1742 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1743 propagateExpire(db
,keyobj
);
1744 dbDelete(db
,keyobj
);
1745 server
.stat_evictedkeys
++;
1746 decrRefCount(keyobj
);
1750 if (!freed
) return; /* nothing to free... */
1754 /* =================================== Main! ================================ */
1757 int linuxOvercommitMemoryValue(void) {
1758 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1762 if (fgets(buf
,64,fp
) == NULL
) {
1771 void linuxOvercommitMemoryWarning(void) {
1772 if (linuxOvercommitMemoryValue() == 0) {
1773 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.");
1776 #endif /* __linux__ */
1778 void createPidFile(void) {
1779 /* Try to write the pid file in a best-effort way. */
1780 FILE *fp
= fopen(server
.pidfile
,"w");
1782 fprintf(fp
,"%d\n",(int)getpid());
1787 void daemonize(void) {
1790 if (fork() != 0) exit(0); /* parent exits */
1791 setsid(); /* create a new session */
1793 /* Every output goes to /dev/null. If Redis is daemonized but
1794 * the 'logfile' is set to 'stdout' in the configuration file
1795 * it will not log at all. */
1796 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1797 dup2(fd
, STDIN_FILENO
);
1798 dup2(fd
, STDOUT_FILENO
);
1799 dup2(fd
, STDERR_FILENO
);
1800 if (fd
> STDERR_FILENO
) close(fd
);
1805 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1806 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1811 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1812 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1816 void redisAsciiArt(void) {
1817 #include "asciilogo.h"
1818 char *buf
= zmalloc(1024*16);
1820 snprintf(buf
,1024*16,ascii_logo
,
1823 strtol(redisGitDirty(),NULL
,10) > 0,
1824 (sizeof(long) == 8) ? "64" : "32",
1825 server
.cluster_enabled
? "cluster" : "stand alone",
1829 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1833 int main(int argc
, char **argv
) {
1836 zmalloc_enable_thread_safeness();
1839 if (strcmp(argv
[1], "-v") == 0 ||
1840 strcmp(argv
[1], "--version") == 0) version();
1841 if (strcmp(argv
[1], "--help") == 0) usage();
1842 resetServerSaveParams();
1843 loadServerConfig(argv
[1]);
1844 } else if ((argc
> 2)) {
1847 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'");
1849 if (server
.daemonize
) daemonize();
1851 if (server
.daemonize
) createPidFile();
1853 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1855 linuxOvercommitMemoryWarning();
1858 if (server
.appendonly
) {
1859 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1860 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1862 if (rdbLoad(server
.dbfilename
) == REDIS_OK
) {
1863 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",
1864 (float)(ustime()-start
)/1000000);
1865 } else if (errno
!= ENOENT
) {
1866 redisLog(REDIS_WARNING
,"Fatal error loading the DB. Exiting.");
1870 if (server
.ipfd
> 0)
1871 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1872 if (server
.sofd
> 0)
1873 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1874 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1876 aeDeleteEventLoop(server
.el
);
1880 #ifdef HAVE_BACKTRACE
1881 static void *getMcontextEip(ucontext_t
*uc
) {
1882 #if defined(__FreeBSD__)
1883 return (void*) uc
->uc_mcontext
.mc_eip
;
1884 #elif defined(__dietlibc__)
1885 return (void*) uc
->uc_mcontext
.eip
;
1886 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1888 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1890 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1892 return (void*) uc
->uc_mcontext
->__ss
.__srr0
;
1894 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1895 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1896 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1898 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1900 #elif defined(__i386__)
1901 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1902 #elif defined(__X86_64__) || defined(__x86_64__)
1903 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1904 #elif defined(__ia64__) /* Linux IA64 */
1905 return (void*) uc
->uc_mcontext
.sc_ip
;
1911 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1913 char **messages
= NULL
;
1914 int i
, trace_size
= 0;
1915 ucontext_t
*uc
= (ucontext_t
*) secret
;
1917 struct sigaction act
;
1918 REDIS_NOTUSED(info
);
1920 redisLog(REDIS_WARNING
,
1921 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1922 infostring
= genRedisInfoString("all");
1923 redisLogRaw(REDIS_WARNING
, infostring
);
1924 /* It's not safe to sdsfree() the returned string under memory
1925 * corruption conditions. Let it leak as we are going to abort */
1927 trace_size
= backtrace(trace
, 100);
1928 /* overwrite sigaction with caller's address */
1929 if (getMcontextEip(uc
) != NULL
) {
1930 trace
[1] = getMcontextEip(uc
);
1932 messages
= backtrace_symbols(trace
, trace_size
);
1934 for (i
=1; i
<trace_size
; ++i
)
1935 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1937 /* free(messages); Don't call free() with possibly corrupted memory. */
1938 if (server
.daemonize
) unlink(server
.pidfile
);
1940 /* Make sure we exit with the right signal at the end. So for instance
1941 * the core will be dumped if enabled. */
1942 sigemptyset (&act
.sa_mask
);
1943 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1944 * is used. Otherwise, sa_handler is used */
1945 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1946 act
.sa_handler
= SIG_DFL
;
1947 sigaction (sig
, &act
, NULL
);
1950 #endif /* HAVE_BACKTRACE */
1952 static void sigtermHandler(int sig
) {
1955 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1956 server
.shutdown_asap
= 1;
1959 void setupSignalHandlers(void) {
1960 struct sigaction act
;
1962 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1963 * Otherwise, sa_handler is used. */
1964 sigemptyset(&act
.sa_mask
);
1965 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1966 act
.sa_handler
= sigtermHandler
;
1967 sigaction(SIGTERM
, &act
, NULL
);
1969 #ifdef HAVE_BACKTRACE
1970 sigemptyset(&act
.sa_mask
);
1971 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1972 act
.sa_sigaction
= sigsegvHandler
;
1973 sigaction(SIGSEGV
, &act
, NULL
);
1974 sigaction(SIGBUS
, &act
, NULL
);
1975 sigaction(SIGFPE
, &act
, NULL
);
1976 sigaction(SIGILL
, &act
, NULL
);