2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
37 #endif /* HAVE_BACKTRACE */
46 #include <arpa/inet.h>
50 #include <sys/resource.h>
55 #include <sys/resource.h>
57 /* Our shared "common" objects */
59 struct sharedObjectsStruct shared
;
61 /* Global vars that are actually used as constants. The following double
62 * values are used for double on-disk serialization, and are initialized
63 * at runtime to avoid strange compiler optimizations. */
65 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
67 /*================================= Globals ================================= */
70 struct redisServer server
; /* server global state */
71 struct redisCommand
*commandTable
;
73 /* Our command table. Command flags are expressed using strings where every
74 * character represents a flag. Later the populateCommandTable() function will
75 * take care of populating the real 'flags' field using this characters.
77 * This is the meaning of the flags:
79 * w: write command (may modify the key space).
80 * r: read command (will never modify the key space).
81 * m: may increase memory usage once called. Don't allow if out of memory.
82 * a: admin command, like SAVE or SHUTDOWN.
83 * p: Pub/Sub related command.
84 * f: force replication of this command, regarless of server.dirty.
85 * s: command not allowed in scripts.
86 * r: random command. Command is not deterministic, that is, the same command
87 * with the same arguments, with the same key space, may have different
88 * results. For instance SPOP and RANDOMKEY are two random commands. */
89 struct redisCommand redisCommandTable
[] = {
90 {"get",getCommand
,2,"r",0,NULL
,1,1,1,0,0},
91 {"set",setCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
92 {"setnx",setnxCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0},
93 {"setex",setexCommand
,4,"wm",0,noPreloadGetKeys
,2,2,1,0,0},
94 {"append",appendCommand
,3,"wm",0,NULL
,1,1,1,0,0},
95 {"strlen",strlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
96 {"del",delCommand
,-2,"w",0,noPreloadGetKeys
,1,-1,1,0,0},
97 {"exists",existsCommand
,2,"r",0,NULL
,1,1,1,0,0},
98 {"setbit",setbitCommand
,4,"wm",0,NULL
,1,1,1,0,0},
99 {"getbit",getbitCommand
,3,"r",0,NULL
,1,1,1,0,0},
100 {"setrange",setrangeCommand
,4,"wm",0,NULL
,1,1,1,0,0},
101 {"getrange",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
102 {"substr",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
103 {"incr",incrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
104 {"decr",decrCommand
,2,"wm",0,NULL
,1,1,1,0,0},
105 {"mget",mgetCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
106 {"rpush",rpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
107 {"lpush",lpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
108 {"rpushx",rpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
109 {"lpushx",lpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0},
110 {"linsert",linsertCommand
,5,"wm",0,NULL
,1,1,1,0,0},
111 {"rpop",rpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
112 {"lpop",lpopCommand
,2,"w",0,NULL
,1,1,1,0,0},
113 {"brpop",brpopCommand
,-3,"w",0,NULL
,1,1,1,0,0},
114 {"brpoplpush",brpoplpushCommand
,4,"wm",0,NULL
,1,2,1,0,0},
115 {"blpop",blpopCommand
,-3,"w",0,NULL
,1,-2,1,0,0},
116 {"llen",llenCommand
,2,"r",0,NULL
,1,1,1,0,0},
117 {"lindex",lindexCommand
,3,"r",0,NULL
,1,1,1,0,0},
118 {"lset",lsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
119 {"lrange",lrangeCommand
,4,"r",0,NULL
,1,1,1,0,0},
120 {"ltrim",ltrimCommand
,4,"w",0,NULL
,1,1,1,0,0},
121 {"lrem",lremCommand
,4,"w",0,NULL
,1,1,1,0,0},
122 {"rpoplpush",rpoplpushCommand
,3,"wm",0,NULL
,1,2,1,0,0},
123 {"sadd",saddCommand
,-3,"wm",0,NULL
,1,1,1,0,0},
124 {"srem",sremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
125 {"smove",smoveCommand
,4,"w",0,NULL
,1,2,1,0,0},
126 {"sismember",sismemberCommand
,3,"r",0,NULL
,1,1,1,0,0},
127 {"scard",scardCommand
,2,"r",0,NULL
,1,1,1,0,0},
128 {"spop",spopCommand
,2,"wRs",0,NULL
,1,1,1,0,0},
129 {"srandmember",srandmemberCommand
,2,"rR",0,NULL
,1,1,1,0,0},
130 {"sinter",sinterCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
131 {"sinterstore",sinterstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
132 {"sunion",sunionCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
133 {"sunionstore",sunionstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
134 {"sdiff",sdiffCommand
,-2,"r",0,NULL
,1,-1,1,0,0},
135 {"sdiffstore",sdiffstoreCommand
,-3,"wm",0,NULL
,2,-1,1,0,0},
136 {"smembers",sinterCommand
,2,"r",0,NULL
,1,1,1,0,0},
137 {"zadd",zaddCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
138 {"zincrby",zincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
139 {"zrem",zremCommand
,-3,"w",0,NULL
,1,1,1,0,0},
140 {"zremrangebyscore",zremrangebyscoreCommand
,4,"w",0,NULL
,1,1,1,0,0},
141 {"zremrangebyrank",zremrangebyrankCommand
,4,"w",0,NULL
,1,1,1,0,0},
142 {"zunionstore",zunionstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
143 {"zinterstore",zinterstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0},
144 {"zrange",zrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
145 {"zrangebyscore",zrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
146 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0},
147 {"zcount",zcountCommand
,4,"r",0,NULL
,1,1,1,0,0},
148 {"zrevrange",zrevrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0},
149 {"zcard",zcardCommand
,2,"r",0,NULL
,1,1,1,0,0},
150 {"zscore",zscoreCommand
,3,"r",0,NULL
,1,1,1,0,0},
151 {"zrank",zrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
152 {"zrevrank",zrevrankCommand
,3,"r",0,NULL
,1,1,1,0,0},
153 {"hset",hsetCommand
,4,"wm",0,NULL
,1,1,1,0,0},
154 {"hsetnx",hsetnxCommand
,4,"wm",0,NULL
,1,1,1,0,0},
155 {"hget",hgetCommand
,3,"r",0,NULL
,1,1,1,0,0},
156 {"hmset",hmsetCommand
,-4,"wm",0,NULL
,1,1,1,0,0},
157 {"hmget",hmgetCommand
,-3,"r",0,NULL
,1,1,1,0,0},
158 {"hincrby",hincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0},
159 {"hdel",hdelCommand
,-3,"w",0,NULL
,1,1,1,0,0},
160 {"hlen",hlenCommand
,2,"r",0,NULL
,1,1,1,0,0},
161 {"hkeys",hkeysCommand
,2,"r",0,NULL
,1,1,1,0,0},
162 {"hvals",hvalsCommand
,2,"r",0,NULL
,1,1,1,0,0},
163 {"hgetall",hgetallCommand
,2,"r",0,NULL
,1,1,1,0,0},
164 {"hexists",hexistsCommand
,3,"r",0,NULL
,1,1,1,0,0},
165 {"incrby",incrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
166 {"decrby",decrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0},
167 {"getset",getsetCommand
,3,"wm",0,NULL
,1,1,1,0,0},
168 {"mset",msetCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
169 {"msetnx",msetnxCommand
,-3,"wm",0,NULL
,1,-1,2,0,0},
170 {"randomkey",randomkeyCommand
,1,"rR",0,NULL
,0,0,0,0,0},
171 {"select",selectCommand
,2,"r",0,NULL
,0,0,0,0,0},
172 {"move",moveCommand
,3,"w",0,NULL
,1,1,1,0,0},
173 {"rename",renameCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
174 {"renamenx",renamenxCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0},
175 {"expire",expireCommand
,3,"w",0,NULL
,1,1,1,0,0},
176 {"expireat",expireatCommand
,3,"w",0,NULL
,1,1,1,0,0},
177 {"keys",keysCommand
,2,"r",0,NULL
,0,0,0,0,0},
178 {"dbsize",dbsizeCommand
,1,"r",0,NULL
,0,0,0,0,0},
179 {"auth",authCommand
,2,"r",0,NULL
,0,0,0,0,0},
180 {"ping",pingCommand
,1,"r",0,NULL
,0,0,0,0,0},
181 {"echo",echoCommand
,2,"r",0,NULL
,0,0,0,0,0},
182 {"save",saveCommand
,1,"ar",0,NULL
,0,0,0,0,0},
183 {"bgsave",bgsaveCommand
,1,"ar",0,NULL
,0,0,0,0,0},
184 {"bgrewriteaof",bgrewriteaofCommand
,1,"ar",0,NULL
,0,0,0,0,0},
185 {"shutdown",shutdownCommand
,1,"ar",0,NULL
,0,0,0,0,0},
186 {"lastsave",lastsaveCommand
,1,"r",0,NULL
,0,0,0,0,0},
187 {"type",typeCommand
,2,"r",0,NULL
,1,1,1,0,0},
188 {"multi",multiCommand
,1,"rs",0,NULL
,0,0,0,0,0},
189 {"exec",execCommand
,1,"wms",0,NULL
,0,0,0,0,0},
190 {"discard",discardCommand
,1,"rs",0,NULL
,0,0,0,0,0},
191 {"sync",syncCommand
,1,"ars",0,NULL
,0,0,0,0,0},
192 {"flushdb",flushdbCommand
,1,"w",0,NULL
,0,0,0,0,0},
193 {"flushall",flushallCommand
,1,"w",0,NULL
,0,0,0,0,0},
194 {"sort",sortCommand
,-2,"wm",0,NULL
,1,1,1,0,0},
195 {"info",infoCommand
,-1,"r",0,NULL
,0,0,0,0,0},
196 {"monitor",monitorCommand
,1,"ars",0,NULL
,0,0,0,0,0},
197 {"ttl",ttlCommand
,2,"r",0,NULL
,1,1,1,0,0},
198 {"persist",persistCommand
,2,"w",0,NULL
,1,1,1,0,0},
199 {"slaveof",slaveofCommand
,3,"aws",0,NULL
,0,0,0,0,0},
200 {"debug",debugCommand
,-2,"aw",0,NULL
,0,0,0,0,0},
201 {"config",configCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
202 {"subscribe",subscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
203 {"unsubscribe",unsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
204 {"psubscribe",psubscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0},
205 {"punsubscribe",punsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0},
206 {"publish",publishCommand
,3,"rpf",0,NULL
,0,0,0,0,0},
207 {"watch",watchCommand
,-2,"rs",0,noPreloadGetKeys
,1,-1,1,0,0},
208 {"unwatch",unwatchCommand
,1,"rs",0,NULL
,0,0,0,0,0},
209 {"cluster",clusterCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
210 {"restore",restoreCommand
,4,"awm",0,NULL
,1,1,1,0,0},
211 {"migrate",migrateCommand
,6,"aw",0,NULL
,0,0,0,0,0},
212 {"asking",askingCommand
,1,"r",0,NULL
,0,0,0,0,0},
213 {"dump",dumpCommand
,2,"ar",0,NULL
,0,0,0,0,0},
214 {"object",objectCommand
,-2,"r",0,NULL
,0,0,0,0,0},
215 {"client",clientCommand
,-2,"ar",0,NULL
,0,0,0,0,0},
216 {"eval",evalCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
217 {"evalsha",evalShaCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0},
218 {"slowlog",slowlogCommand
,-2,"r",0,NULL
,0,0,0,0,0},
219 {"script",scriptCommand
,-2,"ras",0,NULL
,0,0,0,0,0}
222 /*============================ Utility functions ============================ */
224 /* Low level logging. To use only for very big messages, otherwise
225 * redisLog() is to prefer. */
226 void redisLogRaw(int level
, const char *msg
) {
227 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
228 const char *c
= ".-*#";
229 time_t now
= time(NULL
);
232 int rawmode
= (level
& REDIS_LOG_RAW
);
234 level
&= 0xff; /* clear flags */
235 if (level
< server
.verbosity
) return;
237 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
241 fprintf(fp
,"%s",msg
);
243 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
244 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
248 if (server
.logfile
) fclose(fp
);
250 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
253 /* Like redisLogRaw() but with printf-alike support. This is the funciton that
254 * is used across the code. The raw version is only used in order to dump
255 * the INFO output on crash. */
256 void redisLog(int level
, const char *fmt
, ...) {
258 char msg
[REDIS_MAX_LOGMSG_LEN
];
260 if ((level
&0xff) < server
.verbosity
) return;
263 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
266 redisLogRaw(level
,msg
);
269 /* Redis generally does not try to recover from out of memory conditions
270 * when allocating objects or strings, it is not clear if it will be possible
271 * to report this condition to the client since the networking layer itself
272 * is based on heap allocation for send buffers, so we simply abort.
273 * At least the code will be simpler to read... */
274 void oom(const char *msg
) {
275 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
280 /* Return the UNIX time in microseconds */
281 long long ustime(void) {
285 gettimeofday(&tv
, NULL
);
286 ust
= ((long long)tv
.tv_sec
)*1000000;
291 /* Return the UNIX time in milliseconds */
292 long long mstime(void) {
293 return ustime()/1000;
296 /*====================== Hash table type implementation ==================== */
298 /* This is an hash table type that uses the SDS dynamic strings libary as
299 * keys and radis objects as values (objects can hold SDS strings,
302 void dictVanillaFree(void *privdata
, void *val
)
304 DICT_NOTUSED(privdata
);
308 void dictListDestructor(void *privdata
, void *val
)
310 DICT_NOTUSED(privdata
);
311 listRelease((list
*)val
);
314 int dictSdsKeyCompare(void *privdata
, const void *key1
,
318 DICT_NOTUSED(privdata
);
320 l1
= sdslen((sds
)key1
);
321 l2
= sdslen((sds
)key2
);
322 if (l1
!= l2
) return 0;
323 return memcmp(key1
, key2
, l1
) == 0;
326 /* A case insensitive version used for the command lookup table. */
327 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
330 DICT_NOTUSED(privdata
);
332 return strcasecmp(key1
, key2
) == 0;
335 void dictRedisObjectDestructor(void *privdata
, void *val
)
337 DICT_NOTUSED(privdata
);
339 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
343 void dictSdsDestructor(void *privdata
, void *val
)
345 DICT_NOTUSED(privdata
);
350 int dictObjKeyCompare(void *privdata
, const void *key1
,
353 const robj
*o1
= key1
, *o2
= key2
;
354 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
357 unsigned int dictObjHash(const void *key
) {
359 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
362 unsigned int dictSdsHash(const void *key
) {
363 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
366 unsigned int dictSdsCaseHash(const void *key
) {
367 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
370 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
373 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
376 if (o1
->encoding
== REDIS_ENCODING_INT
&&
377 o2
->encoding
== REDIS_ENCODING_INT
)
378 return o1
->ptr
== o2
->ptr
;
380 o1
= getDecodedObject(o1
);
381 o2
= getDecodedObject(o2
);
382 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
388 unsigned int dictEncObjHash(const void *key
) {
389 robj
*o
= (robj
*) key
;
391 if (o
->encoding
== REDIS_ENCODING_RAW
) {
392 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
394 if (o
->encoding
== REDIS_ENCODING_INT
) {
398 len
= ll2string(buf
,32,(long)o
->ptr
);
399 return dictGenHashFunction((unsigned char*)buf
, len
);
403 o
= getDecodedObject(o
);
404 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
411 /* Sets type hash table */
412 dictType setDictType
= {
413 dictEncObjHash
, /* hash function */
416 dictEncObjKeyCompare
, /* key compare */
417 dictRedisObjectDestructor
, /* key destructor */
418 NULL
/* val destructor */
421 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
422 dictType zsetDictType
= {
423 dictEncObjHash
, /* hash function */
426 dictEncObjKeyCompare
, /* key compare */
427 dictRedisObjectDestructor
, /* key destructor */
428 NULL
/* val destructor */
431 /* Db->dict, keys are sds strings, vals are Redis objects. */
432 dictType dbDictType
= {
433 dictSdsHash
, /* hash function */
436 dictSdsKeyCompare
, /* key compare */
437 dictSdsDestructor
, /* key destructor */
438 dictRedisObjectDestructor
/* val destructor */
442 dictType keyptrDictType
= {
443 dictSdsHash
, /* hash function */
446 dictSdsKeyCompare
, /* key compare */
447 NULL
, /* key destructor */
448 NULL
/* val destructor */
451 /* Command table. sds string -> command struct pointer. */
452 dictType commandTableDictType
= {
453 dictSdsCaseHash
, /* hash function */
456 dictSdsKeyCaseCompare
, /* key compare */
457 dictSdsDestructor
, /* key destructor */
458 NULL
/* val destructor */
461 /* Hash type hash table (note that small hashes are represented with zimpaps) */
462 dictType hashDictType
= {
463 dictEncObjHash
, /* hash function */
466 dictEncObjKeyCompare
, /* key compare */
467 dictRedisObjectDestructor
, /* key destructor */
468 dictRedisObjectDestructor
/* val destructor */
471 /* Keylist hash table type has unencoded redis objects as keys and
472 * lists as values. It's used for blocking operations (BLPOP) and to
473 * map swapped keys to a list of clients waiting for this keys to be loaded. */
474 dictType keylistDictType
= {
475 dictObjHash
, /* hash function */
478 dictObjKeyCompare
, /* key compare */
479 dictRedisObjectDestructor
, /* key destructor */
480 dictListDestructor
/* val destructor */
483 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
484 * clusterNode structures. */
485 dictType clusterNodesDictType
= {
486 dictSdsHash
, /* hash function */
489 dictSdsKeyCompare
, /* key compare */
490 dictSdsDestructor
, /* key destructor */
491 NULL
/* val destructor */
494 int htNeedsResize(dict
*dict
) {
495 long long size
, used
;
497 size
= dictSlots(dict
);
498 used
= dictSize(dict
);
499 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
500 (used
*100/size
< REDIS_HT_MINFILL
));
503 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
504 * we resize the hash table to save memory */
505 void tryResizeHashTables(void) {
508 for (j
= 0; j
< server
.dbnum
; j
++) {
509 if (htNeedsResize(server
.db
[j
].dict
))
510 dictResize(server
.db
[j
].dict
);
511 if (htNeedsResize(server
.db
[j
].expires
))
512 dictResize(server
.db
[j
].expires
);
516 /* Our hash table implementation performs rehashing incrementally while
517 * we write/read from the hash table. Still if the server is idle, the hash
518 * table will use two tables for a long time. So we try to use 1 millisecond
519 * of CPU time at every serverCron() loop in order to rehash some key. */
520 void incrementallyRehash(void) {
523 for (j
= 0; j
< server
.dbnum
; j
++) {
524 if (dictIsRehashing(server
.db
[j
].dict
)) {
525 dictRehashMilliseconds(server
.db
[j
].dict
,1);
526 break; /* already used our millisecond for this loop... */
531 /* This function is called once a background process of some kind terminates,
532 * as we want to avoid resizing the hash tables when there is a child in order
533 * to play well with copy-on-write (otherwise when a resize happens lots of
534 * memory pages are copied). The goal of this function is to update the ability
535 * for dict.c to resize the hash tables accordingly to the fact we have o not
537 void updateDictResizePolicy(void) {
538 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
544 /* ======================= Cron: called every 100 ms ======================== */
546 /* Try to expire a few timed out keys. The algorithm used is adaptive and
547 * will use few CPU cycles if there are few expiring keys, otherwise
548 * it will get more aggressive to avoid that too much memory is used by
549 * keys that can be removed from the keyspace. */
550 void activeExpireCycle(void) {
553 for (j
= 0; j
< server
.dbnum
; j
++) {
555 redisDb
*db
= server
.db
+j
;
557 /* Continue to expire if at the end of the cycle more than 25%
558 * of the keys were expired. */
560 long num
= dictSize(db
->expires
);
561 time_t now
= time(NULL
);
564 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
565 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
570 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
571 t
= (time_t) dictGetVal(de
);
573 sds key
= dictGetKey(de
);
574 robj
*keyobj
= createStringObject(key
,sdslen(key
));
576 propagateExpire(db
,keyobj
);
578 decrRefCount(keyobj
);
580 server
.stat_expiredkeys
++;
583 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
587 void updateLRUClock(void) {
588 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
592 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
593 int j
, loops
= server
.cronloops
;
594 REDIS_NOTUSED(eventLoop
);
596 REDIS_NOTUSED(clientData
);
598 /* We take a cached value of the unix time in the global state because
599 * with virtual memory and aging there is to store the current time
600 * in objects at every object access, and accuracy is not needed.
601 * To access a global var is faster than calling time(NULL) */
602 server
.unixtime
= time(NULL
);
604 /* We have just 22 bits per object for LRU information.
605 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
606 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
608 * Note that even if this will wrap after 1.5 years it's not a problem,
609 * everything will still work but just some object will appear younger
610 * to Redis. But for this to happen a given object should never be touched
613 * Note that you can change the resolution altering the
614 * REDIS_LRU_CLOCK_RESOLUTION define.
618 /* Record the max memory used since the server was started. */
619 if (zmalloc_used_memory() > server
.stat_peak_memory
)
620 server
.stat_peak_memory
= zmalloc_used_memory();
622 /* We received a SIGTERM, shutting down here in a safe way, as it is
623 * not ok doing so inside the signal handler. */
624 if (server
.shutdown_asap
) {
625 if (prepareForShutdown() == REDIS_OK
) exit(0);
626 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
629 /* Show some info about non-empty databases */
630 for (j
= 0; j
< server
.dbnum
; j
++) {
631 long long size
, used
, vkeys
;
633 size
= dictSlots(server
.db
[j
].dict
);
634 used
= dictSize(server
.db
[j
].dict
);
635 vkeys
= dictSize(server
.db
[j
].expires
);
636 if (!(loops
% 50) && (used
|| vkeys
)) {
637 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
638 /* dictPrintStats(server.dict); */
642 /* We don't want to resize the hash tables while a bacground saving
643 * is in progress: the saving child is created using fork() that is
644 * implemented with a copy-on-write semantic in most modern systems, so
645 * if we resize the HT while there is the saving child at work actually
646 * a lot of memory movements in the parent will cause a lot of pages
648 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
649 if (!(loops
% 10)) tryResizeHashTables();
650 if (server
.activerehashing
) incrementallyRehash();
653 /* Show information about connected clients */
655 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
656 listLength(server
.clients
)-listLength(server
.slaves
),
657 listLength(server
.slaves
),
658 zmalloc_used_memory());
661 /* Close connections of timedout clients */
662 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
663 closeTimedoutClients();
665 /* Start a scheduled AOF rewrite if this was requested by the user while
666 * a BGSAVE was in progress. */
667 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1 &&
668 server
.aofrewrite_scheduled
)
670 rewriteAppendOnlyFileBackground();
673 /* Check if a background saving or AOF rewrite in progress terminated. */
674 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
678 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
679 int exitcode
= WEXITSTATUS(statloc
);
682 if (WIFSIGNALED(statloc
)) bysignal
= WTERMSIG(statloc
);
684 if (pid
== server
.bgsavechildpid
) {
685 backgroundSaveDoneHandler(exitcode
,bysignal
);
687 backgroundRewriteDoneHandler(exitcode
,bysignal
);
689 updateDictResizePolicy();
692 time_t now
= time(NULL
);
694 /* If there is not a background saving/rewrite in progress check if
695 * we have to save/rewrite now */
696 for (j
= 0; j
< server
.saveparamslen
; j
++) {
697 struct saveparam
*sp
= server
.saveparams
+j
;
699 if (server
.dirty
>= sp
->changes
&&
700 now
-server
.lastsave
> sp
->seconds
) {
701 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
702 sp
->changes
, sp
->seconds
);
703 rdbSaveBackground(server
.dbfilename
);
708 /* Trigger an AOF rewrite if needed */
709 if (server
.bgsavechildpid
== -1 &&
710 server
.bgrewritechildpid
== -1 &&
711 server
.auto_aofrewrite_perc
&&
712 server
.appendonly_current_size
> server
.auto_aofrewrite_min_size
)
714 long long base
= server
.auto_aofrewrite_base_size
?
715 server
.auto_aofrewrite_base_size
: 1;
716 long long growth
= (server
.appendonly_current_size
*100/base
) - 100;
717 if (growth
>= server
.auto_aofrewrite_perc
) {
718 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
);
719 rewriteAppendOnlyFileBackground();
725 /* If we postponed an AOF buffer flush, let's try to do it every time the
726 * cron function is called. */
727 if (server
.aof_flush_postponed_start
) flushAppendOnlyFile(0);
729 /* Expire a few keys per cycle, only if this is a master.
730 * On slaves we wait for DEL operations synthesized by the master
731 * in order to guarantee a strict consistency. */
732 if (server
.masterhost
== NULL
) activeExpireCycle();
734 /* Replication cron function -- used to reconnect to master and
735 * to detect transfer failures. */
736 if (!(loops
% 10)) replicationCron();
738 /* Run other sub-systems specific cron jobs */
739 if (server
.cluster_enabled
&& !(loops
% 10)) clusterCron();
745 /* This function gets called every time Redis is entering the
746 * main loop of the event driven library, that is, before to sleep
747 * for ready file descriptors. */
748 void beforeSleep(struct aeEventLoop
*eventLoop
) {
749 REDIS_NOTUSED(eventLoop
);
753 /* Try to process pending commands for clients that were just unblocked. */
754 while (listLength(server
.unblocked_clients
)) {
755 ln
= listFirst(server
.unblocked_clients
);
756 redisAssert(ln
!= NULL
);
758 listDelNode(server
.unblocked_clients
,ln
);
759 c
->flags
&= ~REDIS_UNBLOCKED
;
761 /* Process remaining data in the input buffer. */
762 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
763 processInputBuffer(c
);
766 /* Write the AOF buffer on disk */
767 flushAppendOnlyFile(0);
770 /* =========================== Server initialization ======================== */
772 void createSharedObjects(void) {
775 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
776 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
777 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
778 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
779 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
780 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
781 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
782 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
783 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
784 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
785 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
786 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
787 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
788 "-ERR Operation against a key holding the wrong kind of value\r\n"));
789 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
790 "-ERR no such key\r\n"));
791 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
792 "-ERR syntax error\r\n"));
793 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
794 "-ERR source and destination objects are the same\r\n"));
795 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
796 "-ERR index out of range\r\n"));
797 shared
.noscripterr
= createObject(REDIS_STRING
,sdsnew(
798 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
799 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
800 "-LOADING Redis is loading the dataset in memory\r\n"));
801 shared
.slowscripterr
= createObject(REDIS_STRING
,sdsnew(
802 "-BUSY Redis is busy running a script. Please wait or stop the server with SHUTDOWN.\r\n"));
803 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
804 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
805 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
806 shared
.select0
= createStringObject("select 0\r\n",10);
807 shared
.select1
= createStringObject("select 1\r\n",10);
808 shared
.select2
= createStringObject("select 2\r\n",10);
809 shared
.select3
= createStringObject("select 3\r\n",10);
810 shared
.select4
= createStringObject("select 4\r\n",10);
811 shared
.select5
= createStringObject("select 5\r\n",10);
812 shared
.select6
= createStringObject("select 6\r\n",10);
813 shared
.select7
= createStringObject("select 7\r\n",10);
814 shared
.select8
= createStringObject("select 8\r\n",10);
815 shared
.select9
= createStringObject("select 9\r\n",10);
816 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
817 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
818 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
819 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
820 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
821 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
822 shared
.mbulk3
= createStringObject("*3\r\n",4);
823 shared
.mbulk4
= createStringObject("*4\r\n",4);
824 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
825 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
826 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
830 void initServerConfig() {
831 server
.port
= REDIS_SERVERPORT
;
832 server
.bindaddr
= NULL
;
833 server
.unixsocket
= NULL
;
834 server
.unixsocketperm
= 0;
837 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
838 server
.verbosity
= REDIS_VERBOSE
;
839 server
.maxidletime
= REDIS_MAXIDLETIME
;
840 server
.saveparams
= NULL
;
842 server
.logfile
= NULL
; /* NULL = log on standard output */
843 server
.syslog_enabled
= 0;
844 server
.syslog_ident
= zstrdup("redis");
845 server
.syslog_facility
= LOG_LOCAL0
;
846 server
.daemonize
= 0;
847 server
.appendonly
= 0;
848 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
849 server
.no_appendfsync_on_rewrite
= 0;
850 server
.auto_aofrewrite_perc
= REDIS_AUTO_AOFREWRITE_PERC
;
851 server
.auto_aofrewrite_min_size
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
;
852 server
.auto_aofrewrite_base_size
= 0;
853 server
.aofrewrite_scheduled
= 0;
854 server
.lastfsync
= time(NULL
);
855 server
.appendfd
= -1;
856 server
.appendseldb
= -1; /* Make sure the first time will not match */
857 server
.aof_flush_postponed_start
= 0;
858 server
.pidfile
= zstrdup("/var/run/redis.pid");
859 server
.dbfilename
= zstrdup("dump.rdb");
860 server
.appendfilename
= zstrdup("appendonly.aof");
861 server
.requirepass
= NULL
;
862 server
.rdbcompression
= 1;
863 server
.activerehashing
= 1;
864 server
.maxclients
= REDIS_MAX_CLIENTS
;
865 server
.bpop_blocked_clients
= 0;
866 server
.maxmemory
= 0;
867 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
868 server
.maxmemory_samples
= 3;
869 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
870 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
871 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
872 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
873 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
874 server
.zset_max_ziplist_entries
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
;
875 server
.zset_max_ziplist_value
= REDIS_ZSET_MAX_ZIPLIST_VALUE
;
876 server
.shutdown_asap
= 0;
877 server
.repl_ping_slave_period
= REDIS_REPL_PING_SLAVE_PERIOD
;
878 server
.repl_timeout
= REDIS_REPL_TIMEOUT
;
879 server
.cluster_enabled
= 0;
880 server
.cluster
.configfile
= zstrdup("nodes.conf");
881 server
.lua_time_limit
= REDIS_LUA_TIME_LIMIT
;
882 server
.lua_client
= NULL
;
883 server
.lua_timedout
= 0;
886 resetServerSaveParams();
888 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
889 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
890 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
891 /* Replication related */
893 server
.masterauth
= NULL
;
894 server
.masterhost
= NULL
;
895 server
.masterport
= 6379;
896 server
.master
= NULL
;
897 server
.replstate
= REDIS_REPL_NONE
;
898 server
.repl_syncio_timeout
= REDIS_REPL_SYNCIO_TIMEOUT
;
899 server
.repl_serve_stale_data
= 1;
900 server
.repl_down_since
= -1;
902 /* Double constants initialization */
904 R_PosInf
= 1.0/R_Zero
;
905 R_NegInf
= -1.0/R_Zero
;
906 R_Nan
= R_Zero
/R_Zero
;
908 /* Command table -- we intiialize it here as it is part of the
909 * initial configuration, since command names may be changed via
910 * redis.conf using the rename-command directive. */
911 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
912 populateCommandTable();
913 server
.delCommand
= lookupCommandByCString("del");
914 server
.multiCommand
= lookupCommandByCString("multi");
917 server
.slowlog_log_slower_than
= REDIS_SLOWLOG_LOG_SLOWER_THAN
;
918 server
.slowlog_max_len
= REDIS_SLOWLOG_MAX_LEN
;
924 signal(SIGHUP
, SIG_IGN
);
925 signal(SIGPIPE
, SIG_IGN
);
926 setupSignalHandlers();
928 if (server
.syslog_enabled
) {
929 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
930 server
.syslog_facility
);
933 server
.clients
= listCreate();
934 server
.slaves
= listCreate();
935 server
.monitors
= listCreate();
936 server
.unblocked_clients
= listCreate();
938 createSharedObjects();
939 server
.el
= aeCreateEventLoop();
940 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
942 if (server
.port
!= 0) {
943 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
944 if (server
.ipfd
== ANET_ERR
) {
945 redisLog(REDIS_WARNING
, "Opening port %d: %s",
946 server
.port
, server
.neterr
);
950 if (server
.unixsocket
!= NULL
) {
951 unlink(server
.unixsocket
); /* don't care if this fails */
952 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
,server
.unixsocketperm
);
953 if (server
.sofd
== ANET_ERR
) {
954 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
958 if (server
.ipfd
< 0 && server
.sofd
< 0) {
959 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
962 for (j
= 0; j
< server
.dbnum
; j
++) {
963 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
964 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
965 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
966 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
969 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
970 server
.pubsub_patterns
= listCreate();
971 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
972 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
973 server
.cronloops
= 0;
974 server
.bgsavechildpid
= -1;
975 server
.bgrewritechildpid
= -1;
976 server
.bgrewritebuf
= sdsempty();
977 server
.aofbuf
= sdsempty();
978 server
.lastsave
= time(NULL
);
980 server
.stat_numcommands
= 0;
981 server
.stat_numconnections
= 0;
982 server
.stat_expiredkeys
= 0;
983 server
.stat_evictedkeys
= 0;
984 server
.stat_starttime
= time(NULL
);
985 server
.stat_keyspace_misses
= 0;
986 server
.stat_keyspace_hits
= 0;
987 server
.stat_peak_memory
= 0;
988 server
.stat_fork_time
= 0;
989 server
.unixtime
= time(NULL
);
990 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
991 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
992 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
993 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
994 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
996 if (server
.appendonly
) {
997 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
998 if (server
.appendfd
== -1) {
999 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1005 if (server
.cluster_enabled
) clusterInit();
1009 srand(time(NULL
)^getpid());
1011 /* Try to raise the max number of open files accordingly to the
1012 * configured max number of clients. Also account for 32 additional
1013 * file descriptors as we need a few more for persistence, listening
1014 * sockets, log files and so forth. */
1016 rlim_t maxfiles
= server
.maxclients
+32;
1017 struct rlimit limit
;
1019 if (maxfiles
< 1024) maxfiles
= 1024;
1020 if (getrlimit(RLIMIT_NOFILE
,&limit
) == -1) {
1021 redisLog(REDIS_WARNING
,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.",
1023 server
.maxclients
= 1024-32;
1025 rlim_t oldlimit
= limit
.rlim_cur
;
1027 /* Set the max number of files if the current limit is not enough
1029 if (oldlimit
< maxfiles
) {
1030 limit
.rlim_cur
= maxfiles
;
1031 limit
.rlim_max
= maxfiles
;
1032 if (setrlimit(RLIMIT_NOFILE
,&limit
) == -1) {
1033 server
.maxclients
= oldlimit
-32;
1034 redisLog(REDIS_WARNING
,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.",
1035 (int) maxfiles
, strerror(errno
), (int) server
.maxclients
);
1037 redisLog(REDIS_NOTICE
,"Max number of open files set to %d",
1045 /* Populates the Redis Command Table starting from the hard coded list
1046 * we have on top of redis.c file. */
1047 void populateCommandTable(void) {
1049 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1051 for (j
= 0; j
< numcommands
; j
++) {
1052 struct redisCommand
*c
= redisCommandTable
+j
;
1053 char *f
= c
->sflags
;
1058 case 'w': c
->flags
|= REDIS_CMD_WRITE
; break;
1059 case 'r': c
->flags
|= REDIS_CMD_READONLY
; break;
1060 case 'm': c
->flags
|= REDIS_CMD_DENYOOM
; break;
1061 case 'a': c
->flags
|= REDIS_CMD_ADMIN
; break;
1062 case 'p': c
->flags
|= REDIS_CMD_PUBSUB
; break;
1063 case 'f': c
->flags
|= REDIS_CMD_FORCE_REPLICATION
; break;
1064 case 's': c
->flags
|= REDIS_CMD_NOSCRIPT
; break;
1065 case 'R': c
->flags
|= REDIS_CMD_RANDOM
; break;
1066 default: redisPanic("Unsupported command flag"); break;
1071 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
1072 assert(retval
== DICT_OK
);
1076 void resetCommandTableStats(void) {
1077 int numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1080 for (j
= 0; j
< numcommands
; j
++) {
1081 struct redisCommand
*c
= redisCommandTable
+j
;
1083 c
->microseconds
= 0;
1088 /* ====================== Commands lookup and execution ===================== */
1090 struct redisCommand
*lookupCommand(sds name
) {
1091 return dictFetchValue(server
.commands
, name
);
1094 struct redisCommand
*lookupCommandByCString(char *s
) {
1095 struct redisCommand
*cmd
;
1096 sds name
= sdsnew(s
);
1098 cmd
= dictFetchValue(server
.commands
, name
);
1103 /* Call() is the core of Redis execution of a command */
1104 void call(redisClient
*c
) {
1105 long long dirty
, start
= ustime(), duration
;
1107 dirty
= server
.dirty
;
1109 dirty
= server
.dirty
-dirty
;
1110 duration
= ustime()-start
;
1111 c
->cmd
->microseconds
+= duration
;
1112 slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
);
1115 if (server
.appendonly
&& dirty
> 0)
1116 feedAppendOnlyFile(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1117 if ((dirty
> 0 || c
->cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
1118 listLength(server
.slaves
))
1119 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
1120 if (listLength(server
.monitors
))
1121 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
1122 server
.stat_numcommands
++;
1125 /* If this function gets called we already read a whole
1126 * command, argments are in the client argv/argc fields.
1127 * processCommand() execute the command or prepare the
1128 * server for a bulk read from the client.
1130 * If 1 is returned the client is still alive and valid and
1131 * and other operations can be performed by the caller. Otherwise
1132 * if 0 is returned the client was destroied (i.e. after QUIT). */
1133 int processCommand(redisClient
*c
) {
1134 /* The QUIT command is handled separately. Normal command procs will
1135 * go through checking for replication and QUIT will cause trouble
1136 * when FORCE_REPLICATION is enabled and would be implemented in
1137 * a regular command proc. */
1138 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1139 addReply(c
,shared
.ok
);
1140 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1144 /* Now lookup the command and check ASAP about trivial error conditions
1145 * such as wrong arity, bad command name and so forth. */
1146 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1148 addReplyErrorFormat(c
,"unknown command '%s'",
1149 (char*)c
->argv
[0]->ptr
);
1151 } else if ((c
->cmd
->arity
> 0 && c
->cmd
->arity
!= c
->argc
) ||
1152 (c
->argc
< -c
->cmd
->arity
)) {
1153 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
1158 /* Check if the user is authenticated */
1159 if (server
.requirepass
&& !c
->authenticated
&& c
->cmd
->proc
!= authCommand
)
1161 addReplyError(c
,"operation not permitted");
1165 /* If cluster is enabled, redirect here */
1166 if (server
.cluster_enabled
&&
1167 !(c
->cmd
->getkeys_proc
== NULL
&& c
->cmd
->firstkey
== 0)) {
1170 if (server
.cluster
.state
!= REDIS_CLUSTER_OK
) {
1171 addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information");
1175 clusterNode
*n
= getNodeByQuery(c
,c
->cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
);
1177 addReplyError(c
,"Multi keys request invalid in cluster");
1179 } else if (n
!= server
.cluster
.myself
) {
1180 addReplySds(c
,sdscatprintf(sdsempty(),
1181 "-%s %d %s:%d\r\n", ask
? "ASK" : "MOVED",
1182 hashslot
,n
->ip
,n
->port
));
1188 /* Handle the maxmemory directive.
1190 * First we try to free some memory if possible (if there are volatile
1191 * keys in the dataset). If there are not the only thing we can do
1192 * is returning an error. */
1193 if (server
.maxmemory
) freeMemoryIfNeeded();
1194 if (server
.maxmemory
&& (c
->cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1195 zmalloc_used_memory() > server
.maxmemory
)
1197 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1201 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1202 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1204 c
->cmd
->proc
!= subscribeCommand
&&
1205 c
->cmd
->proc
!= unsubscribeCommand
&&
1206 c
->cmd
->proc
!= psubscribeCommand
&&
1207 c
->cmd
->proc
!= punsubscribeCommand
) {
1208 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1212 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1213 * we are a slave with a broken link with master. */
1214 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1215 server
.repl_serve_stale_data
== 0 &&
1216 c
->cmd
->proc
!= infoCommand
&& c
->cmd
->proc
!= slaveofCommand
)
1219 "link with MASTER is down and slave-serve-stale-data is set to no");
1223 /* Loading DB? Return an error if the command is not INFO */
1224 if (server
.loading
&& c
->cmd
->proc
!= infoCommand
) {
1225 addReply(c
, shared
.loadingerr
);
1229 /* Lua script too slow? */
1230 if (server
.lua_timedout
&& c
->cmd
->proc
!= shutdownCommand
) {
1231 addReply(c
, shared
.slowscripterr
);
1235 /* Exec the command */
1236 if (c
->flags
& REDIS_MULTI
&&
1237 c
->cmd
->proc
!= execCommand
&& c
->cmd
->proc
!= discardCommand
&&
1238 c
->cmd
->proc
!= multiCommand
&& c
->cmd
->proc
!= watchCommand
)
1240 queueMultiCommand(c
);
1241 addReply(c
,shared
.queued
);
1248 /*================================== Shutdown =============================== */
1250 int prepareForShutdown() {
1251 redisLog(REDIS_WARNING
,"User requested shutdown...");
1252 /* Kill the saving child if there is a background saving in progress.
1253 We want to avoid race conditions, for instance our saving child may
1254 overwrite the synchronous saving did by SHUTDOWN. */
1255 if (server
.bgsavechildpid
!= -1) {
1256 redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!");
1257 kill(server
.bgsavechildpid
,SIGKILL
);
1258 rdbRemoveTempFile(server
.bgsavechildpid
);
1260 if (server
.appendonly
) {
1261 /* Kill the AOF saving child as the AOF we already have may be longer
1262 * but contains the full dataset anyway. */
1263 if (server
.bgrewritechildpid
!= -1) {
1264 redisLog(REDIS_WARNING
,
1265 "There is a child rewriting the AOF. Killing it!");
1266 kill(server
.bgrewritechildpid
,SIGKILL
);
1268 /* Append only file: fsync() the AOF and exit */
1269 redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file.");
1270 aof_fsync(server
.appendfd
);
1272 if (server
.saveparamslen
> 0) {
1273 redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting.");
1274 /* Snapshotting. Perform a SYNC SAVE and exit */
1275 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1276 /* Ooops.. error saving! The best we can do is to continue
1277 * operating. Note that if there was a background saving process,
1278 * in the next cron() Redis will be notified that the background
1279 * saving aborted, handling special stuff like slaves pending for
1280 * synchronization... */
1281 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit.");
1285 if (server
.daemonize
) {
1286 redisLog(REDIS_NOTICE
,"Removing the pid file.");
1287 unlink(server
.pidfile
);
1289 /* Close the listening sockets. Apparently this allows faster restarts. */
1290 if (server
.ipfd
!= -1) close(server
.ipfd
);
1291 if (server
.sofd
!= -1) close(server
.sofd
);
1292 if (server
.unixsocket
) {
1293 redisLog(REDIS_NOTICE
,"Removing the unix socket file.");
1294 unlink(server
.unixsocket
); /* don't care if this fails */
1297 redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye...");
1301 /*================================== Commands =============================== */
1303 void authCommand(redisClient
*c
) {
1304 if (!server
.requirepass
) {
1305 addReplyError(c
,"Client sent AUTH, but no password is set");
1306 } else if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1307 c
->authenticated
= 1;
1308 addReply(c
,shared
.ok
);
1310 c
->authenticated
= 0;
1311 addReplyError(c
,"invalid password");
1315 void pingCommand(redisClient
*c
) {
1316 addReply(c
,shared
.pong
);
1319 void echoCommand(redisClient
*c
) {
1320 addReplyBulk(c
,c
->argv
[1]);
1323 /* Convert an amount of bytes into a human readable string in the form
1324 * of 100B, 2G, 100M, 4K, and so forth. */
1325 void bytesToHuman(char *s
, unsigned long long n
) {
1330 sprintf(s
,"%lluB",n
);
1332 } else if (n
< (1024*1024)) {
1333 d
= (double)n
/(1024);
1334 sprintf(s
,"%.2fK",d
);
1335 } else if (n
< (1024LL*1024*1024)) {
1336 d
= (double)n
/(1024*1024);
1337 sprintf(s
,"%.2fM",d
);
1338 } else if (n
< (1024LL*1024*1024*1024)) {
1339 d
= (double)n
/(1024LL*1024*1024);
1340 sprintf(s
,"%.2fG",d
);
1344 /* Create the string returned by the INFO command. This is decoupled
1345 * by the INFO command itself as we need to report the same information
1346 * on memory corruption problems. */
1347 sds
genRedisInfoString(char *section
) {
1348 sds info
= sdsempty();
1349 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1351 struct rusage self_ru
, c_ru
;
1352 unsigned long lol
, bib
;
1353 int allsections
= 0, defsections
= 0;
1357 allsections
= strcasecmp(section
,"all") == 0;
1358 defsections
= strcasecmp(section
,"default") == 0;
1361 getrusage(RUSAGE_SELF
, &self_ru
);
1362 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1363 getClientsMaxBuffers(&lol
,&bib
);
1366 if (allsections
|| defsections
|| !strcasecmp(section
,"server")) {
1367 if (sections
++) info
= sdscat(info
,"\r\n");
1368 info
= sdscatprintf(info
,
1370 "redis_version:%s\r\n"
1371 "redis_git_sha1:%s\r\n"
1372 "redis_git_dirty:%d\r\n"
1374 "multiplexing_api:%s\r\n"
1375 "process_id:%ld\r\n"
1377 "uptime_in_seconds:%ld\r\n"
1378 "uptime_in_days:%ld\r\n"
1379 "lru_clock:%ld\r\n",
1382 strtol(redisGitDirty(),NULL
,10) > 0,
1383 (sizeof(long) == 8) ? "64" : "32",
1389 (unsigned long) server
.lruclock
);
1393 if (allsections
|| defsections
|| !strcasecmp(section
,"clients")) {
1394 if (sections
++) info
= sdscat(info
,"\r\n");
1395 info
= sdscatprintf(info
,
1397 "connected_clients:%d\r\n"
1398 "client_longest_output_list:%lu\r\n"
1399 "client_biggest_input_buf:%lu\r\n"
1400 "blocked_clients:%d\r\n",
1401 listLength(server
.clients
)-listLength(server
.slaves
),
1403 server
.bpop_blocked_clients
);
1407 if (allsections
|| defsections
|| !strcasecmp(section
,"memory")) {
1411 bytesToHuman(hmem
,zmalloc_used_memory());
1412 bytesToHuman(peak_hmem
,server
.stat_peak_memory
);
1413 if (sections
++) info
= sdscat(info
,"\r\n");
1414 info
= sdscatprintf(info
,
1416 "used_memory:%zu\r\n"
1417 "used_memory_human:%s\r\n"
1418 "used_memory_rss:%zu\r\n"
1419 "used_memory_peak:%zu\r\n"
1420 "used_memory_peak_human:%s\r\n"
1421 "used_memory_lua:%lld\r\n"
1422 "mem_fragmentation_ratio:%.2f\r\n"
1423 "mem_allocator:%s\r\n",
1424 zmalloc_used_memory(),
1427 server
.stat_peak_memory
,
1429 ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL,
1430 zmalloc_get_fragmentation_ratio(),
1436 if (allsections
|| defsections
|| !strcasecmp(section
,"persistence")) {
1437 if (sections
++) info
= sdscat(info
,"\r\n");
1438 info
= sdscatprintf(info
,
1441 "aof_enabled:%d\r\n"
1442 "changes_since_last_save:%lld\r\n"
1443 "bgsave_in_progress:%d\r\n"
1444 "last_save_time:%ld\r\n"
1445 "bgrewriteaof_in_progress:%d\r\n",
1449 server
.bgsavechildpid
!= -1,
1451 server
.bgrewritechildpid
!= -1);
1453 if (server
.appendonly
) {
1454 info
= sdscatprintf(info
,
1455 "aof_current_size:%lld\r\n"
1456 "aof_base_size:%lld\r\n"
1457 "aof_pending_rewrite:%d\r\n",
1458 (long long) server
.appendonly_current_size
,
1459 (long long) server
.auto_aofrewrite_base_size
,
1460 server
.aofrewrite_scheduled
);
1463 if (server
.loading
) {
1465 time_t eta
, elapsed
;
1466 off_t remaining_bytes
= server
.loading_total_bytes
-
1467 server
.loading_loaded_bytes
;
1469 perc
= ((double)server
.loading_loaded_bytes
/
1470 server
.loading_total_bytes
) * 100;
1472 elapsed
= time(NULL
)-server
.loading_start_time
;
1474 eta
= 1; /* A fake 1 second figure if we don't have
1477 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1480 info
= sdscatprintf(info
,
1481 "loading_start_time:%ld\r\n"
1482 "loading_total_bytes:%llu\r\n"
1483 "loading_loaded_bytes:%llu\r\n"
1484 "loading_loaded_perc:%.2f\r\n"
1485 "loading_eta_seconds:%ld\r\n"
1486 ,(unsigned long) server
.loading_start_time
,
1487 (unsigned long long) server
.loading_total_bytes
,
1488 (unsigned long long) server
.loading_loaded_bytes
,
1496 if (allsections
|| defsections
|| !strcasecmp(section
,"stats")) {
1497 if (sections
++) info
= sdscat(info
,"\r\n");
1498 info
= sdscatprintf(info
,
1500 "total_connections_received:%lld\r\n"
1501 "total_commands_processed:%lld\r\n"
1502 "expired_keys:%lld\r\n"
1503 "evicted_keys:%lld\r\n"
1504 "keyspace_hits:%lld\r\n"
1505 "keyspace_misses:%lld\r\n"
1506 "pubsub_channels:%ld\r\n"
1507 "pubsub_patterns:%u\r\n"
1508 "latest_fork_usec:%lld\r\n",
1509 server
.stat_numconnections
,
1510 server
.stat_numcommands
,
1511 server
.stat_expiredkeys
,
1512 server
.stat_evictedkeys
,
1513 server
.stat_keyspace_hits
,
1514 server
.stat_keyspace_misses
,
1515 dictSize(server
.pubsub_channels
),
1516 listLength(server
.pubsub_patterns
),
1517 server
.stat_fork_time
);
1521 if (allsections
|| defsections
|| !strcasecmp(section
,"replication")) {
1522 if (sections
++) info
= sdscat(info
,"\r\n");
1523 info
= sdscatprintf(info
,
1526 server
.masterhost
== NULL
? "master" : "slave");
1527 if (server
.masterhost
) {
1528 info
= sdscatprintf(info
,
1529 "master_host:%s\r\n"
1530 "master_port:%d\r\n"
1531 "master_link_status:%s\r\n"
1532 "master_last_io_seconds_ago:%d\r\n"
1533 "master_sync_in_progress:%d\r\n"
1536 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1539 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1540 server
.replstate
== REDIS_REPL_TRANSFER
1543 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1544 info
= sdscatprintf(info
,
1545 "master_sync_left_bytes:%ld\r\n"
1546 "master_sync_last_io_seconds_ago:%d\r\n"
1547 ,(long)server
.repl_transfer_left
,
1548 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1552 if (server
.replstate
!= REDIS_REPL_CONNECTED
) {
1553 info
= sdscatprintf(info
,
1554 "master_link_down_since_seconds:%ld\r\n",
1555 (long)time(NULL
)-server
.repl_down_since
);
1558 info
= sdscatprintf(info
,
1559 "connected_slaves:%d\r\n",
1560 listLength(server
.slaves
));
1564 if (allsections
|| defsections
|| !strcasecmp(section
,"cpu")) {
1565 if (sections
++) info
= sdscat(info
,"\r\n");
1566 info
= sdscatprintf(info
,
1568 "used_cpu_sys:%.2f\r\n"
1569 "used_cpu_user:%.2f\r\n"
1570 "used_cpu_sys_children:%.2f\r\n"
1571 "used_cpu_user_children:%.2f\r\n",
1572 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1573 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1574 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1575 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000);
1579 if (allsections
|| !strcasecmp(section
,"commandstats")) {
1580 if (sections
++) info
= sdscat(info
,"\r\n");
1581 info
= sdscatprintf(info
, "# Commandstats\r\n");
1582 numcommands
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
);
1583 for (j
= 0; j
< numcommands
; j
++) {
1584 struct redisCommand
*c
= redisCommandTable
+j
;
1586 if (!c
->calls
) continue;
1587 info
= sdscatprintf(info
,
1588 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1589 c
->name
, c
->calls
, c
->microseconds
,
1590 (c
->calls
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
));
1595 if (allsections
|| defsections
|| !strcasecmp(section
,"cluster")) {
1596 if (sections
++) info
= sdscat(info
,"\r\n");
1597 info
= sdscatprintf(info
,
1599 "cluster_enabled:%d\r\n",
1600 server
.cluster_enabled
);
1604 if (allsections
|| defsections
|| !strcasecmp(section
,"keyspace")) {
1605 if (sections
++) info
= sdscat(info
,"\r\n");
1606 info
= sdscatprintf(info
, "# Keyspace\r\n");
1607 for (j
= 0; j
< server
.dbnum
; j
++) {
1608 long long keys
, vkeys
;
1610 keys
= dictSize(server
.db
[j
].dict
);
1611 vkeys
= dictSize(server
.db
[j
].expires
);
1612 if (keys
|| vkeys
) {
1613 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1621 void infoCommand(redisClient
*c
) {
1622 char *section
= c
->argc
== 2 ? c
->argv
[1]->ptr
: "default";
1625 addReply(c
,shared
.syntaxerr
);
1628 sds info
= genRedisInfoString(section
);
1629 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1630 (unsigned long)sdslen(info
)));
1631 addReplySds(c
,info
);
1632 addReply(c
,shared
.crlf
);
1635 void monitorCommand(redisClient
*c
) {
1636 /* ignore MONITOR if aleady slave or in monitor mode */
1637 if (c
->flags
& REDIS_SLAVE
) return;
1639 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1641 listAddNodeTail(server
.monitors
,c
);
1642 addReply(c
,shared
.ok
);
1645 /* ============================ Maxmemory directive ======================== */
1647 /* This function gets called when 'maxmemory' is set on the config file to limit
1648 * the max memory used by the server, and we are out of memory.
1649 * This function will try to, in order:
1651 * - Free objects from the free list
1652 * - Try to remove keys with an EXPIRE set
1654 * It is not possible to free enough memory to reach used-memory < maxmemory
1655 * the server will start refusing commands that will enlarge even more the
1658 void freeMemoryIfNeeded(void) {
1659 /* Remove keys accordingly to the active policy as long as we are
1660 * over the memory limit. */
1661 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1663 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1664 int j
, k
, freed
= 0;
1666 for (j
= 0; j
< server
.dbnum
; j
++) {
1667 long bestval
= 0; /* just to prevent warning */
1669 struct dictEntry
*de
;
1670 redisDb
*db
= server
.db
+j
;
1673 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1674 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1676 dict
= server
.db
[j
].dict
;
1678 dict
= server
.db
[j
].expires
;
1680 if (dictSize(dict
) == 0) continue;
1682 /* volatile-random and allkeys-random policy */
1683 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1684 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1686 de
= dictGetRandomKey(dict
);
1687 bestkey
= dictGetKey(de
);
1690 /* volatile-lru and allkeys-lru policy */
1691 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1692 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1694 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1699 de
= dictGetRandomKey(dict
);
1700 thiskey
= dictGetKey(de
);
1701 /* When policy is volatile-lru we need an additonal lookup
1702 * to locate the real key, as dict is set to db->expires. */
1703 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1704 de
= dictFind(db
->dict
, thiskey
);
1706 thisval
= estimateObjectIdleTime(o
);
1708 /* Higher idle time is better candidate for deletion */
1709 if (bestkey
== NULL
|| thisval
> bestval
) {
1717 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1718 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1722 de
= dictGetRandomKey(dict
);
1723 thiskey
= dictGetKey(de
);
1724 thisval
= (long) dictGetVal(de
);
1726 /* Expire sooner (minor expire unix timestamp) is better
1727 * candidate for deletion */
1728 if (bestkey
== NULL
|| thisval
< bestval
) {
1735 /* Finally remove the selected key. */
1737 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1738 propagateExpire(db
,keyobj
);
1739 dbDelete(db
,keyobj
);
1740 server
.stat_evictedkeys
++;
1741 decrRefCount(keyobj
);
1745 if (!freed
) return; /* nothing to free... */
1749 /* =================================== Main! ================================ */
1752 int linuxOvercommitMemoryValue(void) {
1753 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1757 if (fgets(buf
,64,fp
) == NULL
) {
1766 void linuxOvercommitMemoryWarning(void) {
1767 if (linuxOvercommitMemoryValue() == 0) {
1768 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.");
1771 #endif /* __linux__ */
1773 void createPidFile(void) {
1774 /* Try to write the pid file in a best-effort way. */
1775 FILE *fp
= fopen(server
.pidfile
,"w");
1777 fprintf(fp
,"%d\n",(int)getpid());
1782 void daemonize(void) {
1785 if (fork() != 0) exit(0); /* parent exits */
1786 setsid(); /* create a new session */
1788 /* Every output goes to /dev/null. If Redis is daemonized but
1789 * the 'logfile' is set to 'stdout' in the configuration file
1790 * it will not log at all. */
1791 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1792 dup2(fd
, STDIN_FILENO
);
1793 dup2(fd
, STDOUT_FILENO
);
1794 dup2(fd
, STDERR_FILENO
);
1795 if (fd
> STDERR_FILENO
) close(fd
);
1800 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1801 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1806 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1807 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1811 void redisAsciiArt(void) {
1812 #include "asciilogo.h"
1813 char *buf
= zmalloc(1024*16);
1815 snprintf(buf
,1024*16,ascii_logo
,
1818 strtol(redisGitDirty(),NULL
,10) > 0,
1819 (sizeof(long) == 8) ? "64" : "32",
1820 server
.cluster_enabled
? "cluster" : "stand alone",
1824 redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
);
1828 int main(int argc
, char **argv
) {
1831 zmalloc_enable_thread_safeness();
1834 if (strcmp(argv
[1], "-v") == 0 ||
1835 strcmp(argv
[1], "--version") == 0) version();
1836 if (strcmp(argv
[1], "--help") == 0) usage();
1837 resetServerSaveParams();
1838 loadServerConfig(argv
[1]);
1839 } else if ((argc
> 2)) {
1842 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'");
1844 if (server
.daemonize
) daemonize();
1846 if (server
.daemonize
) createPidFile();
1848 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1850 linuxOvercommitMemoryWarning();
1853 if (server
.appendonly
) {
1854 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1855 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000);
1857 if (rdbLoad(server
.dbfilename
) == REDIS_OK
) {
1858 redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",
1859 (float)(ustime()-start
)/1000000);
1860 } else if (errno
!= ENOENT
) {
1861 redisLog(REDIS_WARNING
,"Fatal error loading the DB. Exiting.");
1865 if (server
.ipfd
> 0)
1866 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1867 if (server
.sofd
> 0)
1868 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1869 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1871 aeDeleteEventLoop(server
.el
);
1875 #ifdef HAVE_BACKTRACE
1876 static void *getMcontextEip(ucontext_t
*uc
) {
1877 #if defined(__FreeBSD__)
1878 return (void*) uc
->uc_mcontext
.mc_eip
;
1879 #elif defined(__dietlibc__)
1880 return (void*) uc
->uc_mcontext
.eip
;
1881 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1883 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1885 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1887 return (void*) uc
->uc_mcontext
->__ss
.__srr0
;
1889 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1890 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1891 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1893 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1895 #elif defined(__i386__)
1896 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1897 #elif defined(__X86_64__) || defined(__x86_64__)
1898 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1899 #elif defined(__ia64__) /* Linux IA64 */
1900 return (void*) uc
->uc_mcontext
.sc_ip
;
1906 static void sigsegvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1908 char **messages
= NULL
;
1909 int i
, trace_size
= 0;
1910 ucontext_t
*uc
= (ucontext_t
*) secret
;
1912 struct sigaction act
;
1913 REDIS_NOTUSED(info
);
1915 redisLog(REDIS_WARNING
,
1916 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1917 infostring
= genRedisInfoString("all");
1918 redisLogRaw(REDIS_WARNING
, infostring
);
1919 /* It's not safe to sdsfree() the returned string under memory
1920 * corruption conditions. Let it leak as we are going to abort */
1922 trace_size
= backtrace(trace
, 100);
1923 /* overwrite sigaction with caller's address */
1924 if (getMcontextEip(uc
) != NULL
) {
1925 trace
[1] = getMcontextEip(uc
);
1927 messages
= backtrace_symbols(trace
, trace_size
);
1929 for (i
=1; i
<trace_size
; ++i
)
1930 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1932 /* free(messages); Don't call free() with possibly corrupted memory. */
1933 if (server
.daemonize
) unlink(server
.pidfile
);
1935 /* Make sure we exit with the right signal at the end. So for instance
1936 * the core will be dumped if enabled. */
1937 sigemptyset (&act
.sa_mask
);
1938 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1939 * is used. Otherwise, sa_handler is used */
1940 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1941 act
.sa_handler
= SIG_DFL
;
1942 sigaction (sig
, &act
, NULL
);
1945 #endif /* HAVE_BACKTRACE */
1947 static void sigtermHandler(int sig
) {
1950 redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown...");
1951 server
.shutdown_asap
= 1;
1954 void setupSignalHandlers(void) {
1955 struct sigaction act
;
1957 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1958 * Otherwise, sa_handler is used. */
1959 sigemptyset(&act
.sa_mask
);
1960 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1961 act
.sa_handler
= sigtermHandler
;
1962 sigaction(SIGTERM
, &act
, NULL
);
1964 #ifdef HAVE_BACKTRACE
1965 sigemptyset(&act
.sa_mask
);
1966 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1967 act
.sa_sigaction
= sigsegvHandler
;
1968 sigaction(SIGSEGV
, &act
, NULL
);
1969 sigaction(SIGBUS
, &act
, NULL
);
1970 sigaction(SIGFPE
, &act
, NULL
);
1971 sigaction(SIGILL
, &act
, NULL
);