]> git.saurik.com Git - redis.git/blame - src/redis.c
actually call the function to async free clients in serverCron().
[redis.git] / src / redis.c
CommitLineData
e2641e09 1/*
2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
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.
16 *
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.
28 */
29
30#include "redis.h"
daa70b17 31#include "slowlog.h"
8f61a72f 32#include "bio.h"
e2641e09 33
e2641e09 34#include <time.h>
35#include <signal.h>
36#include <sys/wait.h>
37#include <errno.h>
38#include <assert.h>
39#include <ctype.h>
40#include <stdarg.h>
e2641e09 41#include <arpa/inet.h>
42#include <sys/stat.h>
43#include <fcntl.h>
44#include <sys/time.h>
45#include <sys/resource.h>
46#include <sys/uio.h>
47#include <limits.h>
48#include <float.h>
49#include <math.h>
2b00385d 50#include <sys/resource.h>
e2641e09 51
52/* Our shared "common" objects */
53
54struct sharedObjectsStruct shared;
55
c74b7c77 56/* Global vars that are actually used as constants. The following double
e2641e09 57 * values are used for double on-disk serialization, and are initialized
58 * at runtime to avoid strange compiler optimizations. */
59
60double R_Zero, R_PosInf, R_NegInf, R_Nan;
61
62/*================================= Globals ================================= */
63
64/* Global vars */
65struct redisServer server; /* server global state */
66struct redisCommand *commandTable;
5d02b00f 67
7501c66f 68/* Our command table.
69 *
70 * Every entry is composed of the following fields:
71 *
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.
86 *
87 * The flags, microseconds and calls fields are computed by Redis and should
88 * always be set to zero.
89 *
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.
5d02b00f 93 *
94 * This is the meaning of the flags:
95 *
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.
b60ed6e8 101 * f: force replication of this command, regarless of server.dirty.
102 * s: command not allowed in scripts.
7e14a208 103 * R: random command. Command is not deterministic, that is, the same command
b60ed6e8 104 * with the same arguments, with the same key space, may have different
105 * results. For instance SPOP and RANDOMKEY are two random commands. */
d7ed7fd2 106struct redisCommand redisCommandTable[] = {
5d02b00f 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},
39da5d1f 110 {"setex",setexCommand,4,"wm",0,noPreloadGetKeys,1,1,1,0,0},
111 {"psetex",psetexCommand,4,"wm",0,noPreloadGetKeys,1,1,1,0,0},
5d02b00f 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},
e41677b4 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},
5d02b00f 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},
15ef6053 146 {"spop",spopCommand,2,"wRs",0,NULL,1,1,1,0,0},
b60ed6e8 147 {"srandmember",srandmemberCommand,2,"rR",0,NULL,1,1,1,0,0},
5d02b00f 148 {"sinter",sinterCommand,-2,"r",0,NULL,1,-1,1,0,0},
1bcfa0f6 149 {"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
5d02b00f 150 {"sunion",sunionCommand,-2,"r",0,NULL,1,-1,1,0,0},
1bcfa0f6 151 {"sunionstore",sunionstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
5d02b00f 152 {"sdiff",sdiffCommand,-2,"r",0,NULL,1,-1,1,0,0},
1bcfa0f6 153 {"sdiffstore",sdiffstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
5d02b00f 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},
68bfe993 177 {"hincrbyfloat",hincrbyfloatCommand,4,"wm",0,NULL,1,1,1,0,0},
5d02b00f 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},
5574b53e 186 {"incrbyfloat",incrbyfloatCommand,3,"wm",0,NULL,1,1,1,0,0},
5d02b00f 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},
b60ed6e8 190 {"randomkey",randomkeyCommand,1,"rR",0,NULL,0,0,0,0,0},
5d02b00f 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},
12d293ca 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},
5d02b00f 199 {"keys",keysCommand,2,"r",0,NULL,0,0,0,0,0},
200 {"dbsize",dbsizeCommand,1,"r",0,NULL,0,0,0,0,0},
e41677b4 201 {"auth",authCommand,2,"rs",0,NULL,0,0,0,0,0},
5d02b00f 202 {"ping",pingCommand,1,"r",0,NULL,0,0,0,0,0},
203 {"echo",echoCommand,2,"r",0,NULL,0,0,0,0,0},
e41677b4 204 {"save",saveCommand,1,"ars",0,NULL,0,0,0,0,0},
5d02b00f 205 {"bgsave",bgsaveCommand,1,"ar",0,NULL,0,0,0,0,0},
206 {"bgrewriteaof",bgrewriteaofCommand,1,"ar",0,NULL,0,0,0,0,0},
4ab8695d 207 {"shutdown",shutdownCommand,-1,"ar",0,NULL,0,0,0,0,0},
5d02b00f 208 {"lastsave",lastsaveCommand,1,"r",0,NULL,0,0,0,0,0},
209 {"type",typeCommand,2,"r",0,NULL,1,1,1,0,0},
b60ed6e8 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},
5d02b00f 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},
b60ed6e8 218 {"monitor",monitorCommand,1,"ars",0,NULL,0,0,0,0,0},
12d293ca 219 {"ttl",ttlCommand,2,"r",0,NULL,1,1,1,0,0},
220 {"pttl",pttlCommand,2,"r",0,NULL,1,1,1,0,0},
5d02b00f 221 {"persist",persistCommand,2,"w",0,NULL,1,1,1,0,0},
b60ed6e8 222 {"slaveof",slaveofCommand,3,"aws",0,NULL,0,0,0,0,0},
e41677b4 223 {"debug",debugCommand,-2,"aws",0,NULL,0,0,0,0,0},
5d02b00f 224 {"config",configCommand,-2,"ar",0,NULL,0,0,0,0,0},
b60ed6e8 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},
5d02b00f 229 {"publish",publishCommand,3,"rpf",0,NULL,0,0,0,0,0},
b60ed6e8 230 {"watch",watchCommand,-2,"rs",0,noPreloadGetKeys,1,-1,1,0,0},
231 {"unwatch",unwatchCommand,1,"rs",0,NULL,0,0,0,0,0},
5d02b00f 232 {"cluster",clusterCommand,-2,"ar",0,NULL,0,0,0,0,0},
7afc3a96 233 {"restore",restoreCommand,4,"awm",0,NULL,1,1,1,0,0},
5d02b00f 234 {"migrate",migrateCommand,6,"aw",0,NULL,0,0,0,0,0},
6856c7b4 235 {"asking",askingCommand,1,"r",0,NULL,0,0,0,0,0},
1bcfa0f6 236 {"dump",dumpCommand,2,"ar",0,NULL,1,1,1,0,0},
237 {"object",objectCommand,-2,"r",0,NULL,2,2,2,0,0},
5d02b00f 238 {"client",clientCommand,-2,"ar",0,NULL,0,0,0,0,0},
b60ed6e8 239 {"eval",evalCommand,-3,"wms",0,zunionInterGetKeys,0,0,0,0,0},
240 {"evalsha",evalShaCommand,-3,"wms",0,zunionInterGetKeys,0,0,0,0,0},
070e3945 241 {"slowlog",slowlogCommand,-2,"r",0,NULL,0,0,0,0,0},
242 {"script",scriptCommand,-2,"ras",0,NULL,0,0,0,0,0}
e2641e09 243};
244
245/*============================ Utility functions ============================ */
246
9c104c68 247/* Low level logging. To use only for very big messages, otherwise
248 * redisLog() is to prefer. */
249void redisLogRaw(int level, const char *msg) {
e1a586ee
JH
250 const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING };
251 const char *c = ".-*#";
252 time_t now = time(NULL);
e2641e09 253 FILE *fp;
23072961 254 char buf[64];
996d503d 255 int rawmode = (level & REDIS_LOG_RAW);
23072961 256
996d503d 257 level &= 0xff; /* clear flags */
23072961 258 if (level < server.verbosity) return;
e2641e09 259
260 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
261 if (!fp) return;
262
996d503d 263 if (rawmode) {
264 fprintf(fp,"%s",msg);
265 } else {
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);
268 }
e1a586ee
JH
269 fflush(fp);
270
e2641e09 271 if (server.logfile) fclose(fp);
e1a586ee
JH
272
273 if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg);
e2641e09 274}
275
9c104c68 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. */
279void redisLog(int level, const char *fmt, ...) {
280 va_list ap;
281 char msg[REDIS_MAX_LOGMSG_LEN];
282
996d503d 283 if ((level&0xff) < server.verbosity) return;
9c104c68 284
285 va_start(ap, fmt);
286 vsnprintf(msg, sizeof(msg), fmt, ap);
287 va_end(ap);
288
289 redisLogRaw(level,msg);
290}
291
e2641e09 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... */
297void oom(const char *msg) {
298 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
299 sleep(1);
300 abort();
301}
302
d9cb288c 303/* Return the UNIX time in microseconds */
304long long ustime(void) {
305 struct timeval tv;
306 long long ust;
307
308 gettimeofday(&tv, NULL);
309 ust = ((long long)tv.tv_sec)*1000000;
310 ust += tv.tv_usec;
311 return ust;
312}
313
2c2b2085 314/* Return the UNIX time in milliseconds */
315long long mstime(void) {
316 return ustime()/1000;
317}
318
e2641e09 319/*====================== Hash table type implementation ==================== */
320
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,
323 * lists, sets). */
324
325void dictVanillaFree(void *privdata, void *val)
326{
327 DICT_NOTUSED(privdata);
328 zfree(val);
329}
330
331void dictListDestructor(void *privdata, void *val)
332{
333 DICT_NOTUSED(privdata);
334 listRelease((list*)val);
335}
336
337int dictSdsKeyCompare(void *privdata, const void *key1,
338 const void *key2)
339{
340 int l1,l2;
341 DICT_NOTUSED(privdata);
342
343 l1 = sdslen((sds)key1);
344 l2 = sdslen((sds)key2);
345 if (l1 != l2) return 0;
346 return memcmp(key1, key2, l1) == 0;
347}
348
1b1f47c9 349/* A case insensitive version used for the command lookup table. */
350int dictSdsKeyCaseCompare(void *privdata, const void *key1,
351 const void *key2)
352{
353 DICT_NOTUSED(privdata);
354
355 return strcasecmp(key1, key2) == 0;
356}
357
e2641e09 358void dictRedisObjectDestructor(void *privdata, void *val)
359{
360 DICT_NOTUSED(privdata);
361
362 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
363 decrRefCount(val);
364}
365
366void dictSdsDestructor(void *privdata, void *val)
367{
368 DICT_NOTUSED(privdata);
369
370 sdsfree(val);
371}
372
373int dictObjKeyCompare(void *privdata, const void *key1,
374 const void *key2)
375{
376 const robj *o1 = key1, *o2 = key2;
377 return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
378}
379
380unsigned int dictObjHash(const void *key) {
381 const robj *o = key;
382 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
383}
384
385unsigned int dictSdsHash(const void *key) {
386 return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
387}
388
1b1f47c9 389unsigned int dictSdsCaseHash(const void *key) {
390 return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key));
391}
392
e2641e09 393int dictEncObjKeyCompare(void *privdata, const void *key1,
394 const void *key2)
395{
396 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
397 int cmp;
398
399 if (o1->encoding == REDIS_ENCODING_INT &&
400 o2->encoding == REDIS_ENCODING_INT)
401 return o1->ptr == o2->ptr;
402
403 o1 = getDecodedObject(o1);
404 o2 = getDecodedObject(o2);
405 cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
406 decrRefCount(o1);
407 decrRefCount(o2);
408 return cmp;
409}
410
411unsigned int dictEncObjHash(const void *key) {
412 robj *o = (robj*) key;
413
414 if (o->encoding == REDIS_ENCODING_RAW) {
415 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
416 } else {
417 if (o->encoding == REDIS_ENCODING_INT) {
418 char buf[32];
419 int len;
420
421 len = ll2string(buf,32,(long)o->ptr);
422 return dictGenHashFunction((unsigned char*)buf, len);
423 } else {
424 unsigned int hash;
425
426 o = getDecodedObject(o);
427 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
428 decrRefCount(o);
429 return hash;
430 }
431 }
432}
433
4dd444bb 434/* Sets type hash table */
e2641e09 435dictType setDictType = {
436 dictEncObjHash, /* hash function */
437 NULL, /* key dup */
438 NULL, /* val dup */
439 dictEncObjKeyCompare, /* key compare */
440 dictRedisObjectDestructor, /* key destructor */
441 NULL /* val destructor */
442};
443
444/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
445dictType zsetDictType = {
446 dictEncObjHash, /* hash function */
447 NULL, /* key dup */
448 NULL, /* val dup */
449 dictEncObjKeyCompare, /* key compare */
450 dictRedisObjectDestructor, /* key destructor */
69ef89f2 451 NULL /* val destructor */
e2641e09 452};
453
454/* Db->dict, keys are sds strings, vals are Redis objects. */
455dictType dbDictType = {
456 dictSdsHash, /* hash function */
457 NULL, /* key dup */
458 NULL, /* val dup */
459 dictSdsKeyCompare, /* key compare */
460 dictSdsDestructor, /* key destructor */
461 dictRedisObjectDestructor /* val destructor */
462};
463
464/* Db->expires */
465dictType keyptrDictType = {
466 dictSdsHash, /* hash function */
467 NULL, /* key dup */
468 NULL, /* val dup */
469 dictSdsKeyCompare, /* key compare */
470 NULL, /* key destructor */
471 NULL /* val destructor */
472};
473
1b1f47c9 474/* Command table. sds string -> command struct pointer. */
475dictType commandTableDictType = {
476 dictSdsCaseHash, /* hash function */
477 NULL, /* key dup */
478 NULL, /* val dup */
479 dictSdsKeyCaseCompare, /* key compare */
480 dictSdsDestructor, /* key destructor */
481 NULL /* val destructor */
482};
483
e2641e09 484/* Hash type hash table (note that small hashes are represented with zimpaps) */
485dictType hashDictType = {
486 dictEncObjHash, /* hash function */
487 NULL, /* key dup */
488 NULL, /* val dup */
489 dictEncObjKeyCompare, /* key compare */
490 dictRedisObjectDestructor, /* key destructor */
491 dictRedisObjectDestructor /* val destructor */
492};
493
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. */
497dictType keylistDictType = {
498 dictObjHash, /* hash function */
499 NULL, /* key dup */
500 NULL, /* val dup */
501 dictObjKeyCompare, /* key compare */
502 dictRedisObjectDestructor, /* key destructor */
503 dictListDestructor /* val destructor */
504};
505
ecc91094 506/* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
507 * clusterNode structures. */
508dictType clusterNodesDictType = {
509 dictSdsHash, /* hash function */
510 NULL, /* key dup */
511 NULL, /* val dup */
512 dictSdsKeyCompare, /* key compare */
513 dictSdsDestructor, /* key destructor */
514 NULL /* val destructor */
515};
516
e2641e09 517int htNeedsResize(dict *dict) {
518 long long size, used;
519
520 size = dictSlots(dict);
521 used = dictSize(dict);
522 return (size && used && size > DICT_HT_INITIAL_SIZE &&
523 (used*100/size < REDIS_HT_MINFILL));
524}
525
526/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
527 * we resize the hash table to save memory */
528void tryResizeHashTables(void) {
529 int j;
530
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);
536 }
537}
538
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. */
543void incrementallyRehash(void) {
544 int j;
545
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... */
550 }
551 }
552}
553
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
559 * running childs. */
560void updateDictResizePolicy(void) {
f48cd4b9 561 if (server.rdb_child_pid == -1 && server.aof_child_pid == -1)
e2641e09 562 dictEnableResize();
563 else
564 dictDisableResize();
565}
566
567/* ======================= Cron: called every 100 ms ======================== */
568
bcf2995c 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. */
573void activeExpireCycle(void) {
574 int j;
575
576 for (j = 0; j < server.dbnum; j++) {
577 int expired;
578 redisDb *db = server.db+j;
579
580 /* Continue to expire if at the end of the cycle more than 25%
581 * of the keys were expired. */
582 do {
583 long num = dictSize(db->expires);
4be855e7 584 long long now = mstime();
bcf2995c 585
586 expired = 0;
587 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
588 num = REDIS_EXPIRELOOKUPS_PER_CRON;
589 while (num--) {
590 dictEntry *de;
4be855e7 591 long long t;
bcf2995c 592
593 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
4be855e7 594 t = dictGetSignedIntegerVal(de);
bcf2995c 595 if (now > t) {
c0ba9ebe 596 sds key = dictGetKey(de);
bcf2995c 597 robj *keyobj = createStringObject(key,sdslen(key));
598
599 propagateExpire(db,keyobj);
600 dbDelete(db,keyobj);
601 decrRefCount(keyobj);
602 expired++;
603 server.stat_expiredkeys++;
604 }
605 }
606 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
607 }
608}
609
165346ca 610void updateLRUClock(void) {
611 server.lruclock = (time(NULL)/REDIS_LRU_CLOCK_RESOLUTION) &
612 REDIS_LRU_CLOCK_MAX;
613}
bcf2995c 614
e2641e09 615int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
89a1433e 616 int j, loops = server.cronloops;
e2641e09 617 REDIS_NOTUSED(eventLoop);
618 REDIS_NOTUSED(id);
619 REDIS_NOTUSED(clientData);
620
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);
4f06867a 626
ef59a8bc 627 /* We have just 22 bits per object for LRU information.
165346ca 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.
e2641e09 630 *
165346ca 631 * Note that even if this will wrap after 1.5 years it's not a problem,
ef59a8bc 632 * everything will still work but just some object will appear younger
165346ca 633 * to Redis. But for this to happen a given object should never be touched
634 * for 1.5 years.
635 *
636 * Note that you can change the resolution altering the
637 * REDIS_LRU_CLOCK_RESOLUTION define.
e2641e09 638 */
165346ca 639 updateLRUClock();
e2641e09 640
17b24ff3 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();
644
e2641e09 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) {
4ab8695d 648 if (prepareForShutdown(0) == REDIS_OK) exit(0);
e2641e09 649 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
650 }
651
652 /* Show some info about non-empty databases */
653 for (j = 0; j < server.dbnum; j++) {
654 long long size, used, vkeys;
655
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); */
662 }
663 }
664
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
670 * copied. */
f48cd4b9 671 if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) {
e2641e09 672 if (!(loops % 10)) tryResizeHashTables();
673 if (server.activerehashing) incrementallyRehash();
674 }
675
676 /* Show information about connected clients */
677 if (!(loops % 50)) {
678 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
679 listLength(server.clients)-listLength(server.slaves),
680 listLength(server.slaves),
ca734d17 681 zmalloc_used_memory());
e2641e09 682 }
683
684 /* Close connections of timedout clients */
5fa95ad7 685 if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients)
e2641e09 686 closeTimedoutClients();
687
b333e239 688 /* Start a scheduled AOF rewrite if this was requested by the user while
689 * a BGSAVE was in progress. */
f48cd4b9 690 if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 &&
2c915bcf 691 server.aof_rewrite_scheduled)
b333e239 692 {
693 rewriteAppendOnlyFileBackground();
694 }
695
f03fe802 696 /* Check if a background saving or AOF rewrite in progress terminated. */
f48cd4b9 697 if (server.rdb_child_pid != -1 || server.aof_child_pid != -1) {
e2641e09 698 int statloc;
699 pid_t pid;
700
701 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
36c17a53 702 int exitcode = WEXITSTATUS(statloc);
703 int bysignal = 0;
704
705 if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);
706
f48cd4b9 707 if (pid == server.rdb_child_pid) {
36c17a53 708 backgroundSaveDoneHandler(exitcode,bysignal);
e2641e09 709 } else {
36c17a53 710 backgroundRewriteDoneHandler(exitcode,bysignal);
e2641e09 711 }
712 updateDictResizePolicy();
713 }
c9d0c362 714 } else {
e2641e09 715 time_t now = time(NULL);
b333e239 716
717 /* If there is not a background saving/rewrite in progress check if
718 * we have to save/rewrite now */
e2641e09 719 for (j = 0; j < server.saveparamslen; j++) {
720 struct saveparam *sp = server.saveparams+j;
721
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);
f48cd4b9 726 rdbSaveBackground(server.rdb_filename);
e2641e09 727 break;
728 }
729 }
b333e239 730
731 /* Trigger an AOF rewrite if needed */
f48cd4b9 732 if (server.rdb_child_pid == -1 &&
ff2145ad 733 server.aof_child_pid == -1 &&
2c915bcf 734 server.aof_rewrite_perc &&
735 server.aof_current_size > server.aof_rewrite_min_size)
b333e239 736 {
2c915bcf 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) {
19b46c9a 741 redisLog(REDIS_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth);
b333e239 742 rewriteAppendOnlyFileBackground();
743 }
744 }
e2641e09 745 }
746
db3c2a4f 747
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);
751
bcf2995c 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();
e2641e09 756
8c43e663 757 /* Close clients that need to be closed asynchronous */
758 freeClientsInAsyncFreeQueue();
759
f4aa600b 760 /* Replication cron function -- used to reconnect to master and
761 * to detect transfer failures. */
62ec599c 762 if (!(loops % 10)) replicationCron();
f4aa600b 763
ecc91094 764 /* Run other sub-systems specific cron jobs */
765 if (server.cluster_enabled && !(loops % 10)) clusterCron();
766
89a1433e 767 server.cronloops++;
e2641e09 768 return 100;
769}
770
771/* This function gets called every time Redis is entering the
772 * main loop of the event driven library, that is, before to sleep
773 * for ready file descriptors. */
774void beforeSleep(struct aeEventLoop *eventLoop) {
775 REDIS_NOTUSED(eventLoop);
a4ce7581
PN
776 listNode *ln;
777 redisClient *c;
e2641e09 778
a4ce7581
PN
779 /* Try to process pending commands for clients that were just unblocked. */
780 while (listLength(server.unblocked_clients)) {
781 ln = listFirst(server.unblocked_clients);
782 redisAssert(ln != NULL);
783 c = ln->value;
784 listDelNode(server.unblocked_clients,ln);
3bcffcbe 785 c->flags &= ~REDIS_UNBLOCKED;
a4ce7581
PN
786
787 /* Process remaining data in the input buffer. */
00010fa9 788 if (c->querybuf && sdslen(c->querybuf) > 0) {
789 server.current_client = c;
a4ce7581 790 processInputBuffer(c);
00010fa9 791 server.current_client = NULL;
792 }
a4ce7581
PN
793 }
794
e2641e09 795 /* Write the AOF buffer on disk */
db3c2a4f 796 flushAppendOnlyFile(0);
e2641e09 797}
798
799/* =========================== Server initialization ======================== */
800
801void createSharedObjects(void) {
802 int j;
803
804 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
805 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
806 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
807 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
808 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
809 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
810 shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n"));
811 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
812 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
813 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
814 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
815 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
816 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
817 "-ERR Operation against a key holding the wrong kind of value\r\n"));
818 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
819 "-ERR no such key\r\n"));
820 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
821 "-ERR syntax error\r\n"));
822 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
823 "-ERR source and destination objects are the same\r\n"));
824 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
825 "-ERR index out of range\r\n"));
7229d60d 826 shared.noscripterr = createObject(REDIS_STRING,sdsnew(
827 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
97e7f8ae 828 shared.loadingerr = createObject(REDIS_STRING,sdsnew(
829 "-LOADING Redis is loading the dataset in memory\r\n"));
115e3ff3 830 shared.slowscripterr = createObject(REDIS_STRING,sdsnew(
4ab8695d 831 "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n"));
e2641e09 832 shared.space = createObject(REDIS_STRING,sdsnew(" "));
833 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
834 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
835 shared.select0 = createStringObject("select 0\r\n",10);
836 shared.select1 = createStringObject("select 1\r\n",10);
837 shared.select2 = createStringObject("select 2\r\n",10);
838 shared.select3 = createStringObject("select 3\r\n",10);
839 shared.select4 = createStringObject("select 4\r\n",10);
840 shared.select5 = createStringObject("select 5\r\n",10);
841 shared.select6 = createStringObject("select 6\r\n",10);
842 shared.select7 = createStringObject("select 7\r\n",10);
843 shared.select8 = createStringObject("select 8\r\n",10);
844 shared.select9 = createStringObject("select 9\r\n",10);
845 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
846 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
847 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
848 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
849 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
850 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
851 shared.mbulk3 = createStringObject("*3\r\n",4);
852 shared.mbulk4 = createStringObject("*4\r\n",4);
853 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
854 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
855 shared.integers[j]->encoding = REDIS_ENCODING_INT;
856 }
857}
858
859void initServerConfig() {
e2641e09 860 server.port = REDIS_SERVERPORT;
a5639e7d 861 server.bindaddr = NULL;
5d10923f 862 server.unixsocket = NULL;
85238765 863 server.unixsocketperm = 0;
a5639e7d
PN
864 server.ipfd = -1;
865 server.sofd = -1;
866 server.dbnum = REDIS_DEFAULT_DBNUM;
c6f9ee88 867 server.verbosity = REDIS_NOTICE;
e2641e09 868 server.maxidletime = REDIS_MAXIDLETIME;
becf5fdb 869 server.client_max_querybuf_len = REDIS_MAX_QUERYBUF_LEN;
e2641e09 870 server.saveparams = NULL;
97e7f8ae 871 server.loading = 0;
e2641e09 872 server.logfile = NULL; /* NULL = log on standard output */
e1a586ee
JH
873 server.syslog_enabled = 0;
874 server.syslog_ident = zstrdup("redis");
875 server.syslog_facility = LOG_LOCAL0;
e2641e09 876 server.daemonize = 0;
e394114d 877 server.aof_state = REDIS_AOF_OFF;
2c915bcf 878 server.aof_fsync = AOF_FSYNC_EVERYSEC;
879 server.aof_no_fsync_on_rewrite = 0;
880 server.aof_rewrite_perc = REDIS_AOF_REWRITE_PERC;
881 server.aof_rewrite_min_size = REDIS_AOF_REWRITE_MIN_SIZE;
882 server.aof_rewrite_base_size = 0;
883 server.aof_rewrite_scheduled = 0;
ff2145ad 884 server.aof_last_fsync = time(NULL);
885 server.aof_fd = -1;
886 server.aof_selected_db = -1; /* Make sure the first time will not match */
db3c2a4f 887 server.aof_flush_postponed_start = 0;
e2641e09 888 server.pidfile = zstrdup("/var/run/redis.pid");
f48cd4b9 889 server.rdb_filename = zstrdup("dump.rdb");
2c915bcf 890 server.aof_filename = zstrdup("appendonly.aof");
e2641e09 891 server.requirepass = NULL;
f48cd4b9 892 server.rdb_compression = 1;
e2641e09 893 server.activerehashing = 1;
58732c23 894 server.maxclients = REDIS_MAX_CLIENTS;
5fa95ad7 895 server.bpop_blocked_clients = 0;
e2641e09 896 server.maxmemory = 0;
165346ca 897 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
898 server.maxmemory_samples = 3;
e2641e09 899 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
900 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
901 server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
902 server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
96ffb2fe 903 server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
3ea204e1
PN
904 server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES;
905 server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE;
e2641e09 906 server.shutdown_asap = 0;
aeecbdfa 907 server.repl_ping_slave_period = REDIS_REPL_PING_SLAVE_PERIOD;
908 server.repl_timeout = REDIS_REPL_TIMEOUT;
ecc91094 909 server.cluster_enabled = 0;
ef21ab96 910 server.cluster.configfile = zstrdup("nodes.conf");
4ab8695d 911 server.lua_caller = NULL;
eeffcf38 912 server.lua_time_limit = REDIS_LUA_TIME_LIMIT;
070e3945 913 server.lua_client = NULL;
115e3ff3 914 server.lua_timedout = 0;
e2641e09 915
95506e46 916 updateLRUClock();
e2641e09 917 resetServerSaveParams();
918
919 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
920 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
921 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
922 /* Replication related */
e2641e09 923 server.masterauth = NULL;
924 server.masterhost = NULL;
925 server.masterport = 6379;
926 server.master = NULL;
1844f990 927 server.repl_state = REDIS_REPL_NONE;
890a2ed9 928 server.repl_syncio_timeout = REDIS_REPL_SYNCIO_TIMEOUT;
4ebfc455 929 server.repl_serve_stale_data = 1;
07486df6 930 server.repl_down_since = -1;
e2641e09 931
7eac2a75 932 /* Client output buffer limits */
933 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].hard_limit_bytes = 0;
934 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].soft_limit_bytes = 0;
935 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].soft_limit_seconds = 0;
936 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].hard_limit_bytes = 0;
937 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].soft_limit_bytes = 1024*1024*256;
938 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].soft_limit_seconds = 60;
939 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].hard_limit_bytes = 1024*1024*256;
940 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].soft_limit_bytes = 1024*1024*32;
941 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].soft_limit_seconds = 60;
942
e2641e09 943 /* Double constants initialization */
944 R_Zero = 0.0;
945 R_PosInf = 1.0/R_Zero;
946 R_NegInf = -1.0/R_Zero;
947 R_Nan = R_Zero/R_Zero;
8d3e063a 948
949 /* Command table -- we intiialize it here as it is part of the
950 * initial configuration, since command names may be changed via
951 * redis.conf using the rename-command directive. */
952 server.commands = dictCreate(&commandTableDictType,NULL);
953 populateCommandTable();
954 server.delCommand = lookupCommandByCString("del");
955 server.multiCommand = lookupCommandByCString("multi");
daa70b17 956
957 /* Slow log */
958 server.slowlog_log_slower_than = REDIS_SLOWLOG_LOG_SLOWER_THAN;
959 server.slowlog_max_len = REDIS_SLOWLOG_MAX_LEN;
fa5af017 960
961 /* Assert */
962 server.assert_failed = "<no assertion failed>";
963 server.assert_file = "<no file>";
964 server.assert_line = 0;
965 server.bug_report_start = 0;
e2641e09 966}
967
e074416b 968/* This function will try to raise the max number of open files accordingly to
969 * the configured max number of clients. It will also account for 32 additional
970 * file descriptors as we need a few more for persistence, listening
971 * sockets, log files and so forth.
972 *
973 * If it will not be possible to set the limit accordingly to the configured
974 * max number of clients, the function will do the reverse setting
975 * server.maxclients to the value that we can actually handle. */
976void adjustOpenFilesLimit(void) {
977 rlim_t maxfiles = server.maxclients+32;
978 struct rlimit limit;
979
980 if (maxfiles < 1024) maxfiles = 1024;
981 if (getrlimit(RLIMIT_NOFILE,&limit) == -1) {
982 redisLog(REDIS_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.",
983 strerror(errno));
984 server.maxclients = 1024-32;
985 } else {
986 rlim_t oldlimit = limit.rlim_cur;
987
988 /* Set the max number of files if the current limit is not enough
989 * for our needs. */
990 if (oldlimit < maxfiles) {
991 limit.rlim_cur = maxfiles;
992 limit.rlim_max = maxfiles;
993 if (setrlimit(RLIMIT_NOFILE,&limit) == -1) {
994 server.maxclients = oldlimit-32;
995 redisLog(REDIS_WARNING,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.",
996 (int) maxfiles, strerror(errno), (int) server.maxclients);
997 } else {
998 redisLog(REDIS_NOTICE,"Max number of open files set to %d",
999 (int) maxfiles);
1000 }
1001 }
1002 }
1003}
1004
e2641e09 1005void initServer() {
1006 int j;
1007
1008 signal(SIGHUP, SIG_IGN);
1009 signal(SIGPIPE, SIG_IGN);
633a9410 1010 setupSignalHandlers();
e2641e09 1011
e1a586ee
JH
1012 if (server.syslog_enabled) {
1013 openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1014 server.syslog_facility);
1015 }
1016
00010fa9 1017 server.current_client = NULL;
e2641e09 1018 server.clients = listCreate();
7eac2a75 1019 server.clients_to_close = listCreate();
e2641e09 1020 server.slaves = listCreate();
1021 server.monitors = listCreate();
a4ce7581 1022 server.unblocked_clients = listCreate();
cea8c5cd 1023
e2641e09 1024 createSharedObjects();
e074416b 1025 adjustOpenFilesLimit();
1026 server.el = aeCreateEventLoop(server.maxclients+1024);
e2641e09 1027 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
68d6345d 1028
a53b4c24 1029 if (server.port != 0) {
68d6345d 1030 server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr);
a53b4c24 1031 if (server.ipfd == ANET_ERR) {
eef17490 1032 redisLog(REDIS_WARNING, "Opening port %d: %s",
1033 server.port, server.neterr);
a53b4c24 1034 exit(1);
1035 }
a5639e7d 1036 }
5d10923f
PN
1037 if (server.unixsocket != NULL) {
1038 unlink(server.unixsocket); /* don't care if this fails */
85238765 1039 server.sofd = anetUnixServer(server.neterr,server.unixsocket,server.unixsocketperm);
a5639e7d
PN
1040 if (server.sofd == ANET_ERR) {
1041 redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
1042 exit(1);
1043 }
c61e6925 1044 }
a5639e7d
PN
1045 if (server.ipfd < 0 && server.sofd < 0) {
1046 redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
e2641e09 1047 exit(1);
1048 }
1049 for (j = 0; j < server.dbnum; j++) {
1050 server.db[j].dict = dictCreate(&dbDictType,NULL);
1051 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
1052 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1053 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
e2641e09 1054 server.db[j].id = j;
1055 }
1056 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1057 server.pubsub_patterns = listCreate();
1058 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1059 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
1060 server.cronloops = 0;
f48cd4b9 1061 server.rdb_child_pid = -1;
ff2145ad 1062 server.aof_child_pid = -1;
1063 server.aof_rewrite_buf = sdsempty();
1064 server.aof_buf = sdsempty();
e2641e09 1065 server.lastsave = time(NULL);
1066 server.dirty = 0;
1067 server.stat_numcommands = 0;
1068 server.stat_numconnections = 0;
1069 server.stat_expiredkeys = 0;
f21779ff 1070 server.stat_evictedkeys = 0;
e2641e09 1071 server.stat_starttime = time(NULL);
53eeeaff 1072 server.stat_keyspace_misses = 0;
1073 server.stat_keyspace_hits = 0;
17b24ff3 1074 server.stat_peak_memory = 0;
615e414c 1075 server.stat_fork_time = 0;
3c95e721 1076 server.stat_rejected_conn = 0;
e2641e09 1077 server.unixtime = time(NULL);
1078 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
a5639e7d 1079 if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
ab17b909 1080 acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
a5639e7d 1081 if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
ab17b909 1082 acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");
e2641e09 1083
e394114d 1084 if (server.aof_state == REDIS_AOF_ON) {
ff2145ad 1085 server.aof_fd = open(server.aof_filename,
e394114d 1086 O_WRONLY|O_APPEND|O_CREAT,0644);
ff2145ad 1087 if (server.aof_fd == -1) {
e2641e09 1088 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1089 strerror(errno));
1090 exit(1);
1091 }
1092 }
1093
ecc91094 1094 if (server.cluster_enabled) clusterInit();
7585836e 1095 scriptingInit();
daa70b17 1096 slowlogInit();
8f61a72f 1097 bioInit();
e2641e09 1098}
1099
1b1f47c9 1100/* Populates the Redis Command Table starting from the hard coded list
1101 * we have on top of redis.c file. */
1102void populateCommandTable(void) {
1103 int j;
d7ed7fd2 1104 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1b1f47c9 1105
1106 for (j = 0; j < numcommands; j++) {
d7ed7fd2 1107 struct redisCommand *c = redisCommandTable+j;
5d02b00f 1108 char *f = c->sflags;
1b1f47c9 1109 int retval;
e2641e09 1110
5d02b00f 1111 while(*f != '\0') {
1112 switch(*f) {
1113 case 'w': c->flags |= REDIS_CMD_WRITE; break;
1114 case 'r': c->flags |= REDIS_CMD_READONLY; break;
1115 case 'm': c->flags |= REDIS_CMD_DENYOOM; break;
1116 case 'a': c->flags |= REDIS_CMD_ADMIN; break;
1117 case 'p': c->flags |= REDIS_CMD_PUBSUB; break;
1118 case 'f': c->flags |= REDIS_CMD_FORCE_REPLICATION; break;
b60ed6e8 1119 case 's': c->flags |= REDIS_CMD_NOSCRIPT; break;
1120 case 'R': c->flags |= REDIS_CMD_RANDOM; break;
5d02b00f 1121 default: redisPanic("Unsupported command flag"); break;
1122 }
1123 f++;
1124 }
1125
1b1f47c9 1126 retval = dictAdd(server.commands, sdsnew(c->name), c);
1127 assert(retval == DICT_OK);
1128 }
e2641e09 1129}
1130
d7ed7fd2 1131void resetCommandTableStats(void) {
1132 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1133 int j;
1134
1135 for (j = 0; j < numcommands; j++) {
1136 struct redisCommand *c = redisCommandTable+j;
1137
1138 c->microseconds = 0;
1139 c->calls = 0;
1140 }
1141}
1142
e2641e09 1143/* ====================== Commands lookup and execution ===================== */
1144
1b1f47c9 1145struct redisCommand *lookupCommand(sds name) {
1146 return dictFetchValue(server.commands, name);
1147}
1148
1149struct redisCommand *lookupCommandByCString(char *s) {
1150 struct redisCommand *cmd;
1151 sds name = sdsnew(s);
1152
1153 cmd = dictFetchValue(server.commands, name);
1154 sdsfree(name);
1155 return cmd;
e2641e09 1156}
1157
1158/* Call() is the core of Redis execution of a command */
09e2d9ee 1159void call(redisClient *c) {
daa70b17 1160 long long dirty, start = ustime(), duration;
e2641e09 1161
1162 dirty = server.dirty;
09e2d9ee 1163 c->cmd->proc(c);
e2641e09 1164 dirty = server.dirty-dirty;
daa70b17 1165 duration = ustime()-start;
09e2d9ee 1166 c->cmd->microseconds += duration;
daa70b17 1167 slowlogPushEntryIfNeeded(c->argv,c->argc,duration);
09e2d9ee 1168 c->cmd->calls++;
e2641e09 1169
e394114d 1170 if (server.aof_state != REDIS_AOF_OFF && dirty > 0)
09e2d9ee 1171 feedAppendOnlyFile(c->cmd,c->db->id,c->argv,c->argc);
6468a6fa 1172 if ((dirty > 0 || c->cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
e2641e09 1173 listLength(server.slaves))
1174 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
1175 if (listLength(server.monitors))
1176 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
1177 server.stat_numcommands++;
1178}
1179
1180/* If this function gets called we already read a whole
1181 * command, argments are in the client argv/argc fields.
1182 * processCommand() execute the command or prepare the
1183 * server for a bulk read from the client.
1184 *
1185 * If 1 is returned the client is still alive and valid and
1186 * and other operations can be performed by the caller. Otherwise
1187 * if 0 is returned the client was destroied (i.e. after QUIT). */
1188int processCommand(redisClient *c) {
941c9fa2
PN
1189 /* The QUIT command is handled separately. Normal command procs will
1190 * go through checking for replication and QUIT will cause trouble
1191 * when FORCE_REPLICATION is enabled and would be implemented in
1192 * a regular command proc. */
e2641e09 1193 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
941c9fa2 1194 addReply(c,shared.ok);
5e78edb3 1195 c->flags |= REDIS_CLOSE_AFTER_REPLY;
cd8788f2 1196 return REDIS_ERR;
e2641e09 1197 }
1198
1199 /* Now lookup the command and check ASAP about trivial error conditions
09e2d9ee 1200 * such as wrong arity, bad command name and so forth. */
2c74a9f9 1201 c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr);
09e2d9ee 1202 if (!c->cmd) {
3ab20376
PN
1203 addReplyErrorFormat(c,"unknown command '%s'",
1204 (char*)c->argv[0]->ptr);
cd8788f2 1205 return REDIS_OK;
09e2d9ee 1206 } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) ||
1207 (c->argc < -c->cmd->arity)) {
3ab20376 1208 addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
09e2d9ee 1209 c->cmd->name);
cd8788f2 1210 return REDIS_OK;
e2641e09 1211 }
e2641e09 1212
1213 /* Check if the user is authenticated */
09e2d9ee 1214 if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand)
1215 {
3ab20376 1216 addReplyError(c,"operation not permitted");
cd8788f2 1217 return REDIS_OK;
e2641e09 1218 }
1219
ecc91094 1220 /* If cluster is enabled, redirect here */
1221 if (server.cluster_enabled &&
09e2d9ee 1222 !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0)) {
ecc91094 1223 int hashslot;
1224
1225 if (server.cluster.state != REDIS_CLUSTER_OK) {
1226 addReplyError(c,"The cluster is down. Check with CLUSTER INFO for more information");
1227 return REDIS_OK;
1228 } else {
eda827f8 1229 int ask;
09e2d9ee 1230 clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,&hashslot,&ask);
ecc91094 1231 if (n == NULL) {
eda827f8 1232 addReplyError(c,"Multi keys request invalid in cluster");
ecc91094 1233 return REDIS_OK;
1234 } else if (n != server.cluster.myself) {
1235 addReplySds(c,sdscatprintf(sdsempty(),
eda827f8 1236 "-%s %d %s:%d\r\n", ask ? "ASK" : "MOVED",
1237 hashslot,n->ip,n->port));
ecc91094 1238 return REDIS_OK;
1239 }
1240 }
1241 }
1242
1dd10ca2 1243 /* Handle the maxmemory directive.
1244 *
1245 * First we try to free some memory if possible (if there are volatile
1246 * keys in the dataset). If there are not the only thing we can do
1247 * is returning an error. */
1248 if (server.maxmemory) freeMemoryIfNeeded();
09e2d9ee 1249 if (server.maxmemory && (c->cmd->flags & REDIS_CMD_DENYOOM) &&
ca734d17 1250 zmalloc_used_memory() > server.maxmemory)
e2641e09 1251 {
3ab20376 1252 addReplyError(c,"command not allowed when used memory > 'maxmemory'");
cd8788f2 1253 return REDIS_OK;
e2641e09 1254 }
1255
1256 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1257 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
1258 &&
09e2d9ee 1259 c->cmd->proc != subscribeCommand &&
1260 c->cmd->proc != unsubscribeCommand &&
1261 c->cmd->proc != psubscribeCommand &&
1262 c->cmd->proc != punsubscribeCommand) {
3ab20376 1263 addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
cd8788f2 1264 return REDIS_OK;
e2641e09 1265 }
1266
4ebfc455 1267 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1268 * we are a slave with a broken link with master. */
1844f990 1269 if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED &&
4ebfc455 1270 server.repl_serve_stale_data == 0 &&
09e2d9ee 1271 c->cmd->proc != infoCommand && c->cmd->proc != slaveofCommand)
4ebfc455 1272 {
1273 addReplyError(c,
1274 "link with MASTER is down and slave-serve-stale-data is set to no");
1275 return REDIS_OK;
1276 }
1277
97e7f8ae 1278 /* Loading DB? Return an error if the command is not INFO */
09e2d9ee 1279 if (server.loading && c->cmd->proc != infoCommand) {
97e7f8ae 1280 addReply(c, shared.loadingerr);
1281 return REDIS_OK;
1282 }
1283
4ab8695d 1284 /* Lua script too slow? Only allow SHUTDOWN NOSAVE and SCRIPT KILL. */
1285 if (server.lua_timedout &&
1286 !(c->cmd->proc != shutdownCommand &&
1287 c->argc == 2 &&
1288 tolower(((char*)c->argv[1]->ptr)[0]) == 'n') &&
1289 !(c->cmd->proc == scriptCommand &&
1290 c->argc == 2 &&
1291 tolower(((char*)c->argv[1]->ptr)[0]) == 'k'))
1292 {
115e3ff3 1293 addReply(c, shared.slowscripterr);
1294 return REDIS_OK;
1295 }
1296
e2641e09 1297 /* Exec the command */
1298 if (c->flags & REDIS_MULTI &&
09e2d9ee 1299 c->cmd->proc != execCommand && c->cmd->proc != discardCommand &&
1300 c->cmd->proc != multiCommand && c->cmd->proc != watchCommand)
e2641e09 1301 {
09e2d9ee 1302 queueMultiCommand(c);
e2641e09 1303 addReply(c,shared.queued);
1304 } else {
09e2d9ee 1305 call(c);
e2641e09 1306 }
cd8788f2 1307 return REDIS_OK;
e2641e09 1308}
1309
1310/*================================== Shutdown =============================== */
1311
4ab8695d 1312int prepareForShutdown(int flags) {
1313 int save = flags & REDIS_SHUTDOWN_SAVE;
1314 int nosave = flags & REDIS_SHUTDOWN_NOSAVE;
1315
adae85cd 1316 redisLog(REDIS_WARNING,"User requested shutdown...");
e2641e09 1317 /* Kill the saving child if there is a background saving in progress.
1318 We want to avoid race conditions, for instance our saving child may
1319 overwrite the synchronous saving did by SHUTDOWN. */
f48cd4b9 1320 if (server.rdb_child_pid != -1) {
adae85cd 1321 redisLog(REDIS_WARNING,"There is a child saving an .rdb. Killing it!");
f48cd4b9 1322 kill(server.rdb_child_pid,SIGKILL);
1323 rdbRemoveTempFile(server.rdb_child_pid);
e2641e09 1324 }
e394114d 1325 if (server.aof_state != REDIS_AOF_OFF) {
adae85cd 1326 /* Kill the AOF saving child as the AOF we already have may be longer
1327 * but contains the full dataset anyway. */
ff2145ad 1328 if (server.aof_child_pid != -1) {
adae85cd 1329 redisLog(REDIS_WARNING,
1330 "There is a child rewriting the AOF. Killing it!");
ff2145ad 1331 kill(server.aof_child_pid,SIGKILL);
adae85cd 1332 }
e2641e09 1333 /* Append only file: fsync() the AOF and exit */
adae85cd 1334 redisLog(REDIS_NOTICE,"Calling fsync() on the AOF file.");
ff2145ad 1335 aof_fsync(server.aof_fd);
adae85cd 1336 }
4ab8695d 1337 if ((server.saveparamslen > 0 && !nosave) || save) {
adae85cd 1338 redisLog(REDIS_NOTICE,"Saving the final RDB snapshot before exiting.");
e2641e09 1339 /* Snapshotting. Perform a SYNC SAVE and exit */
f48cd4b9 1340 if (rdbSave(server.rdb_filename) != REDIS_OK) {
e2641e09 1341 /* Ooops.. error saving! The best we can do is to continue
1342 * operating. Note that if there was a background saving process,
1343 * in the next cron() Redis will be notified that the background
1344 * saving aborted, handling special stuff like slaves pending for
1345 * synchronization... */
adae85cd 1346 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit.");
e2641e09 1347 return REDIS_ERR;
1348 }
1349 }
adae85cd 1350 if (server.daemonize) {
1351 redisLog(REDIS_NOTICE,"Removing the pid file.");
1352 unlink(server.pidfile);
1353 }
80e87a46 1354 /* Close the listening sockets. Apparently this allows faster restarts. */
1355 if (server.ipfd != -1) close(server.ipfd);
1356 if (server.sofd != -1) close(server.sofd);
56209f72
NF
1357 if (server.unixsocket) {
1358 redisLog(REDIS_NOTICE,"Removing the unix socket file.");
1359 unlink(server.unixsocket); /* don't care if this fails */
1360 }
80e87a46 1361
adae85cd 1362 redisLog(REDIS_WARNING,"Redis is now ready to exit, bye bye...");
e2641e09 1363 return REDIS_OK;
1364}
1365
1366/*================================== Commands =============================== */
1367
1368void authCommand(redisClient *c) {
ab52d1f4 1369 if (!server.requirepass) {
1370 addReplyError(c,"Client sent AUTH, but no password is set");
1371 } else if (!strcmp(c->argv[1]->ptr, server.requirepass)) {
e2641e09 1372 c->authenticated = 1;
1373 addReply(c,shared.ok);
1374 } else {
1375 c->authenticated = 0;
3ab20376 1376 addReplyError(c,"invalid password");
e2641e09 1377 }
1378}
1379
1380void pingCommand(redisClient *c) {
1381 addReply(c,shared.pong);
1382}
1383
1384void echoCommand(redisClient *c) {
1385 addReplyBulk(c,c->argv[1]);
1386}
1387
1388/* Convert an amount of bytes into a human readable string in the form
1389 * of 100B, 2G, 100M, 4K, and so forth. */
1390void bytesToHuman(char *s, unsigned long long n) {
1391 double d;
1392
1393 if (n < 1024) {
1394 /* Bytes */
1395 sprintf(s,"%lluB",n);
1396 return;
1397 } else if (n < (1024*1024)) {
1398 d = (double)n/(1024);
1399 sprintf(s,"%.2fK",d);
1400 } else if (n < (1024LL*1024*1024)) {
1401 d = (double)n/(1024*1024);
1402 sprintf(s,"%.2fM",d);
1403 } else if (n < (1024LL*1024*1024*1024)) {
1404 d = (double)n/(1024LL*1024*1024);
1405 sprintf(s,"%.2fG",d);
1406 }
1407}
1408
1409/* Create the string returned by the INFO command. This is decoupled
1410 * by the INFO command itself as we need to report the same information
1411 * on memory corruption problems. */
1b085c9f 1412sds genRedisInfoString(char *section) {
1413 sds info = sdsempty();
e2641e09 1414 time_t uptime = time(NULL)-server.stat_starttime;
d9cb288c 1415 int j, numcommands;
2b00385d 1416 struct rusage self_ru, c_ru;
7a1fd61e 1417 unsigned long lol, bib;
1b085c9f 1418 int allsections = 0, defsections = 0;
1419 int sections = 0;
1420
1421 if (section) {
1422 allsections = strcasecmp(section,"all") == 0;
0d808ef2 1423 defsections = strcasecmp(section,"default") == 0;
1b085c9f 1424 }
2b00385d 1425
1426 getrusage(RUSAGE_SELF, &self_ru);
1427 getrusage(RUSAGE_CHILDREN, &c_ru);
7a1fd61e 1428 getClientsMaxBuffers(&lol,&bib);
1b085c9f 1429
1430 /* Server */
1431 if (allsections || defsections || !strcasecmp(section,"server")) {
1432 if (sections++) info = sdscat(info,"\r\n");
e2641e09 1433 info = sdscatprintf(info,
1b085c9f 1434 "# Server\r\n"
1435 "redis_version:%s\r\n"
1436 "redis_git_sha1:%s\r\n"
1437 "redis_git_dirty:%d\r\n"
1438 "arch_bits:%s\r\n"
1439 "multiplexing_api:%s\r\n"
5db904bd 1440 "gcc_version:%d.%d.%d\r\n"
1b085c9f 1441 "process_id:%ld\r\n"
1442 "tcp_port:%d\r\n"
1443 "uptime_in_seconds:%ld\r\n"
1444 "uptime_in_days:%ld\r\n"
1445 "lru_clock:%ld\r\n",
1446 REDIS_VERSION,
1447 redisGitSHA1(),
1448 strtol(redisGitDirty(),NULL,10) > 0,
1449 (sizeof(long) == 8) ? "64" : "32",
1450 aeGetApiName(),
5db904bd 1451#ifdef __GNUC__
1452 __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__,
1453#else
1454 0,0,0,
1455#endif
1b085c9f 1456 (long) getpid(),
1457 server.port,
1458 uptime,
1459 uptime/(3600*24),
1460 (unsigned long) server.lruclock);
1461 }
1462
1463 /* Clients */
1464 if (allsections || defsections || !strcasecmp(section,"clients")) {
1465 if (sections++) info = sdscat(info,"\r\n");
1466 info = sdscatprintf(info,
1467 "# Clients\r\n"
1468 "connected_clients:%d\r\n"
1469 "client_longest_output_list:%lu\r\n"
1470 "client_biggest_input_buf:%lu\r\n"
1471 "blocked_clients:%d\r\n",
1472 listLength(server.clients)-listLength(server.slaves),
1473 lol, bib,
1474 server.bpop_blocked_clients);
1475 }
1476
1477 /* Memory */
1478 if (allsections || defsections || !strcasecmp(section,"memory")) {
17b24ff3 1479 char hmem[64];
1480 char peak_hmem[64];
1481
1482 bytesToHuman(hmem,zmalloc_used_memory());
1483 bytesToHuman(peak_hmem,server.stat_peak_memory);
1b085c9f 1484 if (sections++) info = sdscat(info,"\r\n");
1485 info = sdscatprintf(info,
1486 "# Memory\r\n"
1487 "used_memory:%zu\r\n"
1488 "used_memory_human:%s\r\n"
1489 "used_memory_rss:%zu\r\n"
17b24ff3 1490 "used_memory_peak:%zu\r\n"
1491 "used_memory_peak_human:%s\r\n"
8c3402df 1492 "used_memory_lua:%lld\r\n"
1b085c9f 1493 "mem_fragmentation_ratio:%.2f\r\n"
32f99c51 1494 "mem_allocator:%s\r\n",
1b085c9f 1495 zmalloc_used_memory(),
1496 hmem,
1497 zmalloc_get_rss(),
17b24ff3 1498 server.stat_peak_memory,
1499 peak_hmem,
8c3402df 1500 ((long long)lua_gc(server.lua,LUA_GCCOUNT,0))*1024LL,
1b085c9f 1501 zmalloc_get_fragmentation_ratio(),
fec5a664 1502 ZMALLOC_LIB
12ebe2ac 1503 );
0d808ef2 1504 }
1505
1b085c9f 1506 /* Persistence */
1507 if (allsections || defsections || !strcasecmp(section,"persistence")) {
1508 if (sections++) info = sdscat(info,"\r\n");
e2641e09 1509 info = sdscatprintf(info,
1b085c9f 1510 "# Persistence\r\n"
1511 "loading:%d\r\n"
1512 "aof_enabled:%d\r\n"
1513 "changes_since_last_save:%lld\r\n"
1514 "bgsave_in_progress:%d\r\n"
1515 "last_save_time:%ld\r\n"
1516 "bgrewriteaof_in_progress:%d\r\n",
1517 server.loading,
e394114d 1518 server.aof_state != REDIS_AOF_OFF,
1b085c9f 1519 server.dirty,
f48cd4b9 1520 server.rdb_child_pid != -1,
1b085c9f 1521 server.lastsave,
ff2145ad 1522 server.aof_child_pid != -1);
1b085c9f 1523
e394114d 1524 if (server.aof_state != REDIS_AOF_OFF) {
d630abcd 1525 info = sdscatprintf(info,
1526 "aof_current_size:%lld\r\n"
1527 "aof_base_size:%lld\r\n"
e7ef418c 1528 "aof_pending_rewrite:%d\r\n"
1529 "aof_buffer_length:%zu\r\n"
1530 "aof_pending_bio_fsync:%llu\r\n",
2c915bcf 1531 (long long) server.aof_current_size,
1532 (long long) server.aof_rewrite_base_size,
1533 server.aof_rewrite_scheduled,
ff2145ad 1534 sdslen(server.aof_buf),
e7ef418c 1535 bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC));
d630abcd 1536 }
1537
1b085c9f 1538 if (server.loading) {
1539 double perc;
1540 time_t eta, elapsed;
1541 off_t remaining_bytes = server.loading_total_bytes-
1542 server.loading_loaded_bytes;
1543
1544 perc = ((double)server.loading_loaded_bytes /
1545 server.loading_total_bytes) * 100;
1546
1547 elapsed = time(NULL)-server.loading_start_time;
1548 if (elapsed == 0) {
1549 eta = 1; /* A fake 1 second figure if we don't have
1550 enough info */
1551 } else {
1552 eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
1553 }
1554
1555 info = sdscatprintf(info,
1556 "loading_start_time:%ld\r\n"
1557 "loading_total_bytes:%llu\r\n"
1558 "loading_loaded_bytes:%llu\r\n"
1559 "loading_loaded_perc:%.2f\r\n"
1560 "loading_eta_seconds:%ld\r\n"
1561 ,(unsigned long) server.loading_start_time,
1562 (unsigned long long) server.loading_total_bytes,
1563 (unsigned long long) server.loading_loaded_bytes,
1564 perc,
1565 eta
1566 );
1567 }
e2641e09 1568 }
1b085c9f 1569
1b085c9f 1570 /* Stats */
1571 if (allsections || defsections || !strcasecmp(section,"stats")) {
1572 if (sections++) info = sdscat(info,"\r\n");
97e7f8ae 1573 info = sdscatprintf(info,
1b085c9f 1574 "# Stats\r\n"
1575 "total_connections_received:%lld\r\n"
1576 "total_commands_processed:%lld\r\n"
3c95e721 1577 "rejected_connections:%lld\r\n"
1b085c9f 1578 "expired_keys:%lld\r\n"
1579 "evicted_keys:%lld\r\n"
1580 "keyspace_hits:%lld\r\n"
1581 "keyspace_misses:%lld\r\n"
1582 "pubsub_channels:%ld\r\n"
615e414c 1583 "pubsub_patterns:%u\r\n"
1584 "latest_fork_usec:%lld\r\n",
1b085c9f 1585 server.stat_numconnections,
1586 server.stat_numcommands,
3c95e721 1587 server.stat_rejected_conn,
1b085c9f 1588 server.stat_expiredkeys,
1589 server.stat_evictedkeys,
1590 server.stat_keyspace_hits,
1591 server.stat_keyspace_misses,
1592 dictSize(server.pubsub_channels),
615e414c 1593 listLength(server.pubsub_patterns),
1594 server.stat_fork_time);
97e7f8ae 1595 }
67a1810b 1596
1b085c9f 1597 /* Replication */
1598 if (allsections || defsections || !strcasecmp(section,"replication")) {
1599 if (sections++) info = sdscat(info,"\r\n");
1600 info = sdscatprintf(info,
1601 "# Replication\r\n"
1602 "role:%s\r\n",
1603 server.masterhost == NULL ? "master" : "slave");
1604 if (server.masterhost) {
1605 info = sdscatprintf(info,
1606 "master_host:%s\r\n"
1607 "master_port:%d\r\n"
1608 "master_link_status:%s\r\n"
1609 "master_last_io_seconds_ago:%d\r\n"
1610 "master_sync_in_progress:%d\r\n"
1611 ,server.masterhost,
1612 server.masterport,
1844f990 1613 (server.repl_state == REDIS_REPL_CONNECTED) ?
1b085c9f 1614 "up" : "down",
1615 server.master ?
1616 ((int)(time(NULL)-server.master->lastinteraction)) : -1,
1844f990 1617 server.repl_state == REDIS_REPL_TRANSFER
1b085c9f 1618 );
1619
1844f990 1620 if (server.repl_state == REDIS_REPL_TRANSFER) {
1b085c9f 1621 info = sdscatprintf(info,
1622 "master_sync_left_bytes:%ld\r\n"
1623 "master_sync_last_io_seconds_ago:%d\r\n"
1624 ,(long)server.repl_transfer_left,
1625 (int)(time(NULL)-server.repl_transfer_lastio)
1626 );
1627 }
07486df6 1628
1844f990 1629 if (server.repl_state != REDIS_REPL_CONNECTED) {
07486df6 1630 info = sdscatprintf(info,
1631 "master_link_down_since_seconds:%ld\r\n",
1632 (long)time(NULL)-server.repl_down_since);
1633 }
67a1810b 1634 }
1b085c9f 1635 info = sdscatprintf(info,
1636 "connected_slaves:%d\r\n",
1637 listLength(server.slaves));
503d87a8 1638 if (listLength(server.slaves)) {
1639 int slaveid = 0;
1640 listNode *ln;
1641 listIter li;
1642
1643 listRewind(server.slaves,&li);
1644 while((ln = listNext(&li))) {
1645 redisClient *slave = listNodeValue(ln);
1646 char *state = NULL;
1647 char ip[32];
1648 int port;
1649
1650 if (anetPeerToString(slave->fd,ip,&port) == -1) continue;
1651 switch(slave->replstate) {
1652 case REDIS_REPL_WAIT_BGSAVE_START:
1653 case REDIS_REPL_WAIT_BGSAVE_END:
1654 state = "wait_bgsave";
1655 break;
1656 case REDIS_REPL_SEND_BULK:
1657 state = "send_bulk";
1658 break;
1659 case REDIS_REPL_ONLINE:
1660 state = "online";
1661 break;
1662 }
1663 if (state == NULL) continue;
1664 info = sdscatprintf(info,"slave%d:%s,%d,%s\r\n",
1665 slaveid,ip,port,state);
1666 slaveid++;
1667 }
1668 }
67a1810b 1669 }
67a1810b 1670
0d808ef2 1671 /* CPU */
1672 if (allsections || defsections || !strcasecmp(section,"cpu")) {
1b085c9f 1673 if (sections++) info = sdscat(info,"\r\n");
1674 info = sdscatprintf(info,
0d808ef2 1675 "# CPU\r\n"
1b085c9f 1676 "used_cpu_sys:%.2f\r\n"
1677 "used_cpu_user:%.2f\r\n"
5a9dd97c 1678 "used_cpu_sys_children:%.2f\r\n"
1679 "used_cpu_user_children:%.2f\r\n",
1b085c9f 1680 (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000,
d83eda48 1681 (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000,
1682 (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000,
1683 (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000);
0d808ef2 1684 }
1b085c9f 1685
0d808ef2 1686 /* cmdtime */
1687 if (allsections || !strcasecmp(section,"commandstats")) {
1688 if (sections++) info = sdscat(info,"\r\n");
1689 info = sdscatprintf(info, "# Commandstats\r\n");
d7ed7fd2 1690 numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1b085c9f 1691 for (j = 0; j < numcommands; j++) {
d7ed7fd2 1692 struct redisCommand *c = redisCommandTable+j;
0d808ef2 1693
d7ed7fd2 1694 if (!c->calls) continue;
1695 info = sdscatprintf(info,
1696 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1697 c->name, c->calls, c->microseconds,
1698 (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls));
1b085c9f 1699 }
d9cb288c 1700 }
1701
1c708b25
SS
1702 /* Clusetr */
1703 if (allsections || defsections || !strcasecmp(section,"cluster")) {
1704 if (sections++) info = sdscat(info,"\r\n");
1705 info = sdscatprintf(info,
1706 "# Cluster\r\n"
1707 "cluster_enabled:%d\r\n",
1708 server.cluster_enabled);
1709 }
1710
1b085c9f 1711 /* Key space */
1712 if (allsections || defsections || !strcasecmp(section,"keyspace")) {
1713 if (sections++) info = sdscat(info,"\r\n");
1714 info = sdscatprintf(info, "# Keyspace\r\n");
1715 for (j = 0; j < server.dbnum; j++) {
1716 long long keys, vkeys;
e2641e09 1717
1b085c9f 1718 keys = dictSize(server.db[j].dict);
1719 vkeys = dictSize(server.db[j].expires);
1720 if (keys || vkeys) {
1721 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
1722 j, keys, vkeys);
1723 }
e2641e09 1724 }
1725 }
1726 return info;
1727}
1728
1729void infoCommand(redisClient *c) {
1b085c9f 1730 char *section = c->argc == 2 ? c->argv[1]->ptr : "default";
1731
1732 if (c->argc > 2) {
1733 addReply(c,shared.syntaxerr);
1734 return;
1735 }
1736 sds info = genRedisInfoString(section);
e2641e09 1737 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
1738 (unsigned long)sdslen(info)));
1739 addReplySds(c,info);
1740 addReply(c,shared.crlf);
1741}
1742
1743void monitorCommand(redisClient *c) {
1744 /* ignore MONITOR if aleady slave or in monitor mode */
1745 if (c->flags & REDIS_SLAVE) return;
1746
1747 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
1748 c->slaveseldb = 0;
1749 listAddNodeTail(server.monitors,c);
1750 addReply(c,shared.ok);
1751}
1752
1753/* ============================ Maxmemory directive ======================== */
1754
e2641e09 1755/* This function gets called when 'maxmemory' is set on the config file to limit
1756 * the max memory used by the server, and we are out of memory.
1757 * This function will try to, in order:
1758 *
1759 * - Free objects from the free list
1760 * - Try to remove keys with an EXPIRE set
1761 *
1762 * It is not possible to free enough memory to reach used-memory < maxmemory
1763 * the server will start refusing commands that will enlarge even more the
1764 * memory usage.
1765 */
1766void freeMemoryIfNeeded(void) {
165346ca 1767 /* Remove keys accordingly to the active policy as long as we are
1768 * over the memory limit. */
5402c426 1769 if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return;
1770
ca734d17 1771 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
e2641e09 1772 int j, k, freed = 0;
1773
165346ca 1774 for (j = 0; j < server.dbnum; j++) {
10c12171 1775 long bestval = 0; /* just to prevent warning */
165346ca 1776 sds bestkey = NULL;
1777 struct dictEntry *de;
1778 redisDb *db = server.db+j;
1779 dict *dict;
1780
1781 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1782 server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
1783 {
1784 dict = server.db[j].dict;
1785 } else {
1786 dict = server.db[j].expires;
1787 }
1788 if (dictSize(dict) == 0) continue;
1789
1790 /* volatile-random and allkeys-random policy */
1791 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
1792 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
1793 {
1794 de = dictGetRandomKey(dict);
c0ba9ebe 1795 bestkey = dictGetKey(de);
165346ca 1796 }
1797
1798 /* volatile-lru and allkeys-lru policy */
1799 else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1800 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1801 {
1802 for (k = 0; k < server.maxmemory_samples; k++) {
1803 sds thiskey;
1804 long thisval;
1805 robj *o;
1806
1807 de = dictGetRandomKey(dict);
c0ba9ebe 1808 thiskey = dictGetKey(de);
0c2f75c6 1809 /* When policy is volatile-lru we need an additonal lookup
1810 * to locate the real key, as dict is set to db->expires. */
1811 if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1812 de = dictFind(db->dict, thiskey);
c0ba9ebe 1813 o = dictGetVal(de);
165346ca 1814 thisval = estimateObjectIdleTime(o);
1815
1816 /* Higher idle time is better candidate for deletion */
1817 if (bestkey == NULL || thisval > bestval) {
1818 bestkey = thiskey;
1819 bestval = thisval;
1820 }
1821 }
1822 }
1823
1824 /* volatile-ttl */
1825 else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
1826 for (k = 0; k < server.maxmemory_samples; k++) {
1827 sds thiskey;
1828 long thisval;
1829
1830 de = dictGetRandomKey(dict);
c0ba9ebe 1831 thiskey = dictGetKey(de);
1832 thisval = (long) dictGetVal(de);
165346ca 1833
1834 /* Expire sooner (minor expire unix timestamp) is better
1835 * candidate for deletion */
1836 if (bestkey == NULL || thisval < bestval) {
1837 bestkey = thiskey;
1838 bestval = thisval;
1839 }
1840 }
1841 }
1842
1843 /* Finally remove the selected key. */
1844 if (bestkey) {
1845 robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
452229b6 1846 propagateExpire(db,keyobj);
165346ca 1847 dbDelete(db,keyobj);
f21779ff 1848 server.stat_evictedkeys++;
165346ca 1849 decrRefCount(keyobj);
1850 freed++;
1851 }
1852 }
1853 if (!freed) return; /* nothing to free... */
1854 }
e2641e09 1855}
1856
1857/* =================================== Main! ================================ */
1858
1859#ifdef __linux__
1860int linuxOvercommitMemoryValue(void) {
1861 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
1862 char buf[64];
1863
1864 if (!fp) return -1;
1865 if (fgets(buf,64,fp) == NULL) {
1866 fclose(fp);
1867 return -1;
1868 }
1869 fclose(fp);
1870
1871 return atoi(buf);
1872}
1873
1874void linuxOvercommitMemoryWarning(void) {
1875 if (linuxOvercommitMemoryValue() == 0) {
1876 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.");
1877 }
1878}
1879#endif /* __linux__ */
1880
695fe874 1881void createPidFile(void) {
1882 /* Try to write the pid file in a best-effort way. */
1883 FILE *fp = fopen(server.pidfile,"w");
1884 if (fp) {
8ce39260 1885 fprintf(fp,"%d\n",(int)getpid());
695fe874 1886 fclose(fp);
1887 }
1888}
1889
e2641e09 1890void daemonize(void) {
1891 int fd;
e2641e09 1892
1893 if (fork() != 0) exit(0); /* parent exits */
1894 setsid(); /* create a new session */
1895
1896 /* Every output goes to /dev/null. If Redis is daemonized but
1897 * the 'logfile' is set to 'stdout' in the configuration file
1898 * it will not log at all. */
1899 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
1900 dup2(fd, STDIN_FILENO);
1901 dup2(fd, STDOUT_FILENO);
1902 dup2(fd, STDERR_FILENO);
1903 if (fd > STDERR_FILENO) close(fd);
1904 }
e2641e09 1905}
1906
1907void version() {
1908 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
1909 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1910 exit(0);
1911}
1912
1913void usage() {
9268a5b5 1914 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n");
e2641e09 1915 fprintf(stderr," ./redis-server - (read config from stdin)\n");
9268a5b5 1916 fprintf(stderr," ./redis-server -v or --version\n");
1917 fprintf(stderr," ./redis-server -h or --help\n\n");
1918 fprintf(stderr,"Examples:\n");
1919 fprintf(stderr," ./redis-server (run the server with default conf)\n");
1920 fprintf(stderr," ./redis-server /etc/redis/6379.conf\n");
1921 fprintf(stderr," ./redis-server --port 7777\n");
1922 fprintf(stderr," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n");
1923 fprintf(stderr," ./redis-server /etc/myredis.conf --loglevel verbose\n");
e2641e09 1924 exit(1);
1925}
1926
996d503d 1927void redisAsciiArt(void) {
1928#include "asciilogo.h"
1929 char *buf = zmalloc(1024*16);
1930
1931 snprintf(buf,1024*16,ascii_logo,
1932 REDIS_VERSION,
1933 redisGitSHA1(),
1934 strtol(redisGitDirty(),NULL,10) > 0,
1935 (sizeof(long) == 8) ? "64" : "32",
1936 server.cluster_enabled ? "cluster" : "stand alone",
1937 server.port,
1938 (long) getpid()
1939 );
1940 redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf);
1941 zfree(buf);
1942}
1943
633a9410 1944static void sigtermHandler(int sig) {
e2641e09 1945 REDIS_NOTUSED(sig);
1946
633a9410 1947 redisLog(REDIS_WARNING,"Received SIGTERM, scheduling shutdown...");
e2641e09 1948 server.shutdown_asap = 1;
1949}
1950
633a9410 1951void setupSignalHandlers(void) {
e2641e09 1952 struct sigaction act;
1953
633a9410
PN
1954 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1955 * Otherwise, sa_handler is used. */
1956 sigemptyset(&act.sa_mask);
e2641e09 1957 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1958 act.sa_handler = sigtermHandler;
633a9410 1959 sigaction(SIGTERM, &act, NULL);
e2641e09 1960
633a9410
PN
1961#ifdef HAVE_BACKTRACE
1962 sigemptyset(&act.sa_mask);
1963 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
1964 act.sa_sigaction = sigsegvHandler;
1965 sigaction(SIGSEGV, &act, NULL);
1966 sigaction(SIGBUS, &act, NULL);
1967 sigaction(SIGFPE, &act, NULL);
1968 sigaction(SIGILL, &act, NULL);
1969#endif
1970 return;
e2641e09 1971}
e2641e09 1972
39ca1713 1973int main(int argc, char **argv) {
1974 long long start;
a48c8d87 1975 struct timeval tv;
39ca1713 1976
06c5523a 1977 /* We need to initialize our libraries, and the server configuration. */
39ca1713 1978 zmalloc_enable_thread_safeness();
a48c8d87 1979 srand(time(NULL)^getpid());
1980 gettimeofday(&tv,NULL);
1981 dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid());
39ca1713 1982 initServerConfig();
a48c8d87 1983
67c6f0f6 1984 if (argc >= 2) {
1985 int j = 1; /* First option to parse in argv[] */
1986 sds options = sdsempty();
1987 char *configfile = NULL;
1988
1989 /* Handle special options --help and --version */
39ca1713 1990 if (strcmp(argv[1], "-v") == 0 ||
1991 strcmp(argv[1], "--version") == 0) version();
4c8bd905 1992 if (strcmp(argv[1], "--help") == 0 ||
1993 strcmp(argv[1], "-h") == 0) usage();
67c6f0f6 1994 /* First argument is the config file name? */
1995 if (argv[j][0] != '-' || argv[j][1] != '-')
1996 configfile = argv[j++];
1997 /* All the other options are parsed and conceptually appended to the
1998 * configuration file. For instance --port 6380 will generate the
1999 * string "port 6380\n" to be parsed after the actual file name
2000 * is parsed, if any. */
2001 while(j != argc) {
2002 if (argv[j][0] == '-' && argv[j][1] == '-') {
2003 /* Option name */
2004 if (sdslen(options)) options = sdscat(options,"\n");
2005 options = sdscat(options,argv[j]+2);
2006 options = sdscat(options," ");
2007 } else {
2008 /* Option argument */
2009 options = sdscatrepr(options,argv[j],strlen(argv[j]));
2010 options = sdscat(options," ");
2011 }
2012 j++;
2013 }
39ca1713 2014 resetServerSaveParams();
67c6f0f6 2015 loadServerConfig(configfile,options);
2016 sdsfree(options);
39ca1713 2017 } else {
2018 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'");
2019 }
2020 if (server.daemonize) daemonize();
2021 initServer();
2022 if (server.daemonize) createPidFile();
2023 redisAsciiArt();
27ccb94a 2024 redisLog(REDIS_WARNING,"Server started, Redis version " REDIS_VERSION);
39ca1713 2025#ifdef __linux__
2026 linuxOvercommitMemoryWarning();
2027#endif
2028 start = ustime();
e394114d 2029 if (server.aof_state == REDIS_AOF_ON) {
2c915bcf 2030 if (loadAppendOnlyFile(server.aof_filename) == REDIS_OK)
39ca1713 2031 redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000);
2032 } else {
f48cd4b9 2033 if (rdbLoad(server.rdb_filename) == REDIS_OK) {
39ca1713 2034 redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds",
2035 (float)(ustime()-start)/1000000);
2036 } else if (errno != ENOENT) {
2037 redisLog(REDIS_WARNING,"Fatal error loading the DB. Exiting.");
2038 exit(1);
2039 }
2040 }
2041 if (server.ipfd > 0)
2042 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
2043 if (server.sofd > 0)
2044 redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
2045 aeSetBeforeSleepProc(server.el,beforeSleep);
2046 aeMain(server.el);
2047 aeDeleteEventLoop(server.el);
2048 return 0;
2049}
2050
e2641e09 2051/* The End */