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.
41 #include <arpa/inet.h>
45 #include <sys/resource.h>
50 #include <sys/resource.h>
52 /* Our shared "common" objects */
54 struct sharedObjectsStruct shared
;
56 /* Global vars that are actually used as constants. The following double
57 * values are used for double on-disk serialization, and are initialized
58 * at runtime to avoid strange compiler optimizations. */
60 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
62 /*================================= Globals ================================= */
65 struct redisServer server
; /* server global state */
66 struct redisCommand
*commandTable
;
70 * Every entry is composed of the following fields:
72 * name: a string representing the command name.
73 * function: pointer to the C function implementing the command.
74 * arity: number of arguments, it is possible to use -N to say >= N
75 * sflags: command flags as string. See below for a table of flags.
76 * flags: flags as bitmask. Computed by Redis using the 'sflags' field.
77 * get_keys_proc: an optional function to get key arguments from a command.
78 * This is only used when the following three fields are not
79 * enough to specify what arguments are keys.
80 * first_key_index: first argument that is a key
81 * last_key_index: last argument that is a key
82 * key_step: step to get all the keys from first to last argument. For instance
83 * in MSET the step is two since arguments are key,val,key,val,...
84 * microseconds: microseconds of total execution time for this command.
85 * calls: total number of calls of this command.
87 * The flags, microseconds and calls fields are computed by Redis and should
88 * always be set to zero.
90 * Command flags are expressed using strings where every character represents
91 * a flag. Later the populateCommandTable() function will take care of
92 * populating the real 'flags' field using this characters.
94 * This is the meaning of the flags:
96 * w: write command (may modify the key space).
97 * r: read command (will never modify the key space).
98 * m: may increase memory usage once called. Don't allow if out of memory.
99 * a: admin command, like SAVE or SHUTDOWN.
100 * p: Pub/Sub related command.
101 * f: force replication of this command, regarless of server.dirty.
102 * s: command not allowed in scripts.
103 * R: random command. Command is not deterministic, that is, the same command
104 * with the same arguments, with the same key space, may have different
105 * results. For instance SPOP and RANDOMKEY are two random commands. */
106 struct redisCommand redisCommandTable
[] = {
107 {"get",getCommand
,2,"r",0,NULL
,1,1,1,0,0},
108 {"set",setCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
109 {"setnx",setnxCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
110 {"setex",setexCommand
,4,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
111 {"psetex",psetexCommand
,4,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
112 {"append",appendCommand
,3,"wm",0,NULL
,1,1,1,0,0},
113 {"strlen",strlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
114 {"del",delCommand
,-2,"w",0,noPreloadGetKeys
,1,-1,1,0,0},
115 {"exists",existsCommand
,2,"r",0,NULL
,1,1,1,0,0},
116 {"setbit",setbitCommand
,4,"wm",0,NULL
,1,1,1,0,0},
117 {"getbit",getbitCommand
,3,"r",0,NULL
,1,1,1,0,0},
118 {"setrange",setrangeCommand
,4,"wm",0,NULL
,1,1,1,0,0},
119 {"getrange",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
120 {"substr",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
121 {"incr",incrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
122 {"decr",decrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
123 {"mget",mgetCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
124 {"rpush",rpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
125 {"lpush",lpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
126 {"rpushx",rpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
127 {"lpushx",lpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
128 {"linsert",linsertCommand
,5,"wm",0,NULL
,1,1,1,0,0},
129 {"rpop",rpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
130 {"lpop",lpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
131 {"brpop",brpopCommand
,-3,"ws",0,NULL
,1,1,1,0,0},
132 {"brpoplpush",brpoplpushCommand
,4,"wms",0,NULL
,1,2,1,0,0},
133 {"blpop",blpopCommand
,-3,"ws",0,NULL
,1,-2,1,0,0},
134 {"llen",llenCommand
,2,"r",0,NULL
,1,1,1,0,0},
135 {"lindex",lindexCommand
,3,"r",0,NULL
,1,1,1,0,0},
136 {"lset",lsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
137 {"lrange",lrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
138 {"ltrim",ltrimCommand
,4,"w",0,NULL
,1,1,1,0,0},
139 {"lrem",lremCommand
,4,"w",0,NULL
,1,1,1,0,0},
140 {"rpoplpush",rpoplpushCommand
,3,"wm",0,NULL
,1,2,1,0,0},
141 {"sadd",saddCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
142 {"srem",sremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
143 {"smove",smoveCommand
,4,"w",0,NULL
,1,2,1,0,0},
144 {"sismember",sismemberCommand
,3,"r",0,NULL
,1,1,1,0,0},
145 {"scard",scardCommand
,2,"r",0,NULL
,1,1,1,0,0},
146 {"spop",spopCommand
,2,"wRs",0,NULL
,1,1,1,0,0},
147 {"srandmember",srandmemberCommand
,2,"rR",0,NULL
,1,1,1,0,0},
148 {"sinter",sinterCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
149 {"sinterstore",sinterstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0},
150 {"sunion",sunionCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
151 {"sunionstore",sunionstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0},
152 {"sdiff",sdiffCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
153 {"sdiffstore",sdiffstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0},
154 {"smembers",sinterCommand
,2,"r",0,NULL
,1,1,1,0,0},
155 {"zadd",zaddCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
156 {"zincrby",zincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
157 {"zrem",zremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
158 {"zremrangebyscore",zremrangebyscoreCommand
,4,"w",0,NULL
,1,1,1,0,0},
159 {"zremrangebyrank",zremrangebyrankCommand
,4,"w",0,NULL
,1,1,1,0,0},
160 {"zunionstore",zunionstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
161 {"zinterstore",zinterstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
162 {"zrange",zrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
163 {"zrangebyscore",zrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
164 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
165 {"zcount",zcountCommand
,4,"r",0,NULL
,1,1,1,0,0},
166 {"zrevrange",zrevrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
167 {"zcard",zcardCommand
,2,"r",0,NULL
,1,1,1,0,0},
168 {"zscore",zscoreCommand
,3,"r",0,NULL
,1,1,1,0,0},
169 {"zrank",zrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
170 {"zrevrank",zrevrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
171 {"hset",hsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
172 {"hsetnx",hsetnxCommand
,4,"wm",0,NULL
,1,1,1,0,0},
173 {"hget",hgetCommand
,3,"r",0,NULL
,1,1,1,0,0},
174 {"hmset",hmsetCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
175 {"hmget",hmgetCommand
,-3,"r",0,NULL
,1,1,1,0,0},
176 {"hincrby",hincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
177 {"hincrbyfloat",hincrbyfloatCommand
,4,"wm",0,NULL
,1,1,1,0,0},
178 {"hdel",hdelCommand
,-3,"w",0,NULL
,1,1,1,0,0},
179 {"hlen",hlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
180 {"hkeys",hkeysCommand
,2,"r",0,NULL
,1,1,1,0,0},
181 {"hvals",hvalsCommand
,2,"r",0,NULL
,1,1,1,0,0},
182 {"hgetall",hgetallCommand
,2,"r",0,NULL
,1,1,1,0,0},
183 {"hexists",hexistsCommand
,3,"r",0,NULL
,1,1,1,0,0},
184 {"incrby",incrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
185 {"decrby",decrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
186 {"incrbyfloat",incrbyfloatCommand
,3,"wm",0,NULL
,1,1,1,0,0},
187 {"getset",getsetCommand
,3,"wm",0,NULL
,1,1,1,0,0},
188 {"mset",msetCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
189 {"msetnx",msetnxCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
190 {"randomkey",randomkeyCommand
,1,"rR",0,NULL
,0,0,0,0,0},
191 {"select",selectCommand
,2,"r",0,NULL
,0,0,0,0,0},
192 {"move",moveCommand
,3,"w",0,NULL
,1,1,1,0,0},
193 {"rename",renameCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
194 {"renamenx",renamenxCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
195 {"expire",expireCommand
,3,"w",0,NULL
,1,1,1,0,0},
196 {"expireat",expireatCommand
,3,"w",0,NULL
,1,1,1,0,0},
197 {"pexpire",pexpireCommand
,3,"w",0,NULL
,1,1,1,0,0},
198 {"pexpireat",pexpireatCommand
,3,"w",0,NULL
,1,1,1,0,0},
199 {"keys",keysCommand
,2,"r",0,NULL
,0,0,0,0,0},
200 {"dbsize",dbsizeCommand
,1,"r",0,NULL
,0,0,0,0,0},
201 {"auth",authCommand
,2,"rs",0,NULL
,0,0,0,0,0},
202 {"ping",pingCommand
,1,"r",0,NULL
,0,0,0,0,0},
203 {"echo",echoCommand
,2,"r",0,NULL
,0,0,0,0,0},
204 {"save",saveCommand
,1,"ars",0,NULL
,0,0,0,0,0},
205 {"bgsave",bgsaveCommand
,1,"ar",0,NULL
,0,0,0,0,0},
206 {"bgrewriteaof",bgrewriteaofCommand
,1,"ar",0,NULL
,0,0,0,0,0},
207 {"shutdown",shutdownCommand
,-1,"ar",0,NULL
,0,0,0,0,0},
208 {"lastsave",lastsaveCommand
,1,"r",0,NULL
,0,0,0,0,0},
209 {"type",typeCommand
,2,"r",0,NULL
,1,1,1,0,0},
210 {"multi",multiCommand
,1,"rs",0,NULL
,0,0,0,0,0},
211 {"exec",execCommand
,1,"wms",0,NULL
,0,0,0,0,0},
212 {"discard",discardCommand
,1,"rs",0,NULL
,0,0,0,0,0},
213 {"sync",syncCommand
,1,"ars",0,NULL
,0,0,0,0,0},
214 {"flushdb",flushdbCommand
,1,"w",0,NULL
,0,0,0,0,0},
215 {"flushall",flushallCommand
,1,"w",0,NULL
,0,0,0,0,0},
216 {"sort",sortCommand
,-2,"wm",0,NULL
,1,1,1,0,0},
217 {"info",infoCommand
,-1,"r",0,NULL
,0,0,0,0,0},
218 {"monitor",monitorCommand
,1,"ars",0,NULL
,0,0,0,0,0},
219 {"ttl",ttlCommand
,2,"r",0,NULL
,1,1,1,0,0},
220 {"pttl",pttlCommand
,2,"r",0,NULL
,1,1,1,0,0},
221 {"persist",persistCommand
,2,"w",0,NULL
,1,1,1,0,0},
222 {"slaveof",slaveofCommand
,3,"aws",0,NULL
,0,0,0,0,0},
223 {"debug",debugCommand
,-2,"aws",0,NULL
,0,0,0,0,0},
224 {"config",configCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
225 {"subscribe",subscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
226 {"unsubscribe",unsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
227 {"psubscribe",psubscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
228 {"punsubscribe",punsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
229 {"publish",publishCommand
,3,"rpf",0,NULL
,0,0,0,0,0},
230 {"watch",watchCommand
,-2,"rs",0,noPreloadGetKeys
,1,-1,1,0,0},
231 {"unwatch",unwatchCommand
,1,"rs",0,NULL
,0,0,0,0,0},
232 {"cluster",clusterCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
233 {"restore",restoreCommand
,4,"awm",0,NULL
,1,1,1,0,0},
234 {"migrate",migrateCommand
,6,"aw",0,NULL
,0,0,0,0,0},
235 {"asking",askingCommand
,1,"r",0,NULL
,0,0,0,0,0},
236 {"dump",dumpCommand
,2,"ar",0,NULL
,1,1,1,0,0},
237 {"object",objectCommand
,-2,"r",0,NULL
,2,2,2,0,0},
238 {"client",clientCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
239 {"eval",evalCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
240 {"evalsha",evalShaCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
241 {"slowlog",slowlogCommand
,-2,"r",0,NULL
,0,0,0,0,0},
242 {"script",scriptCommand
,-2,"ras",0,NULL
,0,0,0,0,0}
245 /*============================ Utility functions ============================ */
247 /* Low level logging. To use only for very big messages, otherwise
248 * redisLog() is to prefer. */
249 void redisLogRaw(int level
, const char *msg
) {
250 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
251 const char *c
= ".-*#";
252 time_t now
= time(NULL
);
255 int rawmode
= (level
& REDIS_LOG_RAW
);
257 level
&= 0xff; /* clear flags */
258 if (level
< server
.verbosity
) return;
260 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
264 fprintf(fp
,"%s",msg
);
266 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
267 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
271 if (server
.logfile
) fclose(fp
);
273 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
276 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
277 * is used across the code. The raw version is only used in order to dump
278 * the INFO output on crash. */
279 void redisLog(int level
, const char *fmt
, ...) {
281 char msg
[REDIS_MAX_LOGMSG_LEN
];
283 if ((level
&0xff) < server
.verbosity
) return;
286 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
289 redisLogRaw(level
,msg
);
292 /* Redis generally does not try to recover from out of memory conditions
293 * when allocating objects or strings, it is not clear if it will be possible
294 * to report this condition to the client since the networking layer itself
295 * is based on heap allocation for send buffers, so we simply abort.
296 * At least the code will be simpler to read... */
297 void oom(const char *msg
) {
298 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
303 /* Return the UNIX time in microseconds */
304 long long ustime(void) {
308 gettimeofday(&tv
, NULL
);
309 ust
= ((long long)tv
.tv_sec
)*1000000;
314 /* Return the UNIX time in milliseconds */
315 long long mstime(void) {
316 return ustime()/1000;
319 /*====================== Hash table type implementation ==================== */
321 /* This is an hash table type that uses the SDS dynamic strings libary as
322 * keys and radis objects as values (objects can hold SDS strings,
325 void dictVanillaFree(void *privdata
, void *val
)
327 DICT_NOTUSED(privdata
);
331 void dictListDestructor(void *privdata
, void *val
)
333 DICT_NOTUSED(privdata
);
334 listRelease((list
*)val
);
337 int dictSdsKeyCompare(void *privdata
, const void *key1
,
341 DICT_NOTUSED(privdata
);
343 l1
= sdslen((sds
)key1
);
344 l2
= sdslen((sds
)key2
);
345 if (l1
!= l2
) return 0;
346 return memcmp(key1
, key2
, l1
) == 0;
349 /* A case insensitive version used for the command lookup table. */
350 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
353 DICT_NOTUSED(privdata
);
355 return strcasecmp(key1
, key2
) == 0;
358 void dictRedisObjectDestructor(void *privdata
, void *val
)
360 DICT_NOTUSED(privdata
);
362 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
366 void dictSdsDestructor(void *privdata
, void *val
)
368 DICT_NOTUSED(privdata
);
373 int dictObjKeyCompare(void *privdata
, const void *key1
,
376 const robj
*o1
= key1
, *o2
= key2
;
377 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
380 unsigned int dictObjHash(const void *key
) {
382 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
385 unsigned int dictSdsHash(const void *key
) {
386 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
389 unsigned int dictSdsCaseHash(const void *key
) {
390 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
393 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
396 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
399 if (o1
->encoding
== REDIS_ENCODING_INT
&&
400 o2
->encoding
== REDIS_ENCODING_INT
)
401 return o1
->ptr
== o2
->ptr
;
403 o1
= getDecodedObject(o1
);
404 o2
= getDecodedObject(o2
);
405 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
411 unsigned int dictEncObjHash(const void *key
) {
412 robj
*o
= (robj
*) key
;
414 if (o
->encoding
== REDIS_ENCODING_RAW
) {
415 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
417 if (o
->encoding
== REDIS_ENCODING_INT
) {
421 len
= ll2string(buf
,32,(long)o
->ptr
);
422 return dictGenHashFunction((unsigned char*)buf
, len
);
426 o
= getDecodedObject(o
);
427 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
434 /* Sets type hash table */
435 dictType setDictType
= {
436 dictEncObjHash
, /* hash function */
439 dictEncObjKeyCompare
, /* key compare */
440 dictRedisObjectDestructor
, /* key destructor */
441 NULL
/* val destructor */
444 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
445 dictType zsetDictType
= {
446 dictEncObjHash
, /* hash function */
449 dictEncObjKeyCompare
, /* key compare */
450 dictRedisObjectDestructor
, /* key destructor */
451 NULL
/* val destructor */
454 /* Db->dict, keys are sds strings, vals are Redis objects. */
455 dictType dbDictType
= {
456 dictSdsHash
, /* hash function */
459 dictSdsKeyCompare
, /* key compare */
460 dictSdsDestructor
, /* key destructor */
461 dictRedisObjectDestructor
/* val destructor */
465 dictType keyptrDictType
= {
466 dictSdsHash
, /* hash function */
469 dictSdsKeyCompare
, /* key compare */
470 NULL
, /* key destructor */
471 NULL
/* val destructor */
474 /* Command table. sds string -> command struct pointer. */
475 dictType commandTableDictType
= {
476 dictSdsCaseHash
, /* hash function */
479 dictSdsKeyCaseCompare
, /* key compare */
480 dictSdsDestructor
, /* key destructor */
481 NULL
/* val destructor */
484 /* Hash type hash table (note that small hashes are represented with zimpaps) */
485 dictType hashDictType
= {
486 dictEncObjHash
, /* hash function */
489 dictEncObjKeyCompare
, /* key compare */
490 dictRedisObjectDestructor
, /* key destructor */
491 dictRedisObjectDestructor
/* val destructor */
494 /* Keylist hash table type has unencoded redis objects as keys and
495 * lists as values. It's used for blocking operations (BLPOP) and to
496 * map swapped keys to a list of clients waiting for this keys to be loaded. */
497 dictType keylistDictType
= {
498 dictObjHash
, /* hash function */
501 dictObjKeyCompare
, /* key compare */
502 dictRedisObjectDestructor
, /* key destructor */
503 dictListDestructor
/* val destructor */
506 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
507 * clusterNode structures. */
508 dictType clusterNodesDictType
= {
509 dictSdsHash
, /* hash function */
512 dictSdsKeyCompare
, /* key compare */
513 dictSdsDestructor
, /* key destructor */
514 NULL
/* val destructor */
517 int htNeedsResize(dict
*dict
) {
518 long long size
, used
;
520 size
= dictSlots(dict
);
521 used
= dictSize(dict
);
522 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
523 (used
*100/size
< REDIS_HT_MINFILL
));
526 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
527 * we resize the hash table to save memory */
528 void tryResizeHashTables(void) {
531 for (j
= 0; j
< server
.dbnum
; j
++) {
532 if (htNeedsResize(server
.db
[j
].dict
))
533 dictResize(server
.db
[j
].dict
);
534 if (htNeedsResize(server
.db
[j
].expires
))
535 dictResize(server
.db
[j
].expires
);
539 /* Our hash table implementation performs rehashing incrementally while
540 * we write/read from the hash table. Still if the server is idle, the hash
541 * table will use two tables for a long time. So we try to use 1 millisecond
542 * of CPU time at every serverCron() loop in order to rehash some key. */
543 void incrementallyRehash(void) {
546 for (j
= 0; j
< server
.dbnum
; j
++) {
547 if (dictIsRehashing(server
.db
[j
].dict
)) {
548 dictRehashMilliseconds(server
.db
[j
].dict
,1);
549 break; /* already used our millisecond for this loop... */
554 /* This function is called once a background process of some kind terminates,
555 * as we want to avoid resizing the hash tables when there is a child in order
556 * to play well with copy-on-write (otherwise when a resize happens lots of
557 * memory pages are copied). The goal of this function is to update the ability
558 * for dict.c to resize the hash tables accordingly to the fact we have o not
560 void updateDictResizePolicy(void) {
561 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1)
567 /* ======================= Cron: called every 100 ms ======================== */
569 /* Try to expire a few timed out keys. The algorithm used is adaptive and
570 * will use few CPU cycles if there are few expiring keys, otherwise
571 * it will get more aggressive to avoid that too much memory is used by
572 * keys that can be removed from the keyspace. */
573 void activeExpireCycle(void) {
576 for (j
= 0; j
< server
.dbnum
; j
++) {
578 redisDb
*db
= server
.db
+j
;
580 /* Continue to expire if at the end of the cycle more than 25%
581 * of the keys were expired. */
583 long num
= dictSize(db
->expires
);
584 long long now
= mstime();
587 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
588 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
593 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
594 t
= dictGetSignedIntegerVal(de
);
596 sds key
= dictGetKey(de
);
597 robj
*keyobj
= createStringObject(key
,sdslen(key
));
599 propagateExpire(db
,keyobj
);
601 decrRefCount(keyobj
);
603 server
.stat_expiredkeys
++;
606 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
610 void updateLRUClock(void) {
611 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
615 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
616 int j
, loops
= server
.cronloops
;
617 REDIS_NOTUSED(eventLoop
);
619 REDIS_NOTUSED(clientData
);
621 /* We take a cached value of the unix time in the global state because
622 * with virtual memory and aging there is to store the current time
623 * in objects at every object access, and accuracy is not needed.
624 * To access a global var is faster than calling time(NULL) */
625 server
.unixtime
= time(NULL
);
627 /* We have just 22 bits per object for LRU information.
628 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
629 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
631 * Note that even if this will wrap after 1.5 years it's not a problem,
632 * everything will still work but just some object will appear younger
633 * to Redis. But for this to happen a given object should never be touched
636 * Note that you can change the resolution altering the
637 * REDIS_LRU_CLOCK_RESOLUTION define.
641 /* Record the max memory used since the server was started. */
642 if (zmalloc_used_memory() > server
.stat_peak_memory
)
643 server
.stat_peak_memory
= zmalloc_used_memory();
645 /* We received a SIGTERM, shutting down here in a safe way, as it is
646 * not ok doing so inside the signal handler. */
647 if (server
.shutdown_asap
) {
648 if (prepareForShutdown(0) == REDIS_OK
) exit(0);
649 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
652 /* Show some info about non-empty databases */
653 for (j
= 0; j
< server
.dbnum
; j
++) {
654 long long size
, used
, vkeys
;
656 size
= dictSlots(server
.db
[j
].dict
);
657 used
= dictSize(server
.db
[j
].dict
);
658 vkeys
= dictSize(server
.db
[j
].expires
);
659 if (!(loops
% 50) && (used
|| vkeys
)) {
660 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
661 /* dictPrintStats(server.dict); */
665 /* We don't want to resize the hash tables while a bacground saving
666 * is in progress: the saving child is created using fork() that is
667 * implemented with a copy-on-write semantic in most modern systems, so
668 * if we resize the HT while there is the saving child at work actually
669 * a lot of memory movements in the parent will cause a lot of pages
671 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1) {
672 if (!(loops
% 10)) tryResizeHashTables();
673 if (server
.activerehashing
) incrementallyRehash();
676 /* Show information about connected clients */
678 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
679 listLength(server
.clients
)-listLength(server
.slaves
),
680 listLength(server
.slaves
),
681 zmalloc_used_memory());
684 /* Close connections of timedout clients */
685 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
686 closeTimedoutClients();
688 /* Start a scheduled AOF rewrite if this was requested by the user while
689 * a BGSAVE was in progress. */
690 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1 &&
691 server
.aof_rewrite_scheduled
)
693 rewriteAppendOnlyFileBackground();
696 /* Check if a background saving or AOF rewrite in progress terminated. */
697 if (server
.rdb_child_pid
!= -1 || server
.aof_child_pid
!= -1) {
701 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
702 int exitcode
= WEXITSTATUS(statloc
);
705 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
707 if (pid
== server
.rdb_child_pid
) {
708 backgroundSaveDoneHandler(exitcode
,bysignal
);
710 backgroundRewriteDoneHandler(exitcode
,bysignal
);
712 updateDictResizePolicy();
715 time_t now
= time(NULL
);
717 /* If there is not a background saving/rewrite in progress check if
718 * we have to save/rewrite now */
719 for (j
= 0; j
< server
.saveparamslen
; j
++) {
720 struct saveparam
*sp
= server
.saveparams
+j
;
722 if (server
.dirty
>= sp
->changes
&&
723 now
-server
.lastsave
> sp
->seconds
) {
724 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
725 sp
->changes
, sp
->seconds
);
726 rdbSaveBackground(server
.rdb_filename
);
731 /* Trigger an AOF rewrite if needed */
732 if (server
.rdb_child_pid
== -1 &&
733 server
.aof_child_pid
== -1 &&
734 server
.aof_rewrite_perc
&&
735 server
.aof_current_size
> server
.aof_rewrite_min_size
)
737 long long base
= server
.aof_rewrite_base_size
?
738 server
.aof_rewrite_base_size
: 1;
739 long long growth
= (server
.aof_current_size
*100/base
) - 100;
740 if (growth
>= server
.aof_rewrite_perc
) {
741 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
742 rewriteAppendOnlyFileBackground();
748 /* If we postponed an AOF buffer flush, let's try to do it every time the
749 * cron function is called. */
750 if (server
.aof_flush_postponed_start
) flushAppendOnlyFile(0);
752 /* Expire a few keys per cycle, only if this is a master.
753 * On slaves we wait for DEL operations synthesized by the master
754 * in order to guarantee a strict consistency. */
755 if (server
.masterhost
== NULL
) activeExpireCycle();
757 /* Replication cron function -- used to reconnect to master and
758 * to detect transfer failures. */
759 if (!(loops
% 10)) replicationCron();
761 /* Run other sub-systems specific cron jobs */
762 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
768 /* This function gets called every time Redis is entering the
769 * main loop of the event driven library, that is, before to sleep
770 * for ready file descriptors. */
771 void beforeSleep(struct aeEventLoop
*eventLoop
) {
772 REDIS_NOTUSED(eventLoop
);
776 /* Try to process pending commands for clients that were just unblocked. */
777 while (listLength(server
.unblocked_clients
)) {
778 ln
= listFirst(server
.unblocked_clients
);
779 redisAssert(ln
!= NULL
);
781 listDelNode(server
.unblocked_clients
,ln
);
782 c
->flags
&= ~REDIS_UNBLOCKED
;
784 /* Process remaining data in the input buffer. */
785 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) {
786 server
.current_client
= c
;
787 processInputBuffer(c
);
788 server
.current_client
= NULL
;
792 /* Write the AOF buffer on disk */
793 flushAppendOnlyFile(0);
796 /* =========================== Server initialization ======================== */
798 void createSharedObjects(void) {
801 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
802 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
803 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
804 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
805 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
806 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
807 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
808 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
809 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
810 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
811 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
812 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
813 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
814 "-ERR Operation against a key holding the wrong kind of value\r\n"));
815 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
816 "-ERR no such key\r\n"));
817 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
818 "-ERR syntax error\r\n"));
819 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
820 "-ERR source and destination objects are the same\r\n"));
821 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
822 "-ERR index out of range\r\n"));
823 shared
.noscripterr
= createObject(REDIS_STRING
,sdsnew(
824 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
825 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
826 "-LOADING Redis is loading the dataset in memory\r\n"));
827 shared
.slowscripterr
= createObject(REDIS_STRING
,sdsnew(
828 "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n"));
829 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
830 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
831 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
832 shared
.select0
= createStringObject("select 0\r\n",10);
833 shared
.select1
= createStringObject("select 1\r\n",10);
834 shared
.select2
= createStringObject("select 2\r\n",10);
835 shared
.select3
= createStringObject("select 3\r\n",10);
836 shared
.select4
= createStringObject("select 4\r\n",10);
837 shared
.select5
= createStringObject("select 5\r\n",10);
838 shared
.select6
= createStringObject("select 6\r\n",10);
839 shared
.select7
= createStringObject("select 7\r\n",10);
840 shared
.select8
= createStringObject("select 8\r\n",10);
841 shared
.select9
= createStringObject("select 9\r\n",10);
842 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
843 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
844 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
845 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
846 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
847 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
848 shared
.mbulk3
= createStringObject("*3\r\n",4);
849 shared
.mbulk4
= createStringObject("*4\r\n",4);
850 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
851 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
852 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
856 void initServerConfig() {
857 server
.port
= REDIS_SERVERPORT
;
858 server
.bindaddr
= NULL
;
859 server
.unixsocket
= NULL
;
860 server
.unixsocketperm
= 0;
863 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
864 server
.verbosity
= REDIS_NOTICE
;
865 server
.maxidletime
= REDIS_MAXIDLETIME
;
866 server
.client_max_querybuf_len
= REDIS_MAX_QUERYBUF_LEN
;
867 server
.saveparams
= NULL
;
869 server
.logfile
= NULL
; /* NULL = log on standard output */
870 server
.syslog_enabled
= 0;
871 server
.syslog_ident
= zstrdup("redis");
872 server
.syslog_facility
= LOG_LOCAL0
;
873 server
.daemonize
= 0;
874 server
.aof_state
= REDIS_AOF_OFF
;
875 server
.aof_fsync
= AOF_FSYNC_EVERYSEC
;
876 server
.aof_no_fsync_on_rewrite
= 0;
877 server
.aof_rewrite_perc
= REDIS_AOF_REWRITE_PERC
;
878 server
.aof_rewrite_min_size
= REDIS_AOF_REWRITE_MIN_SIZE
;
879 server
.aof_rewrite_base_size
= 0;
880 server
.aof_rewrite_scheduled
= 0;
881 server
.aof_last_fsync
= time(NULL
);
883 server
.aof_selected_db
= -1; /* Make sure the first time will not match */
884 server
.aof_flush_postponed_start
= 0;
885 server
.pidfile
= zstrdup("/var/run/redis.pid");
886 server
.rdb_filename
= zstrdup("dump.rdb");
887 server
.aof_filename
= zstrdup("appendonly.aof");
888 server
.requirepass
= NULL
;
889 server
.rdb_compression
= 1;
890 server
.activerehashing
= 1;
891 server
.maxclients
= REDIS_MAX_CLIENTS
;
892 server
.bpop_blocked_clients
= 0;
893 server
.maxmemory
= 0;
894 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
895 server
.maxmemory_samples
= 3;
896 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
897 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
898 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
899 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
900 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
901 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
902 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
903 server
.shutdown_asap
= 0;
904 server
.repl_ping_slave_period
= REDIS_REPL_PING_SLAVE_PERIOD
;
905 server
.repl_timeout
= REDIS_REPL_TIMEOUT
;
906 server
.cluster_enabled
= 0;
907 server
.cluster
.configfile
= zstrdup("nodes.conf");
908 server
.lua_caller
= NULL
;
909 server
.lua_time_limit
= REDIS_LUA_TIME_LIMIT
;
910 server
.lua_client
= NULL
;
911 server
.lua_timedout
= 0;
914 resetServerSaveParams();
916 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
917 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
918 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
919 /* Replication related */
920 server
.masterauth
= NULL
;
921 server
.masterhost
= NULL
;
922 server
.masterport
= 6379;
923 server
.master
= NULL
;
924 server
.repl_state
= REDIS_REPL_NONE
;
925 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
926 server
.repl_serve_stale_data
= 1;
927 server
.repl_down_since
= -1;
929 /* Double constants initialization */
931 R_PosInf
= 1.0/R_Zero
;
932 R_NegInf
= -1.0/R_Zero
;
933 R_Nan
= R_Zero
/R_Zero
;
935 /* Command table -- we intiialize it here as it is part of the
936 * initial configuration, since command names may be changed via
937 * redis.conf using the rename-command directive. */
938 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
939 populateCommandTable();
940 server
.delCommand
= lookupCommandByCString("del");
941 server
.multiCommand
= lookupCommandByCString("multi");
944 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
945 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
948 server
.assert_failed
= "<no assertion failed>";
949 server
.assert_file
= "<no file>";
950 server
.assert_line
= 0;
951 server
.bug_report_start
= 0;
954 /* This function will try to raise the max number of open files accordingly to
955 * the configured max number of clients. It will also account for 32 additional
956 * file descriptors as we need a few more for persistence, listening
957 * sockets, log files and so forth.
959 * If it will not be possible to set the limit accordingly to the configured
960 * max number of clients, the function will do the reverse setting
961 * server.maxclients to the value that we can actually handle. */
962 void adjustOpenFilesLimit(void) {
963 rlim_t maxfiles
= server
.maxclients
+32;
966 if (maxfiles
< 1024) maxfiles
= 1024;
967 if (getrlimit(RLIMIT_NOFILE
,&limit
) == -1) {
968 redisLog(REDIS_WARNING
,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.",
970 server
.maxclients
= 1024-32;
972 rlim_t oldlimit
= limit
.rlim_cur
;
974 /* Set the max number of files if the current limit is not enough
976 if (oldlimit
< maxfiles
) {
977 limit
.rlim_cur
= maxfiles
;
978 limit
.rlim_max
= maxfiles
;
979 if (setrlimit(RLIMIT_NOFILE
,&limit
) == -1) {
980 server
.maxclients
= oldlimit
-32;
981 redisLog(REDIS_WARNING
,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.",
982 (int) maxfiles
, strerror(errno
), (int) server
.maxclients
);
984 redisLog(REDIS_NOTICE
,"Max number of open files set to %d",
994 signal(SIGHUP
, SIG_IGN
);
995 signal(SIGPIPE
, SIG_IGN
);
996 setupSignalHandlers();
998 if (server
.syslog_enabled
) {
999 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
1000 server
.syslog_facility
);
1003 server
.current_client
= NULL
;
1004 server
.clients
= listCreate();
1005 server
.slaves
= listCreate();
1006 server
.monitors
= listCreate();
1007 server
.unblocked_clients
= listCreate();
1009 createSharedObjects();
1010 adjustOpenFilesLimit();
1011 server
.el
= aeCreateEventLoop(server
.maxclients
+1024);
1012 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1014 if (server
.port
!= 0) {
1015 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
1016 if (server
.ipfd
== ANET_ERR
) {
1017 redisLog(REDIS_WARNING
, "Opening port %d: %s",
1018 server
.port
, server
.neterr
);
1022 if (server
.unixsocket
!= NULL
) {
1023 unlink(server
.unixsocket
); /* don't care if this fails */
1024 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
,server
.unixsocketperm
);
1025 if (server
.sofd
== ANET_ERR
) {
1026 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
1030 if (server
.ipfd
< 0 && server
.sofd
< 0) {
1031 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
1034 for (j
= 0; j
< server
.dbnum
; j
++) {
1035 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1036 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1037 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
1038 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
1039 server
.db
[j
].id
= j
;
1041 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
1042 server
.pubsub_patterns
= listCreate();
1043 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
1044 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
1045 server
.cronloops
= 0;
1046 server
.rdb_child_pid
= -1;
1047 server
.aof_child_pid
= -1;
1048 server
.aof_rewrite_buf
= sdsempty();
1049 server
.aof_buf
= sdsempty();
1050 server
.lastsave
= time(NULL
);
1052 server
.stat_numcommands
= 0;
1053 server
.stat_numconnections
= 0;
1054 server
.stat_expiredkeys
= 0;
1055 server
.stat_evictedkeys
= 0;
1056 server
.stat_starttime
= time(NULL
);
1057 server
.stat_keyspace_misses
= 0;
1058 server
.stat_keyspace_hits
= 0;
1059 server
.stat_peak_memory
= 0;
1060 server
.stat_fork_time
= 0;
1061 server
.stat_rejected_conn
= 0;
1062 server
.unixtime
= time(NULL
);
1063 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1064 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
1065 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
1066 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
1067 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
1069 if (server
.aof_state
== REDIS_AOF_ON
) {
1070 server
.aof_fd
= open(server
.aof_filename
,
1071 O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1072 if (server
.aof_fd
== -1) {
1073 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1079 if (server
.cluster_enabled
) clusterInit();
1085 /* Populates the Redis Command Table starting from the hard coded list
1086 * we have on top of redis.c file. */
1087 void populateCommandTable(void) {
1089 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1091 for (j
= 0; j
< numcommands
; j
++) {
1092 struct redisCommand
*c
= redisCommandTable
+j
;
1093 char *f
= c
->sflags
;
1098 case 'w': c
->flags
|= REDIS_CMD_WRITE
; break;
1099 case 'r': c
->flags
|= REDIS_CMD_READONLY
; break;
1100 case 'm': c
->flags
|= REDIS_CMD_DENYOOM
; break;
1101 case 'a': c
->flags
|= REDIS_CMD_ADMIN
; break;
1102 case 'p': c
->flags
|= REDIS_CMD_PUBSUB
; break;
1103 case 'f': c
->flags
|= REDIS_CMD_FORCE_REPLICATION
; break;
1104 case 's': c
->flags
|= REDIS_CMD_NOSCRIPT
; break;
1105 case 'R': c
->flags
|= REDIS_CMD_RANDOM
; break;
1106 default: redisPanic("Unsupported command flag"); break;
1111 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
1112 assert(retval
== DICT_OK
);
1116 void resetCommandTableStats(void) {
1117 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1120 for (j
= 0; j
< numcommands
; j
++) {
1121 struct redisCommand
*c
= redisCommandTable
+j
;
1123 c
->microseconds
= 0;
1128 /* ====================== Commands lookup and execution ===================== */
1130 struct redisCommand
*lookupCommand(sds name
) {
1131 return dictFetchValue(server
.commands
, name
);
1134 struct redisCommand
*lookupCommandByCString(char *s
) {
1135 struct redisCommand
*cmd
;
1136 sds name
= sdsnew(s
);
1138 cmd
= dictFetchValue(server
.commands
, name
);
1143 /* Call() is the core of Redis execution of a command */
1144 void call(redisClient
*c
) {
1145 long long dirty
, start
= ustime(), duration
;
1147 dirty
= server
.dirty
;
1149 dirty
= server
.dirty
-dirty
;
1150 duration
= ustime()-start
;
1151 c
->cmd
->microseconds
+= duration
;
1152 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1155 if (server
.aof_state
!= REDIS_AOF_OFF
&& dirty
> 0)
1156 feedAppendOnlyFile(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1157 if ((dirty
> 0 || c
->cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1158 listLength(server
.slaves
))
1159 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1160 if (listLength(server
.monitors
))
1161 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1162 server
.stat_numcommands
++;
1165 /* If this function gets called we already read a whole
1166 * command, argments are in the client argv/argc fields.
1167 * processCommand() execute the command or prepare the
1168 * server for a bulk read from the client.
1170 * If 1 is returned the client is still alive and valid and
1171 * and other operations can be performed by the caller. Otherwise
1172 * if 0 is returned the client was destroied (i.e. after QUIT). */
1173 int processCommand(redisClient
*c
) {
1174 /* The QUIT command is handled separately. Normal command procs will
1175 * go through checking for replication and QUIT will cause trouble
1176 * when FORCE_REPLICATION is enabled and would be implemented in
1177 * a regular command proc. */
1178 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1179 addReply(c
,shared
.ok
);
1180 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1184 /* Now lookup the command and check ASAP about trivial error conditions
1185 * such as wrong arity, bad command name and so forth. */
1186 c
->cmd
= c
->lastcmd
= lookupCommand(c
->argv
[0]->ptr
);
1188 addReplyErrorFormat(c
,"unknown command '%s'",
1189 (char*)c
->argv
[0]->ptr
);
1191 } else if ((c
->cmd
->arity
> 0 && c
->cmd
->arity
!= c
->argc
) ||
1192 (c
->argc
< -c
->cmd
->arity
)) {
1193 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1198 /* Check if the user is authenticated */
1199 if (server
.requirepass
&& !c
->authenticated
&& c
->cmd
->proc
!= authCommand
)
1201 addReplyError(c
,"operation not permitted");
1205 /* If cluster is enabled, redirect here */
1206 if (server
.cluster_enabled
&&
1207 !(c
->cmd
->getkeys_proc
== NULL
&& c
->cmd
->firstkey
== 0)) {
1210 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1211 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1215 clusterNode
*n
= getNodeByQuery(c
,c
->cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1217 addReplyError(c
,"Multi keys request invalid in cluster");
1219 } else if (n
!= server
.cluster
.myself
) {
1220 addReplySds(c
,sdscatprintf(sdsempty(),
1221 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1222 hashslot
,n
->ip
,n
->port
));
1228 /* Handle the maxmemory directive.
1230 * First we try to free some memory if possible (if there are volatile
1231 * keys in the dataset). If there are not the only thing we can do
1232 * is returning an error. */
1233 if (server
.maxmemory
) freeMemoryIfNeeded();
1234 if (server
.maxmemory
&& (c
->cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1235 zmalloc_used_memory() > server
.maxmemory
)
1237 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1241 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1242 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1244 c
->cmd
->proc
!= subscribeCommand
&&
1245 c
->cmd
->proc
!= unsubscribeCommand
&&
1246 c
->cmd
->proc
!= psubscribeCommand
&&
1247 c
->cmd
->proc
!= punsubscribeCommand
) {
1248 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1252 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1253 * we are a slave with a broken link with master. */
1254 if (server
.masterhost
&& server
.repl_state
!= REDIS_REPL_CONNECTED
&&
1255 server
.repl_serve_stale_data
== 0 &&
1256 c
->cmd
->proc
!= infoCommand
&& c
->cmd
->proc
!= slaveofCommand
)
1259 "link with MASTER is down and slave-serve-stale-data is set to no");
1263 /* Loading DB? Return an error if the command is not INFO */
1264 if (server
.loading
&& c
->cmd
->proc
!= infoCommand
) {
1265 addReply(c
, shared
.loadingerr
);
1269 /* Lua script too slow? Only allow SHUTDOWN NOSAVE and SCRIPT KILL. */
1270 if (server
.lua_timedout
&&
1271 !(c
->cmd
->proc
!= shutdownCommand
&&
1273 tolower(((char*)c
->argv
[1]->ptr
)[0]) == 'n') &&
1274 !(c
->cmd
->proc
== scriptCommand
&&
1276 tolower(((char*)c
->argv
[1]->ptr
)[0]) == 'k'))
1278 addReply(c
, shared
.slowscripterr
);
1282 /* Exec the command */
1283 if (c
->flags
& REDIS_MULTI
&&
1284 c
->cmd
->proc
!= execCommand
&& c
->cmd
->proc
!= discardCommand
&&
1285 c
->cmd
->proc
!= multiCommand
&& c
->cmd
->proc
!= watchCommand
)
1287 queueMultiCommand(c
);
1288 addReply(c
,shared
.queued
);
1295 /*================================== Shutdown =============================== */
1297 int prepareForShutdown(int flags
) {
1298 int save
= flags
& REDIS_SHUTDOWN_SAVE
;
1299 int nosave
= flags
& REDIS_SHUTDOWN_NOSAVE
;
1301 redisLog(REDIS_WARNING
,"User requested shutdown...");
1302 /* Kill the saving child if there is a background saving in progress.
1303 We want to avoid race conditions, for instance our saving child may
1304 overwrite the synchronous saving did by SHUTDOWN. */
1305 if (server
.rdb_child_pid
!= -1) {
1306 redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!");
1307 kill(server
.rdb_child_pid
,SIGKILL
);
1308 rdbRemoveTempFile(server
.rdb_child_pid
);
1310 if (server
.aof_state
!= REDIS_AOF_OFF
) {
1311 /* Kill the AOF saving child as the AOF we already have may be longer
1312 * but contains the full dataset anyway. */
1313 if (server
.aof_child_pid
!= -1) {
1314 redisLog(REDIS_WARNING
,
1315 "There is a child rewriting the AOF. Killing it!");
1316 kill(server
.aof_child_pid
,SIGKILL
);
1318 /* Append only file: fsync() the AOF and exit */
1319 redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file.");
1320 aof_fsync(server
.aof_fd
);
1322 if ((server
.saveparamslen
> 0 && !nosave
) || save
) {
1323 redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting.");
1324 /* Snapshotting. Perform a SYNC SAVE and exit */
1325 if (rdbSave(server
.rdb_filename
) != REDIS_OK
) {
1326 /* Ooops.. error saving! The best we can do is to continue
1327 * operating. Note that if there was a background saving process,
1328 * in the next cron() Redis will be notified that the background
1329 * saving aborted, handling special stuff like slaves pending for
1330 * synchronization... */
1331 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit.");
1335 if (server
.daemonize
) {
1336 redisLog(REDIS_NOTICE
,"Removing the pid file.");
1337 unlink(server
.pidfile
);
1339 /* Close the listening sockets. Apparently this allows faster restarts. */
1340 if (server
.ipfd
!= -1) close(server
.ipfd
);
1341 if (server
.sofd
!= -1) close(server
.sofd
);
1342 if (server
.unixsocket
) {
1343 redisLog(REDIS_NOTICE
,"Removing the unix socket file.");
1344 unlink(server
.unixsocket
); /* don't care if this fails */
1347 redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye...");
1351 /*================================== Commands =============================== */
1353 void authCommand(redisClient
*c
) {
1354 if (!server
.requirepass
) {
1355 addReplyError(c
,"Client sent AUTH, but no password is set");
1356 } else if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1357 c
->authenticated
= 1;
1358 addReply(c
,shared
.ok
);
1360 c
->authenticated
= 0;
1361 addReplyError(c
,"invalid password");
1365 void pingCommand(redisClient
*c
) {
1366 addReply(c
,shared
.pong
);
1369 void echoCommand(redisClient
*c
) {
1370 addReplyBulk(c
,c
->argv
[1]);
1373 /* Convert an amount of bytes into a human readable string in the form
1374 * of 100B, 2G, 100M, 4K, and so forth. */
1375 void bytesToHuman(char *s
, unsigned long long n
) {
1380 sprintf(s
,"%lluB",n
);
1382 } else if (n
< (1024*1024)) {
1383 d
= (double)n
/(1024);
1384 sprintf(s
,"%.2fK",d
);
1385 } else if (n
< (1024LL*1024*1024)) {
1386 d
= (double)n
/(1024*1024);
1387 sprintf(s
,"%.2fM",d
);
1388 } else if (n
< (1024LL*1024*1024*1024)) {
1389 d
= (double)n
/(1024LL*1024*1024);
1390 sprintf(s
,"%.2fG",d
);
1394 /* Create the string returned by the INFO command. This is decoupled
1395 * by the INFO command itself as we need to report the same information
1396 * on memory corruption problems. */
1397 sds
genRedisInfoString(char *section
) {
1398 sds info
= sdsempty();
1399 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1401 struct rusage self_ru
, c_ru
;
1402 unsigned long lol
, bib
;
1403 int allsections
= 0, defsections
= 0;
1407 allsections
= strcasecmp(section
,"all") == 0;
1408 defsections
= strcasecmp(section
,"default") == 0;
1411 getrusage(RUSAGE_SELF
, &self_ru
);
1412 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1413 getClientsMaxBuffers(&lol
,&bib
);
1416 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1417 if (sections
++) info
= sdscat(info
,"\r\n");
1418 info
= sdscatprintf(info
,
1420 "redis_version:%s\r\n"
1421 "redis_git_sha1:%s\r\n"
1422 "redis_git_dirty:%d\r\n"
1424 "multiplexing_api:%s\r\n"
1425 "gcc_version:%d.%d.%d\r\n"
1426 "process_id:%ld\r\n"
1428 "uptime_in_seconds:%ld\r\n"
1429 "uptime_in_days:%ld\r\n"
1430 "lru_clock:%ld\r\n",
1433 strtol(redisGitDirty(),NULL
,10) > 0,
1434 (sizeof(long) == 8) ? "64" : "32",
1437 __GNUC__
,__GNUC_MINOR__
,__GNUC_PATCHLEVEL__
,
1445 (unsigned long) server
.lruclock
);
1449 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1450 if (sections
++) info
= sdscat(info
,"\r\n");
1451 info
= sdscatprintf(info
,
1453 "connected_clients:%d\r\n"
1454 "client_longest_output_list:%lu\r\n"
1455 "client_biggest_input_buf:%lu\r\n"
1456 "blocked_clients:%d\r\n",
1457 listLength(server
.clients
)-listLength(server
.slaves
),
1459 server
.bpop_blocked_clients
);
1463 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1467 bytesToHuman(hmem
,zmalloc_used_memory());
1468 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1469 if (sections
++) info
= sdscat(info
,"\r\n");
1470 info
= sdscatprintf(info
,
1472 "used_memory:%zu\r\n"
1473 "used_memory_human:%s\r\n"
1474 "used_memory_rss:%zu\r\n"
1475 "used_memory_peak:%zu\r\n"
1476 "used_memory_peak_human:%s\r\n"
1477 "used_memory_lua:%lld\r\n"
1478 "mem_fragmentation_ratio:%.2f\r\n"
1479 "mem_allocator:%s\r\n",
1480 zmalloc_used_memory(),
1483 server
.stat_peak_memory
,
1485 ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL,
1486 zmalloc_get_fragmentation_ratio(),
1492 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1493 if (sections
++) info
= sdscat(info
,"\r\n");
1494 info
= sdscatprintf(info
,
1497 "aof_enabled:%d\r\n"
1498 "changes_since_last_save:%lld\r\n"
1499 "bgsave_in_progress:%d\r\n"
1500 "last_save_time:%ld\r\n"
1501 "bgrewriteaof_in_progress:%d\r\n",
1503 server
.aof_state
!= REDIS_AOF_OFF
,
1505 server
.rdb_child_pid
!= -1,
1507 server
.aof_child_pid
!= -1);
1509 if (server
.aof_state
!= REDIS_AOF_OFF
) {
1510 info
= sdscatprintf(info
,
1511 "aof_current_size:%lld\r\n"
1512 "aof_base_size:%lld\r\n"
1513 "aof_pending_rewrite:%d\r\n"
1514 "aof_buffer_length:%zu\r\n"
1515 "aof_pending_bio_fsync:%llu\r\n",
1516 (long long) server
.aof_current_size
,
1517 (long long) server
.aof_rewrite_base_size
,
1518 server
.aof_rewrite_scheduled
,
1519 sdslen(server
.aof_buf
),
1520 bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
));
1523 if (server
.loading
) {
1525 time_t eta
, elapsed
;
1526 off_t remaining_bytes
= server
.loading_total_bytes
-
1527 server
.loading_loaded_bytes
;
1529 perc
= ((double)server
.loading_loaded_bytes
/
1530 server
.loading_total_bytes
) * 100;
1532 elapsed
= time(NULL
)-server
.loading_start_time
;
1534 eta
= 1; /* A fake 1 second figure if we don't have
1537 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1540 info
= sdscatprintf(info
,
1541 "loading_start_time:%ld\r\n"
1542 "loading_total_bytes:%llu\r\n"
1543 "loading_loaded_bytes:%llu\r\n"
1544 "loading_loaded_perc:%.2f\r\n"
1545 "loading_eta_seconds:%ld\r\n"
1546 ,(unsigned long) server
.loading_start_time
,
1547 (unsigned long long) server
.loading_total_bytes
,
1548 (unsigned long long) server
.loading_loaded_bytes
,
1556 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1557 if (sections
++) info
= sdscat(info
,"\r\n");
1558 info
= sdscatprintf(info
,
1560 "total_connections_received:%lld\r\n"
1561 "total_commands_processed:%lld\r\n"
1562 "rejected_connections:%lld\r\n"
1563 "expired_keys:%lld\r\n"
1564 "evicted_keys:%lld\r\n"
1565 "keyspace_hits:%lld\r\n"
1566 "keyspace_misses:%lld\r\n"
1567 "pubsub_channels:%ld\r\n"
1568 "pubsub_patterns:%u\r\n"
1569 "latest_fork_usec:%lld\r\n",
1570 server
.stat_numconnections
,
1571 server
.stat_numcommands
,
1572 server
.stat_rejected_conn
,
1573 server
.stat_expiredkeys
,
1574 server
.stat_evictedkeys
,
1575 server
.stat_keyspace_hits
,
1576 server
.stat_keyspace_misses
,
1577 dictSize(server
.pubsub_channels
),
1578 listLength(server
.pubsub_patterns
),
1579 server
.stat_fork_time
);
1583 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1584 if (sections
++) info
= sdscat(info
,"\r\n");
1585 info
= sdscatprintf(info
,
1588 server
.masterhost
== NULL
? "master" : "slave");
1589 if (server
.masterhost
) {
1590 info
= sdscatprintf(info
,
1591 "master_host:%s\r\n"
1592 "master_port:%d\r\n"
1593 "master_link_status:%s\r\n"
1594 "master_last_io_seconds_ago:%d\r\n"
1595 "master_sync_in_progress:%d\r\n"
1598 (server
.repl_state
== REDIS_REPL_CONNECTED
) ?
1601 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1602 server
.repl_state
== REDIS_REPL_TRANSFER
1605 if (server
.repl_state
== REDIS_REPL_TRANSFER
) {
1606 info
= sdscatprintf(info
,
1607 "master_sync_left_bytes:%ld\r\n"
1608 "master_sync_last_io_seconds_ago:%d\r\n"
1609 ,(long)server
.repl_transfer_left
,
1610 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1614 if (server
.repl_state
!= REDIS_REPL_CONNECTED
) {
1615 info
= sdscatprintf(info
,
1616 "master_link_down_since_seconds:%ld\r\n",
1617 (long)time(NULL
)-server
.repl_down_since
);
1620 info
= sdscatprintf(info
,
1621 "connected_slaves:%d\r\n",
1622 listLength(server
.slaves
));
1623 if (listLength(server
.slaves
)) {
1628 listRewind(server
.slaves
,&li
);
1629 while((ln
= listNext(&li
))) {
1630 redisClient
*slave
= listNodeValue(ln
);
1635 if (anetPeerToString(slave
->fd
,ip
,&port
) == -1) continue;
1636 switch(slave
->replstate
) {
1637 case REDIS_REPL_WAIT_BGSAVE_START
:
1638 case REDIS_REPL_WAIT_BGSAVE_END
:
1639 state
= "wait_bgsave";
1641 case REDIS_REPL_SEND_BULK
:
1642 state
= "send_bulk";
1644 case REDIS_REPL_ONLINE
:
1648 if (state
== NULL
) continue;
1649 info
= sdscatprintf(info
,"slave%d:%s,%d,%s\r\n",
1650 slaveid
,ip
,port
,state
);
1657 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1658 if (sections
++) info
= sdscat(info
,"\r\n");
1659 info
= sdscatprintf(info
,
1661 "used_cpu_sys:%.2f\r\n"
1662 "used_cpu_user:%.2f\r\n"
1663 "used_cpu_sys_children:%.2f\r\n"
1664 "used_cpu_user_children:%.2f\r\n",
1665 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1666 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1667 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1668 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000);
1672 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1673 if (sections
++) info
= sdscat(info
,"\r\n");
1674 info
= sdscatprintf(info
, "# Commandstats\r\n");
1675 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1676 for (j
= 0; j
< numcommands
; j
++) {
1677 struct redisCommand
*c
= redisCommandTable
+j
;
1679 if (!c
->calls
) continue;
1680 info
= sdscatprintf(info
,
1681 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1682 c
->name
, c
->calls
, c
->microseconds
,
1683 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1688 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1689 if (sections
++) info
= sdscat(info
,"\r\n");
1690 info
= sdscatprintf(info
,
1692 "cluster_enabled:%d\r\n",
1693 server
.cluster_enabled
);
1697 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1698 if (sections
++) info
= sdscat(info
,"\r\n");
1699 info
= sdscatprintf(info
, "# Keyspace\r\n");
1700 for (j
= 0; j
< server
.dbnum
; j
++) {
1701 long long keys
, vkeys
;
1703 keys
= dictSize(server
.db
[j
].dict
);
1704 vkeys
= dictSize(server
.db
[j
].expires
);
1705 if (keys
|| vkeys
) {
1706 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1714 void infoCommand(redisClient
*c
) {
1715 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1718 addReply(c
,shared
.syntaxerr
);
1721 sds info
= genRedisInfoString(section
);
1722 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1723 (unsigned long)sdslen(info
)));
1724 addReplySds(c
,info
);
1725 addReply(c
,shared
.crlf
);
1728 void monitorCommand(redisClient
*c
) {
1729 /* ignore MONITOR if aleady slave or in monitor mode */
1730 if (c
->flags
& REDIS_SLAVE
) return;
1732 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1734 listAddNodeTail(server
.monitors
,c
);
1735 addReply(c
,shared
.ok
);
1738 /* ============================ Maxmemory directive ======================== */
1740 /* This function gets called when 'maxmemory' is set on the config file to limit
1741 * the max memory used by the server, and we are out of memory.
1742 * This function will try to, in order:
1744 * - Free objects from the free list
1745 * - Try to remove keys with an EXPIRE set
1747 * It is not possible to free enough memory to reach used-memory < maxmemory
1748 * the server will start refusing commands that will enlarge even more the
1751 void freeMemoryIfNeeded(void) {
1752 /* Remove keys accordingly to the active policy as long as we are
1753 * over the memory limit. */
1754 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1756 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1757 int j
, k
, freed
= 0;
1759 for (j
= 0; j
< server
.dbnum
; j
++) {
1760 long bestval
= 0; /* just to prevent warning */
1762 struct dictEntry
*de
;
1763 redisDb
*db
= server
.db
+j
;
1766 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1767 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1769 dict
= server
.db
[j
].dict
;
1771 dict
= server
.db
[j
].expires
;
1773 if (dictSize(dict
) == 0) continue;
1775 /* volatile-random and allkeys-random policy */
1776 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1777 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1779 de
= dictGetRandomKey(dict
);
1780 bestkey
= dictGetKey(de
);
1783 /* volatile-lru and allkeys-lru policy */
1784 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1785 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1787 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1792 de
= dictGetRandomKey(dict
);
1793 thiskey
= dictGetKey(de
);
1794 /* When policy is volatile-lru we need an additonal lookup
1795 * to locate the real key, as dict is set to db->expires. */
1796 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1797 de
= dictFind(db
->dict
, thiskey
);
1799 thisval
= estimateObjectIdleTime(o
);
1801 /* Higher idle time is better candidate for deletion */
1802 if (bestkey
== NULL
|| thisval
> bestval
) {
1810 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1811 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1815 de
= dictGetRandomKey(dict
);
1816 thiskey
= dictGetKey(de
);
1817 thisval
= (long) dictGetVal(de
);
1819 /* Expire sooner (minor expire unix timestamp) is better
1820 * candidate for deletion */
1821 if (bestkey
== NULL
|| thisval
< bestval
) {
1828 /* Finally remove the selected key. */
1830 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1831 propagateExpire(db
,keyobj
);
1832 dbDelete(db
,keyobj
);
1833 server
.stat_evictedkeys
++;
1834 decrRefCount(keyobj
);
1838 if (!freed
) return; /* nothing to free... */
1842 /* =================================== Main! ================================ */
1845 int linuxOvercommitMemoryValue(void) {
1846 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1850 if (fgets(buf
,64,fp
) == NULL
) {
1859 void linuxOvercommitMemoryWarning(void) {
1860 if (linuxOvercommitMemoryValue() == 0) {
1861 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.");
1864 #endif /* __linux__ */
1866 void createPidFile(void) {
1867 /* Try to write the pid file in a best-effort way. */
1868 FILE *fp
= fopen(server
.pidfile
,"w");
1870 fprintf(fp
,"%d\n",(int)getpid());
1875 void daemonize(void) {
1878 if (fork() != 0) exit(0); /* parent exits */
1879 setsid(); /* create a new session */
1881 /* Every output goes to /dev/null. If Redis is daemonized but
1882 * the 'logfile' is set to 'stdout' in the configuration file
1883 * it will not log at all. */
1884 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1885 dup2(fd
, STDIN_FILENO
);
1886 dup2(fd
, STDOUT_FILENO
);
1887 dup2(fd
, STDERR_FILENO
);
1888 if (fd
> STDERR_FILENO
) close(fd
);
1893 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1894 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1899 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf] [options]\n");
1900 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1901 fprintf(stderr
," ./redis-server -v or --version\n");
1902 fprintf(stderr
," ./redis-server -h or --help\n\n");
1903 fprintf(stderr
,"Examples:\n");
1904 fprintf(stderr
," ./redis-server (run the server with default conf)\n");
1905 fprintf(stderr
," ./redis-server /etc/redis/6379.conf\n");
1906 fprintf(stderr
," ./redis-server --port 7777\n");
1907 fprintf(stderr
," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n");
1908 fprintf(stderr
," ./redis-server /etc/myredis.conf --loglevel verbose\n");
1912 void redisAsciiArt(void) {
1913 #include "asciilogo.h"
1914 char *buf
= zmalloc(1024*16);
1916 snprintf(buf
,1024*16,ascii_logo
,
1919 strtol(redisGitDirty(),NULL
,10) > 0,
1920 (sizeof(long) == 8) ? "64" : "32",
1921 server
.cluster_enabled
? "cluster" : "stand alone",
1925 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1929 static void sigtermHandler(int sig
) {
1932 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1933 server
.shutdown_asap
= 1;
1936 void setupSignalHandlers(void) {
1937 struct sigaction act
;
1939 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1940 * Otherwise, sa_handler is used. */
1941 sigemptyset(&act
.sa_mask
);
1942 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1943 act
.sa_handler
= sigtermHandler
;
1944 sigaction(SIGTERM
, &act
, NULL
);
1946 #ifdef HAVE_BACKTRACE
1947 sigemptyset(&act
.sa_mask
);
1948 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1949 act
.sa_sigaction
= sigsegvHandler
;
1950 sigaction(SIGSEGV
, &act
, NULL
);
1951 sigaction(SIGBUS
, &act
, NULL
);
1952 sigaction(SIGFPE
, &act
, NULL
);
1953 sigaction(SIGILL
, &act
, NULL
);
1958 int main(int argc
, char **argv
) {
1962 /* We need to initialize our libraries, and the server. */
1963 zmalloc_enable_thread_safeness();
1964 srand(time(NULL
)^getpid());
1965 gettimeofday(&tv
,NULL
);
1966 dictSetHashFunctionSeed(tv
.tv_sec
^tv
.tv_usec
^getpid());
1970 int j
= 1; /* First option to parse in argv[] */
1971 sds options
= sdsempty();
1972 char *configfile
= NULL
;
1974 /* Handle special options --help and --version */
1975 if (strcmp(argv
[1], "-v") == 0 ||
1976 strcmp(argv
[1], "--version") == 0) version();
1977 if (strcmp(argv
[1], "--help") == 0 ||
1978 strcmp(argv
[1], "-h") == 0) usage();
1979 /* First argument is the config file name? */
1980 if (argv
[j
][0] != '-' || argv
[j
][1] != '-')
1981 configfile
= argv
[j
++];
1982 /* All the other options are parsed and conceptually appended to the
1983 * configuration file. For instance --port 6380 will generate the
1984 * string "port 6380\n" to be parsed after the actual file name
1985 * is parsed, if any. */
1987 if (argv
[j
][0] == '-' && argv
[j
][1] == '-') {
1989 if (sdslen(options
)) options
= sdscat(options
,"\n");
1990 options
= sdscat(options
,argv
[j
]+2);
1991 options
= sdscat(options
," ");
1993 /* Option argument */
1994 options
= sdscatrepr(options
,argv
[j
],strlen(argv
[j
]));
1995 options
= sdscat(options
," ");
1999 resetServerSaveParams();
2000 loadServerConfig(configfile
,options
);
2003 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'");
2005 if (server
.daemonize
) daemonize();
2007 if (server
.daemonize
) createPidFile();
2009 redisLog(REDIS_WARNING
,"Server started, Redis version " REDIS_VERSION
);
2011 linuxOvercommitMemoryWarning();
2014 if (server
.aof_state
== REDIS_AOF_ON
) {
2015 if (loadAppendOnlyFile(server
.aof_filename
) == REDIS_OK
)
2016 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
2018 if (rdbLoad(server
.rdb_filename
) == REDIS_OK
) {
2019 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",
2020 (float)(ustime()-start
)/1000000);
2021 } else if (errno
!= ENOENT
) {
2022 redisLog(REDIS_WARNING
,"Fatal error loading the DB. Exiting.");
2026 if (server
.ipfd
> 0)
2027 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
2028 if (server
.sofd
> 0)
2029 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
2030 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
2032 aeDeleteEventLoop(server
.el
);