]> git.saurik.com Git - redis.git/blame - src/redis.c
Implementation of the internals that make possible to terminate clients overcoming...
[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
f4aa600b 757 /* Replication cron function -- used to reconnect to master and
758 * to detect transfer failures. */
62ec599c 759 if (!(loops % 10)) replicationCron();
f4aa600b 760
ecc91094 761 /* Run other sub-systems specific cron jobs */
762 if (server.cluster_enabled && !(loops % 10)) clusterCron();
763
89a1433e 764 server.cronloops++;
e2641e09 765 return 100;
766}
767
768/* This function gets called every time Redis is entering the
769 * main loop of the event driven library, that is, before to sleep
770 * for ready file descriptors. */
771void beforeSleep(struct aeEventLoop *eventLoop) {
772 REDIS_NOTUSED(eventLoop);
a4ce7581
PN
773 listNode *ln;
774 redisClient *c;
e2641e09 775
a4ce7581
PN
776 /* Try to process pending commands for clients that were just unblocked. */
777 while (listLength(server.unblocked_clients)) {
778 ln = listFirst(server.unblocked_clients);
779 redisAssert(ln != NULL);
780 c = ln->value;
781 listDelNode(server.unblocked_clients,ln);
3bcffcbe 782 c->flags &= ~REDIS_UNBLOCKED;
a4ce7581
PN
783
784 /* Process remaining data in the input buffer. */
00010fa9 785 if (c->querybuf && sdslen(c->querybuf) > 0) {
786 server.current_client = c;
a4ce7581 787 processInputBuffer(c);
00010fa9 788 server.current_client = NULL;
789 }
a4ce7581
PN
790 }
791
e2641e09 792 /* Write the AOF buffer on disk */
db3c2a4f 793 flushAppendOnlyFile(0);
e2641e09 794}
795
796/* =========================== Server initialization ======================== */
797
798void createSharedObjects(void) {
799 int j;
800
801 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
802 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
803 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
804 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
805 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
806 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
807 shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n"));
808 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
809 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
810 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
811 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
812 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
813 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
814 "-ERR Operation against a key holding the wrong kind of value\r\n"));
815 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
816 "-ERR no such key\r\n"));
817 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
818 "-ERR syntax error\r\n"));
819 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
820 "-ERR source and destination objects are the same\r\n"));
821 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
822 "-ERR index out of range\r\n"));
7229d60d 823 shared.noscripterr = createObject(REDIS_STRING,sdsnew(
824 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
97e7f8ae 825 shared.loadingerr = createObject(REDIS_STRING,sdsnew(
826 "-LOADING Redis is loading the dataset in memory\r\n"));
115e3ff3 827 shared.slowscripterr = createObject(REDIS_STRING,sdsnew(
4ab8695d 828 "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n"));
e2641e09 829 shared.space = createObject(REDIS_STRING,sdsnew(" "));
830 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
831 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
832 shared.select0 = createStringObject("select 0\r\n",10);
833 shared.select1 = createStringObject("select 1\r\n",10);
834 shared.select2 = createStringObject("select 2\r\n",10);
835 shared.select3 = createStringObject("select 3\r\n",10);
836 shared.select4 = createStringObject("select 4\r\n",10);
837 shared.select5 = createStringObject("select 5\r\n",10);
838 shared.select6 = createStringObject("select 6\r\n",10);
839 shared.select7 = createStringObject("select 7\r\n",10);
840 shared.select8 = createStringObject("select 8\r\n",10);
841 shared.select9 = createStringObject("select 9\r\n",10);
842 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
843 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
844 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
845 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
846 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
847 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
848 shared.mbulk3 = createStringObject("*3\r\n",4);
849 shared.mbulk4 = createStringObject("*4\r\n",4);
850 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
851 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
852 shared.integers[j]->encoding = REDIS_ENCODING_INT;
853 }
854}
855
856void initServerConfig() {
e2641e09 857 server.port = REDIS_SERVERPORT;
a5639e7d 858 server.bindaddr = NULL;
5d10923f 859 server.unixsocket = NULL;
85238765 860 server.unixsocketperm = 0;
a5639e7d
PN
861 server.ipfd = -1;
862 server.sofd = -1;
863 server.dbnum = REDIS_DEFAULT_DBNUM;
c6f9ee88 864 server.verbosity = REDIS_NOTICE;
e2641e09 865 server.maxidletime = REDIS_MAXIDLETIME;
becf5fdb 866 server.client_max_querybuf_len = REDIS_MAX_QUERYBUF_LEN;
e2641e09 867 server.saveparams = NULL;
97e7f8ae 868 server.loading = 0;
e2641e09 869 server.logfile = NULL; /* NULL = log on standard output */
e1a586ee
JH
870 server.syslog_enabled = 0;
871 server.syslog_ident = zstrdup("redis");
872 server.syslog_facility = LOG_LOCAL0;
e2641e09 873 server.daemonize = 0;
e394114d 874 server.aof_state = REDIS_AOF_OFF;
2c915bcf 875 server.aof_fsync = AOF_FSYNC_EVERYSEC;
876 server.aof_no_fsync_on_rewrite = 0;
877 server.aof_rewrite_perc = REDIS_AOF_REWRITE_PERC;
878 server.aof_rewrite_min_size = REDIS_AOF_REWRITE_MIN_SIZE;
879 server.aof_rewrite_base_size = 0;
880 server.aof_rewrite_scheduled = 0;
ff2145ad 881 server.aof_last_fsync = time(NULL);
882 server.aof_fd = -1;
883 server.aof_selected_db = -1; /* Make sure the first time will not match */
db3c2a4f 884 server.aof_flush_postponed_start = 0;
e2641e09 885 server.pidfile = zstrdup("/var/run/redis.pid");
f48cd4b9 886 server.rdb_filename = zstrdup("dump.rdb");
2c915bcf 887 server.aof_filename = zstrdup("appendonly.aof");
e2641e09 888 server.requirepass = NULL;
f48cd4b9 889 server.rdb_compression = 1;
e2641e09 890 server.activerehashing = 1;
58732c23 891 server.maxclients = REDIS_MAX_CLIENTS;
5fa95ad7 892 server.bpop_blocked_clients = 0;
e2641e09 893 server.maxmemory = 0;
165346ca 894 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
895 server.maxmemory_samples = 3;
e2641e09 896 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
897 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
898 server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
899 server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
96ffb2fe 900 server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
3ea204e1
PN
901 server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES;
902 server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE;
e2641e09 903 server.shutdown_asap = 0;
aeecbdfa 904 server.repl_ping_slave_period = REDIS_REPL_PING_SLAVE_PERIOD;
905 server.repl_timeout = REDIS_REPL_TIMEOUT;
ecc91094 906 server.cluster_enabled = 0;
ef21ab96 907 server.cluster.configfile = zstrdup("nodes.conf");
4ab8695d 908 server.lua_caller = NULL;
eeffcf38 909 server.lua_time_limit = REDIS_LUA_TIME_LIMIT;
070e3945 910 server.lua_client = NULL;
115e3ff3 911 server.lua_timedout = 0;
e2641e09 912
95506e46 913 updateLRUClock();
e2641e09 914 resetServerSaveParams();
915
916 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
917 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
918 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
919 /* Replication related */
e2641e09 920 server.masterauth = NULL;
921 server.masterhost = NULL;
922 server.masterport = 6379;
923 server.master = NULL;
1844f990 924 server.repl_state = REDIS_REPL_NONE;
890a2ed9 925 server.repl_syncio_timeout = REDIS_REPL_SYNCIO_TIMEOUT;
4ebfc455 926 server.repl_serve_stale_data = 1;
07486df6 927 server.repl_down_since = -1;
e2641e09 928
7eac2a75 929 /* Client output buffer limits */
930 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].hard_limit_bytes = 0;
931 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].soft_limit_bytes = 0;
932 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].soft_limit_seconds = 0;
933 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].hard_limit_bytes = 0;
934 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].soft_limit_bytes = 1024*1024*256;
935 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].soft_limit_seconds = 60;
936 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].hard_limit_bytes = 1024*1024*256;
937 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].soft_limit_bytes = 1024*1024*32;
938 server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].soft_limit_seconds = 60;
939
e2641e09 940 /* Double constants initialization */
941 R_Zero = 0.0;
942 R_PosInf = 1.0/R_Zero;
943 R_NegInf = -1.0/R_Zero;
944 R_Nan = R_Zero/R_Zero;
8d3e063a 945
946 /* Command table -- we intiialize it here as it is part of the
947 * initial configuration, since command names may be changed via
948 * redis.conf using the rename-command directive. */
949 server.commands = dictCreate(&commandTableDictType,NULL);
950 populateCommandTable();
951 server.delCommand = lookupCommandByCString("del");
952 server.multiCommand = lookupCommandByCString("multi");
daa70b17 953
954 /* Slow log */
955 server.slowlog_log_slower_than = REDIS_SLOWLOG_LOG_SLOWER_THAN;
956 server.slowlog_max_len = REDIS_SLOWLOG_MAX_LEN;
fa5af017 957
958 /* Assert */
959 server.assert_failed = "<no assertion failed>";
960 server.assert_file = "<no file>";
961 server.assert_line = 0;
962 server.bug_report_start = 0;
e2641e09 963}
964
e074416b 965/* This function will try to raise the max number of open files accordingly to
966 * the configured max number of clients. It will also account for 32 additional
967 * file descriptors as we need a few more for persistence, listening
968 * sockets, log files and so forth.
969 *
970 * If it will not be possible to set the limit accordingly to the configured
971 * max number of clients, the function will do the reverse setting
972 * server.maxclients to the value that we can actually handle. */
973void adjustOpenFilesLimit(void) {
974 rlim_t maxfiles = server.maxclients+32;
975 struct rlimit limit;
976
977 if (maxfiles < 1024) maxfiles = 1024;
978 if (getrlimit(RLIMIT_NOFILE,&limit) == -1) {
979 redisLog(REDIS_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.",
980 strerror(errno));
981 server.maxclients = 1024-32;
982 } else {
983 rlim_t oldlimit = limit.rlim_cur;
984
985 /* Set the max number of files if the current limit is not enough
986 * for our needs. */
987 if (oldlimit < maxfiles) {
988 limit.rlim_cur = maxfiles;
989 limit.rlim_max = maxfiles;
990 if (setrlimit(RLIMIT_NOFILE,&limit) == -1) {
991 server.maxclients = oldlimit-32;
992 redisLog(REDIS_WARNING,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.",
993 (int) maxfiles, strerror(errno), (int) server.maxclients);
994 } else {
995 redisLog(REDIS_NOTICE,"Max number of open files set to %d",
996 (int) maxfiles);
997 }
998 }
999 }
1000}
1001
e2641e09 1002void initServer() {
1003 int j;
1004
1005 signal(SIGHUP, SIG_IGN);
1006 signal(SIGPIPE, SIG_IGN);
633a9410 1007 setupSignalHandlers();
e2641e09 1008
e1a586ee
JH
1009 if (server.syslog_enabled) {
1010 openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1011 server.syslog_facility);
1012 }
1013
00010fa9 1014 server.current_client = NULL;
e2641e09 1015 server.clients = listCreate();
7eac2a75 1016 server.clients_to_close = listCreate();
e2641e09 1017 server.slaves = listCreate();
1018 server.monitors = listCreate();
a4ce7581 1019 server.unblocked_clients = listCreate();
cea8c5cd 1020
e2641e09 1021 createSharedObjects();
e074416b 1022 adjustOpenFilesLimit();
1023 server.el = aeCreateEventLoop(server.maxclients+1024);
e2641e09 1024 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
68d6345d 1025
a53b4c24 1026 if (server.port != 0) {
68d6345d 1027 server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr);
a53b4c24 1028 if (server.ipfd == ANET_ERR) {
eef17490 1029 redisLog(REDIS_WARNING, "Opening port %d: %s",
1030 server.port, server.neterr);
a53b4c24 1031 exit(1);
1032 }
a5639e7d 1033 }
5d10923f
PN
1034 if (server.unixsocket != NULL) {
1035 unlink(server.unixsocket); /* don't care if this fails */
85238765 1036 server.sofd = anetUnixServer(server.neterr,server.unixsocket,server.unixsocketperm);
a5639e7d
PN
1037 if (server.sofd == ANET_ERR) {
1038 redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
1039 exit(1);
1040 }
c61e6925 1041 }
a5639e7d
PN
1042 if (server.ipfd < 0 && server.sofd < 0) {
1043 redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
e2641e09 1044 exit(1);
1045 }
1046 for (j = 0; j < server.dbnum; j++) {
1047 server.db[j].dict = dictCreate(&dbDictType,NULL);
1048 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
1049 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1050 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
e2641e09 1051 server.db[j].id = j;
1052 }
1053 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1054 server.pubsub_patterns = listCreate();
1055 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1056 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
1057 server.cronloops = 0;
f48cd4b9 1058 server.rdb_child_pid = -1;
ff2145ad 1059 server.aof_child_pid = -1;
1060 server.aof_rewrite_buf = sdsempty();
1061 server.aof_buf = sdsempty();
e2641e09 1062 server.lastsave = time(NULL);
1063 server.dirty = 0;
1064 server.stat_numcommands = 0;
1065 server.stat_numconnections = 0;
1066 server.stat_expiredkeys = 0;
f21779ff 1067 server.stat_evictedkeys = 0;
e2641e09 1068 server.stat_starttime = time(NULL);
53eeeaff 1069 server.stat_keyspace_misses = 0;
1070 server.stat_keyspace_hits = 0;
17b24ff3 1071 server.stat_peak_memory = 0;
615e414c 1072 server.stat_fork_time = 0;
3c95e721 1073 server.stat_rejected_conn = 0;
e2641e09 1074 server.unixtime = time(NULL);
1075 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
a5639e7d 1076 if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
ab17b909 1077 acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
a5639e7d 1078 if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
ab17b909 1079 acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");
e2641e09 1080
e394114d 1081 if (server.aof_state == REDIS_AOF_ON) {
ff2145ad 1082 server.aof_fd = open(server.aof_filename,
e394114d 1083 O_WRONLY|O_APPEND|O_CREAT,0644);
ff2145ad 1084 if (server.aof_fd == -1) {
e2641e09 1085 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1086 strerror(errno));
1087 exit(1);
1088 }
1089 }
1090
ecc91094 1091 if (server.cluster_enabled) clusterInit();
7585836e 1092 scriptingInit();
daa70b17 1093 slowlogInit();
8f61a72f 1094 bioInit();
e2641e09 1095}
1096
1b1f47c9 1097/* Populates the Redis Command Table starting from the hard coded list
1098 * we have on top of redis.c file. */
1099void populateCommandTable(void) {
1100 int j;
d7ed7fd2 1101 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1b1f47c9 1102
1103 for (j = 0; j < numcommands; j++) {
d7ed7fd2 1104 struct redisCommand *c = redisCommandTable+j;
5d02b00f 1105 char *f = c->sflags;
1b1f47c9 1106 int retval;
e2641e09 1107
5d02b00f 1108 while(*f != '\0') {
1109 switch(*f) {
1110 case 'w': c->flags |= REDIS_CMD_WRITE; break;
1111 case 'r': c->flags |= REDIS_CMD_READONLY; break;
1112 case 'm': c->flags |= REDIS_CMD_DENYOOM; break;
1113 case 'a': c->flags |= REDIS_CMD_ADMIN; break;
1114 case 'p': c->flags |= REDIS_CMD_PUBSUB; break;
1115 case 'f': c->flags |= REDIS_CMD_FORCE_REPLICATION; break;
b60ed6e8 1116 case 's': c->flags |= REDIS_CMD_NOSCRIPT; break;
1117 case 'R': c->flags |= REDIS_CMD_RANDOM; break;
5d02b00f 1118 default: redisPanic("Unsupported command flag"); break;
1119 }
1120 f++;
1121 }
1122
1b1f47c9 1123 retval = dictAdd(server.commands, sdsnew(c->name), c);
1124 assert(retval == DICT_OK);
1125 }
e2641e09 1126}
1127
d7ed7fd2 1128void resetCommandTableStats(void) {
1129 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1130 int j;
1131
1132 for (j = 0; j < numcommands; j++) {
1133 struct redisCommand *c = redisCommandTable+j;
1134
1135 c->microseconds = 0;
1136 c->calls = 0;
1137 }
1138}
1139
e2641e09 1140/* ====================== Commands lookup and execution ===================== */
1141
1b1f47c9 1142struct redisCommand *lookupCommand(sds name) {
1143 return dictFetchValue(server.commands, name);
1144}
1145
1146struct redisCommand *lookupCommandByCString(char *s) {
1147 struct redisCommand *cmd;
1148 sds name = sdsnew(s);
1149
1150 cmd = dictFetchValue(server.commands, name);
1151 sdsfree(name);
1152 return cmd;
e2641e09 1153}
1154
1155/* Call() is the core of Redis execution of a command */
09e2d9ee 1156void call(redisClient *c) {
daa70b17 1157 long long dirty, start = ustime(), duration;
e2641e09 1158
1159 dirty = server.dirty;
09e2d9ee 1160 c->cmd->proc(c);
e2641e09 1161 dirty = server.dirty-dirty;
daa70b17 1162 duration = ustime()-start;
09e2d9ee 1163 c->cmd->microseconds += duration;
daa70b17 1164 slowlogPushEntryIfNeeded(c->argv,c->argc,duration);
09e2d9ee 1165 c->cmd->calls++;
e2641e09 1166
e394114d 1167 if (server.aof_state != REDIS_AOF_OFF && dirty > 0)
09e2d9ee 1168 feedAppendOnlyFile(c->cmd,c->db->id,c->argv,c->argc);
6468a6fa 1169 if ((dirty > 0 || c->cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
e2641e09 1170 listLength(server.slaves))
1171 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
1172 if (listLength(server.monitors))
1173 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
1174 server.stat_numcommands++;
1175}
1176
1177/* If this function gets called we already read a whole
1178 * command, argments are in the client argv/argc fields.
1179 * processCommand() execute the command or prepare the
1180 * server for a bulk read from the client.
1181 *
1182 * If 1 is returned the client is still alive and valid and
1183 * and other operations can be performed by the caller. Otherwise
1184 * if 0 is returned the client was destroied (i.e. after QUIT). */
1185int processCommand(redisClient *c) {
941c9fa2
PN
1186 /* The QUIT command is handled separately. Normal command procs will
1187 * go through checking for replication and QUIT will cause trouble
1188 * when FORCE_REPLICATION is enabled and would be implemented in
1189 * a regular command proc. */
e2641e09 1190 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
941c9fa2 1191 addReply(c,shared.ok);
5e78edb3 1192 c->flags |= REDIS_CLOSE_AFTER_REPLY;
cd8788f2 1193 return REDIS_ERR;
e2641e09 1194 }
1195
1196 /* Now lookup the command and check ASAP about trivial error conditions
09e2d9ee 1197 * such as wrong arity, bad command name and so forth. */
2c74a9f9 1198 c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr);
09e2d9ee 1199 if (!c->cmd) {
3ab20376
PN
1200 addReplyErrorFormat(c,"unknown command '%s'",
1201 (char*)c->argv[0]->ptr);
cd8788f2 1202 return REDIS_OK;
09e2d9ee 1203 } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) ||
1204 (c->argc < -c->cmd->arity)) {
3ab20376 1205 addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
09e2d9ee 1206 c->cmd->name);
cd8788f2 1207 return REDIS_OK;
e2641e09 1208 }
e2641e09 1209
1210 /* Check if the user is authenticated */
09e2d9ee 1211 if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand)
1212 {
3ab20376 1213 addReplyError(c,"operation not permitted");
cd8788f2 1214 return REDIS_OK;
e2641e09 1215 }
1216
ecc91094 1217 /* If cluster is enabled, redirect here */
1218 if (server.cluster_enabled &&
09e2d9ee 1219 !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0)) {
ecc91094 1220 int hashslot;
1221
1222 if (server.cluster.state != REDIS_CLUSTER_OK) {
1223 addReplyError(c,"The cluster is down. Check with CLUSTER INFO for more information");
1224 return REDIS_OK;
1225 } else {
eda827f8 1226 int ask;
09e2d9ee 1227 clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,&hashslot,&ask);
ecc91094 1228 if (n == NULL) {
eda827f8 1229 addReplyError(c,"Multi keys request invalid in cluster");
ecc91094 1230 return REDIS_OK;
1231 } else if (n != server.cluster.myself) {
1232 addReplySds(c,sdscatprintf(sdsempty(),
eda827f8 1233 "-%s %d %s:%d\r\n", ask ? "ASK" : "MOVED",
1234 hashslot,n->ip,n->port));
ecc91094 1235 return REDIS_OK;
1236 }
1237 }
1238 }
1239
1dd10ca2 1240 /* Handle the maxmemory directive.
1241 *
1242 * First we try to free some memory if possible (if there are volatile
1243 * keys in the dataset). If there are not the only thing we can do
1244 * is returning an error. */
1245 if (server.maxmemory) freeMemoryIfNeeded();
09e2d9ee 1246 if (server.maxmemory && (c->cmd->flags & REDIS_CMD_DENYOOM) &&
ca734d17 1247 zmalloc_used_memory() > server.maxmemory)
e2641e09 1248 {
3ab20376 1249 addReplyError(c,"command not allowed when used memory > 'maxmemory'");
cd8788f2 1250 return REDIS_OK;
e2641e09 1251 }
1252
1253 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1254 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
1255 &&
09e2d9ee 1256 c->cmd->proc != subscribeCommand &&
1257 c->cmd->proc != unsubscribeCommand &&
1258 c->cmd->proc != psubscribeCommand &&
1259 c->cmd->proc != punsubscribeCommand) {
3ab20376 1260 addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
cd8788f2 1261 return REDIS_OK;
e2641e09 1262 }
1263
4ebfc455 1264 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1265 * we are a slave with a broken link with master. */
1844f990 1266 if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED &&
4ebfc455 1267 server.repl_serve_stale_data == 0 &&
09e2d9ee 1268 c->cmd->proc != infoCommand && c->cmd->proc != slaveofCommand)
4ebfc455 1269 {
1270 addReplyError(c,
1271 "link with MASTER is down and slave-serve-stale-data is set to no");
1272 return REDIS_OK;
1273 }
1274
97e7f8ae 1275 /* Loading DB? Return an error if the command is not INFO */
09e2d9ee 1276 if (server.loading && c->cmd->proc != infoCommand) {
97e7f8ae 1277 addReply(c, shared.loadingerr);
1278 return REDIS_OK;
1279 }
1280
4ab8695d 1281 /* Lua script too slow? Only allow SHUTDOWN NOSAVE and SCRIPT KILL. */
1282 if (server.lua_timedout &&
1283 !(c->cmd->proc != shutdownCommand &&
1284 c->argc == 2 &&
1285 tolower(((char*)c->argv[1]->ptr)[0]) == 'n') &&
1286 !(c->cmd->proc == scriptCommand &&
1287 c->argc == 2 &&
1288 tolower(((char*)c->argv[1]->ptr)[0]) == 'k'))
1289 {
115e3ff3 1290 addReply(c, shared.slowscripterr);
1291 return REDIS_OK;
1292 }
1293
e2641e09 1294 /* Exec the command */
1295 if (c->flags & REDIS_MULTI &&
09e2d9ee 1296 c->cmd->proc != execCommand && c->cmd->proc != discardCommand &&
1297 c->cmd->proc != multiCommand && c->cmd->proc != watchCommand)
e2641e09 1298 {
09e2d9ee 1299 queueMultiCommand(c);
e2641e09 1300 addReply(c,shared.queued);
1301 } else {
09e2d9ee 1302 call(c);
e2641e09 1303 }
cd8788f2 1304 return REDIS_OK;
e2641e09 1305}
1306
1307/*================================== Shutdown =============================== */
1308
4ab8695d 1309int prepareForShutdown(int flags) {
1310 int save = flags & REDIS_SHUTDOWN_SAVE;
1311 int nosave = flags & REDIS_SHUTDOWN_NOSAVE;
1312
adae85cd 1313 redisLog(REDIS_WARNING,"User requested shutdown...");
e2641e09 1314 /* Kill the saving child if there is a background saving in progress.
1315 We want to avoid race conditions, for instance our saving child may
1316 overwrite the synchronous saving did by SHUTDOWN. */
f48cd4b9 1317 if (server.rdb_child_pid != -1) {
adae85cd 1318 redisLog(REDIS_WARNING,"There is a child saving an .rdb. Killing it!");
f48cd4b9 1319 kill(server.rdb_child_pid,SIGKILL);
1320 rdbRemoveTempFile(server.rdb_child_pid);
e2641e09 1321 }
e394114d 1322 if (server.aof_state != REDIS_AOF_OFF) {
adae85cd 1323 /* Kill the AOF saving child as the AOF we already have may be longer
1324 * but contains the full dataset anyway. */
ff2145ad 1325 if (server.aof_child_pid != -1) {
adae85cd 1326 redisLog(REDIS_WARNING,
1327 "There is a child rewriting the AOF. Killing it!");
ff2145ad 1328 kill(server.aof_child_pid,SIGKILL);
adae85cd 1329 }
e2641e09 1330 /* Append only file: fsync() the AOF and exit */
adae85cd 1331 redisLog(REDIS_NOTICE,"Calling fsync() on the AOF file.");
ff2145ad 1332 aof_fsync(server.aof_fd);
adae85cd 1333 }
4ab8695d 1334 if ((server.saveparamslen > 0 && !nosave) || save) {
adae85cd 1335 redisLog(REDIS_NOTICE,"Saving the final RDB snapshot before exiting.");
e2641e09 1336 /* Snapshotting. Perform a SYNC SAVE and exit */
f48cd4b9 1337 if (rdbSave(server.rdb_filename) != REDIS_OK) {
e2641e09 1338 /* Ooops.. error saving! The best we can do is to continue
1339 * operating. Note that if there was a background saving process,
1340 * in the next cron() Redis will be notified that the background
1341 * saving aborted, handling special stuff like slaves pending for
1342 * synchronization... */
adae85cd 1343 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit.");
e2641e09 1344 return REDIS_ERR;
1345 }
1346 }
adae85cd 1347 if (server.daemonize) {
1348 redisLog(REDIS_NOTICE,"Removing the pid file.");
1349 unlink(server.pidfile);
1350 }
80e87a46 1351 /* Close the listening sockets. Apparently this allows faster restarts. */
1352 if (server.ipfd != -1) close(server.ipfd);
1353 if (server.sofd != -1) close(server.sofd);
56209f72
NF
1354 if (server.unixsocket) {
1355 redisLog(REDIS_NOTICE,"Removing the unix socket file.");
1356 unlink(server.unixsocket); /* don't care if this fails */
1357 }
80e87a46 1358
adae85cd 1359 redisLog(REDIS_WARNING,"Redis is now ready to exit, bye bye...");
e2641e09 1360 return REDIS_OK;
1361}
1362
1363/*================================== Commands =============================== */
1364
1365void authCommand(redisClient *c) {
ab52d1f4 1366 if (!server.requirepass) {
1367 addReplyError(c,"Client sent AUTH, but no password is set");
1368 } else if (!strcmp(c->argv[1]->ptr, server.requirepass)) {
e2641e09 1369 c->authenticated = 1;
1370 addReply(c,shared.ok);
1371 } else {
1372 c->authenticated = 0;
3ab20376 1373 addReplyError(c,"invalid password");
e2641e09 1374 }
1375}
1376
1377void pingCommand(redisClient *c) {
1378 addReply(c,shared.pong);
1379}
1380
1381void echoCommand(redisClient *c) {
1382 addReplyBulk(c,c->argv[1]);
1383}
1384
1385/* Convert an amount of bytes into a human readable string in the form
1386 * of 100B, 2G, 100M, 4K, and so forth. */
1387void bytesToHuman(char *s, unsigned long long n) {
1388 double d;
1389
1390 if (n < 1024) {
1391 /* Bytes */
1392 sprintf(s,"%lluB",n);
1393 return;
1394 } else if (n < (1024*1024)) {
1395 d = (double)n/(1024);
1396 sprintf(s,"%.2fK",d);
1397 } else if (n < (1024LL*1024*1024)) {
1398 d = (double)n/(1024*1024);
1399 sprintf(s,"%.2fM",d);
1400 } else if (n < (1024LL*1024*1024*1024)) {
1401 d = (double)n/(1024LL*1024*1024);
1402 sprintf(s,"%.2fG",d);
1403 }
1404}
1405
1406/* Create the string returned by the INFO command. This is decoupled
1407 * by the INFO command itself as we need to report the same information
1408 * on memory corruption problems. */
1b085c9f 1409sds genRedisInfoString(char *section) {
1410 sds info = sdsempty();
e2641e09 1411 time_t uptime = time(NULL)-server.stat_starttime;
d9cb288c 1412 int j, numcommands;
2b00385d 1413 struct rusage self_ru, c_ru;
7a1fd61e 1414 unsigned long lol, bib;
1b085c9f 1415 int allsections = 0, defsections = 0;
1416 int sections = 0;
1417
1418 if (section) {
1419 allsections = strcasecmp(section,"all") == 0;
0d808ef2 1420 defsections = strcasecmp(section,"default") == 0;
1b085c9f 1421 }
2b00385d 1422
1423 getrusage(RUSAGE_SELF, &self_ru);
1424 getrusage(RUSAGE_CHILDREN, &c_ru);
7a1fd61e 1425 getClientsMaxBuffers(&lol,&bib);
1b085c9f 1426
1427 /* Server */
1428 if (allsections || defsections || !strcasecmp(section,"server")) {
1429 if (sections++) info = sdscat(info,"\r\n");
e2641e09 1430 info = sdscatprintf(info,
1b085c9f 1431 "# Server\r\n"
1432 "redis_version:%s\r\n"
1433 "redis_git_sha1:%s\r\n"
1434 "redis_git_dirty:%d\r\n"
1435 "arch_bits:%s\r\n"
1436 "multiplexing_api:%s\r\n"
5db904bd 1437 "gcc_version:%d.%d.%d\r\n"
1b085c9f 1438 "process_id:%ld\r\n"
1439 "tcp_port:%d\r\n"
1440 "uptime_in_seconds:%ld\r\n"
1441 "uptime_in_days:%ld\r\n"
1442 "lru_clock:%ld\r\n",
1443 REDIS_VERSION,
1444 redisGitSHA1(),
1445 strtol(redisGitDirty(),NULL,10) > 0,
1446 (sizeof(long) == 8) ? "64" : "32",
1447 aeGetApiName(),
5db904bd 1448#ifdef __GNUC__
1449 __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__,
1450#else
1451 0,0,0,
1452#endif
1b085c9f 1453 (long) getpid(),
1454 server.port,
1455 uptime,
1456 uptime/(3600*24),
1457 (unsigned long) server.lruclock);
1458 }
1459
1460 /* Clients */
1461 if (allsections || defsections || !strcasecmp(section,"clients")) {
1462 if (sections++) info = sdscat(info,"\r\n");
1463 info = sdscatprintf(info,
1464 "# Clients\r\n"
1465 "connected_clients:%d\r\n"
1466 "client_longest_output_list:%lu\r\n"
1467 "client_biggest_input_buf:%lu\r\n"
1468 "blocked_clients:%d\r\n",
1469 listLength(server.clients)-listLength(server.slaves),
1470 lol, bib,
1471 server.bpop_blocked_clients);
1472 }
1473
1474 /* Memory */
1475 if (allsections || defsections || !strcasecmp(section,"memory")) {
17b24ff3 1476 char hmem[64];
1477 char peak_hmem[64];
1478
1479 bytesToHuman(hmem,zmalloc_used_memory());
1480 bytesToHuman(peak_hmem,server.stat_peak_memory);
1b085c9f 1481 if (sections++) info = sdscat(info,"\r\n");
1482 info = sdscatprintf(info,
1483 "# Memory\r\n"
1484 "used_memory:%zu\r\n"
1485 "used_memory_human:%s\r\n"
1486 "used_memory_rss:%zu\r\n"
17b24ff3 1487 "used_memory_peak:%zu\r\n"
1488 "used_memory_peak_human:%s\r\n"
8c3402df 1489 "used_memory_lua:%lld\r\n"
1b085c9f 1490 "mem_fragmentation_ratio:%.2f\r\n"
32f99c51 1491 "mem_allocator:%s\r\n",
1b085c9f 1492 zmalloc_used_memory(),
1493 hmem,
1494 zmalloc_get_rss(),
17b24ff3 1495 server.stat_peak_memory,
1496 peak_hmem,
8c3402df 1497 ((long long)lua_gc(server.lua,LUA_GCCOUNT,0))*1024LL,
1b085c9f 1498 zmalloc_get_fragmentation_ratio(),
fec5a664 1499 ZMALLOC_LIB
12ebe2ac 1500 );
0d808ef2 1501 }
1502
1b085c9f 1503 /* Persistence */
1504 if (allsections || defsections || !strcasecmp(section,"persistence")) {
1505 if (sections++) info = sdscat(info,"\r\n");
e2641e09 1506 info = sdscatprintf(info,
1b085c9f 1507 "# Persistence\r\n"
1508 "loading:%d\r\n"
1509 "aof_enabled:%d\r\n"
1510 "changes_since_last_save:%lld\r\n"
1511 "bgsave_in_progress:%d\r\n"
1512 "last_save_time:%ld\r\n"
1513 "bgrewriteaof_in_progress:%d\r\n",
1514 server.loading,
e394114d 1515 server.aof_state != REDIS_AOF_OFF,
1b085c9f 1516 server.dirty,
f48cd4b9 1517 server.rdb_child_pid != -1,
1b085c9f 1518 server.lastsave,
ff2145ad 1519 server.aof_child_pid != -1);
1b085c9f 1520
e394114d 1521 if (server.aof_state != REDIS_AOF_OFF) {
d630abcd 1522 info = sdscatprintf(info,
1523 "aof_current_size:%lld\r\n"
1524 "aof_base_size:%lld\r\n"
e7ef418c 1525 "aof_pending_rewrite:%d\r\n"
1526 "aof_buffer_length:%zu\r\n"
1527 "aof_pending_bio_fsync:%llu\r\n",
2c915bcf 1528 (long long) server.aof_current_size,
1529 (long long) server.aof_rewrite_base_size,
1530 server.aof_rewrite_scheduled,
ff2145ad 1531 sdslen(server.aof_buf),
e7ef418c 1532 bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC));
d630abcd 1533 }
1534
1b085c9f 1535 if (server.loading) {
1536 double perc;
1537 time_t eta, elapsed;
1538 off_t remaining_bytes = server.loading_total_bytes-
1539 server.loading_loaded_bytes;
1540
1541 perc = ((double)server.loading_loaded_bytes /
1542 server.loading_total_bytes) * 100;
1543
1544 elapsed = time(NULL)-server.loading_start_time;
1545 if (elapsed == 0) {
1546 eta = 1; /* A fake 1 second figure if we don't have
1547 enough info */
1548 } else {
1549 eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
1550 }
1551
1552 info = sdscatprintf(info,
1553 "loading_start_time:%ld\r\n"
1554 "loading_total_bytes:%llu\r\n"
1555 "loading_loaded_bytes:%llu\r\n"
1556 "loading_loaded_perc:%.2f\r\n"
1557 "loading_eta_seconds:%ld\r\n"
1558 ,(unsigned long) server.loading_start_time,
1559 (unsigned long long) server.loading_total_bytes,
1560 (unsigned long long) server.loading_loaded_bytes,
1561 perc,
1562 eta
1563 );
1564 }
e2641e09 1565 }
1b085c9f 1566
1b085c9f 1567 /* Stats */
1568 if (allsections || defsections || !strcasecmp(section,"stats")) {
1569 if (sections++) info = sdscat(info,"\r\n");
97e7f8ae 1570 info = sdscatprintf(info,
1b085c9f 1571 "# Stats\r\n"
1572 "total_connections_received:%lld\r\n"
1573 "total_commands_processed:%lld\r\n"
3c95e721 1574 "rejected_connections:%lld\r\n"
1b085c9f 1575 "expired_keys:%lld\r\n"
1576 "evicted_keys:%lld\r\n"
1577 "keyspace_hits:%lld\r\n"
1578 "keyspace_misses:%lld\r\n"
1579 "pubsub_channels:%ld\r\n"
615e414c 1580 "pubsub_patterns:%u\r\n"
1581 "latest_fork_usec:%lld\r\n",
1b085c9f 1582 server.stat_numconnections,
1583 server.stat_numcommands,
3c95e721 1584 server.stat_rejected_conn,
1b085c9f 1585 server.stat_expiredkeys,
1586 server.stat_evictedkeys,
1587 server.stat_keyspace_hits,
1588 server.stat_keyspace_misses,
1589 dictSize(server.pubsub_channels),
615e414c 1590 listLength(server.pubsub_patterns),
1591 server.stat_fork_time);
97e7f8ae 1592 }
67a1810b 1593
1b085c9f 1594 /* Replication */
1595 if (allsections || defsections || !strcasecmp(section,"replication")) {
1596 if (sections++) info = sdscat(info,"\r\n");
1597 info = sdscatprintf(info,
1598 "# Replication\r\n"
1599 "role:%s\r\n",
1600 server.masterhost == NULL ? "master" : "slave");
1601 if (server.masterhost) {
1602 info = sdscatprintf(info,
1603 "master_host:%s\r\n"
1604 "master_port:%d\r\n"
1605 "master_link_status:%s\r\n"
1606 "master_last_io_seconds_ago:%d\r\n"
1607 "master_sync_in_progress:%d\r\n"
1608 ,server.masterhost,
1609 server.masterport,
1844f990 1610 (server.repl_state == REDIS_REPL_CONNECTED) ?
1b085c9f 1611 "up" : "down",
1612 server.master ?
1613 ((int)(time(NULL)-server.master->lastinteraction)) : -1,
1844f990 1614 server.repl_state == REDIS_REPL_TRANSFER
1b085c9f 1615 );
1616
1844f990 1617 if (server.repl_state == REDIS_REPL_TRANSFER) {
1b085c9f 1618 info = sdscatprintf(info,
1619 "master_sync_left_bytes:%ld\r\n"
1620 "master_sync_last_io_seconds_ago:%d\r\n"
1621 ,(long)server.repl_transfer_left,
1622 (int)(time(NULL)-server.repl_transfer_lastio)
1623 );
1624 }
07486df6 1625
1844f990 1626 if (server.repl_state != REDIS_REPL_CONNECTED) {
07486df6 1627 info = sdscatprintf(info,
1628 "master_link_down_since_seconds:%ld\r\n",
1629 (long)time(NULL)-server.repl_down_since);
1630 }
67a1810b 1631 }
1b085c9f 1632 info = sdscatprintf(info,
1633 "connected_slaves:%d\r\n",
1634 listLength(server.slaves));
503d87a8 1635 if (listLength(server.slaves)) {
1636 int slaveid = 0;
1637 listNode *ln;
1638 listIter li;
1639
1640 listRewind(server.slaves,&li);
1641 while((ln = listNext(&li))) {
1642 redisClient *slave = listNodeValue(ln);
1643 char *state = NULL;
1644 char ip[32];
1645 int port;
1646
1647 if (anetPeerToString(slave->fd,ip,&port) == -1) continue;
1648 switch(slave->replstate) {
1649 case REDIS_REPL_WAIT_BGSAVE_START:
1650 case REDIS_REPL_WAIT_BGSAVE_END:
1651 state = "wait_bgsave";
1652 break;
1653 case REDIS_REPL_SEND_BULK:
1654 state = "send_bulk";
1655 break;
1656 case REDIS_REPL_ONLINE:
1657 state = "online";
1658 break;
1659 }
1660 if (state == NULL) continue;
1661 info = sdscatprintf(info,"slave%d:%s,%d,%s\r\n",
1662 slaveid,ip,port,state);
1663 slaveid++;
1664 }
1665 }
67a1810b 1666 }
67a1810b 1667
0d808ef2 1668 /* CPU */
1669 if (allsections || defsections || !strcasecmp(section,"cpu")) {
1b085c9f 1670 if (sections++) info = sdscat(info,"\r\n");
1671 info = sdscatprintf(info,
0d808ef2 1672 "# CPU\r\n"
1b085c9f 1673 "used_cpu_sys:%.2f\r\n"
1674 "used_cpu_user:%.2f\r\n"
5a9dd97c 1675 "used_cpu_sys_children:%.2f\r\n"
1676 "used_cpu_user_children:%.2f\r\n",
1b085c9f 1677 (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000,
d83eda48 1678 (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000,
1679 (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000,
1680 (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000);
0d808ef2 1681 }
1b085c9f 1682
0d808ef2 1683 /* cmdtime */
1684 if (allsections || !strcasecmp(section,"commandstats")) {
1685 if (sections++) info = sdscat(info,"\r\n");
1686 info = sdscatprintf(info, "# Commandstats\r\n");
d7ed7fd2 1687 numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1b085c9f 1688 for (j = 0; j < numcommands; j++) {
d7ed7fd2 1689 struct redisCommand *c = redisCommandTable+j;
0d808ef2 1690
d7ed7fd2 1691 if (!c->calls) continue;
1692 info = sdscatprintf(info,
1693 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1694 c->name, c->calls, c->microseconds,
1695 (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls));
1b085c9f 1696 }
d9cb288c 1697 }
1698
1c708b25
SS
1699 /* Clusetr */
1700 if (allsections || defsections || !strcasecmp(section,"cluster")) {
1701 if (sections++) info = sdscat(info,"\r\n");
1702 info = sdscatprintf(info,
1703 "# Cluster\r\n"
1704 "cluster_enabled:%d\r\n",
1705 server.cluster_enabled);
1706 }
1707
1b085c9f 1708 /* Key space */
1709 if (allsections || defsections || !strcasecmp(section,"keyspace")) {
1710 if (sections++) info = sdscat(info,"\r\n");
1711 info = sdscatprintf(info, "# Keyspace\r\n");
1712 for (j = 0; j < server.dbnum; j++) {
1713 long long keys, vkeys;
e2641e09 1714
1b085c9f 1715 keys = dictSize(server.db[j].dict);
1716 vkeys = dictSize(server.db[j].expires);
1717 if (keys || vkeys) {
1718 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
1719 j, keys, vkeys);
1720 }
e2641e09 1721 }
1722 }
1723 return info;
1724}
1725
1726void infoCommand(redisClient *c) {
1b085c9f 1727 char *section = c->argc == 2 ? c->argv[1]->ptr : "default";
1728
1729 if (c->argc > 2) {
1730 addReply(c,shared.syntaxerr);
1731 return;
1732 }
1733 sds info = genRedisInfoString(section);
e2641e09 1734 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
1735 (unsigned long)sdslen(info)));
1736 addReplySds(c,info);
1737 addReply(c,shared.crlf);
1738}
1739
1740void monitorCommand(redisClient *c) {
1741 /* ignore MONITOR if aleady slave or in monitor mode */
1742 if (c->flags & REDIS_SLAVE) return;
1743
1744 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
1745 c->slaveseldb = 0;
1746 listAddNodeTail(server.monitors,c);
1747 addReply(c,shared.ok);
1748}
1749
1750/* ============================ Maxmemory directive ======================== */
1751
e2641e09 1752/* This function gets called when 'maxmemory' is set on the config file to limit
1753 * the max memory used by the server, and we are out of memory.
1754 * This function will try to, in order:
1755 *
1756 * - Free objects from the free list
1757 * - Try to remove keys with an EXPIRE set
1758 *
1759 * It is not possible to free enough memory to reach used-memory < maxmemory
1760 * the server will start refusing commands that will enlarge even more the
1761 * memory usage.
1762 */
1763void freeMemoryIfNeeded(void) {
165346ca 1764 /* Remove keys accordingly to the active policy as long as we are
1765 * over the memory limit. */
5402c426 1766 if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return;
1767
ca734d17 1768 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
e2641e09 1769 int j, k, freed = 0;
1770
165346ca 1771 for (j = 0; j < server.dbnum; j++) {
10c12171 1772 long bestval = 0; /* just to prevent warning */
165346ca 1773 sds bestkey = NULL;
1774 struct dictEntry *de;
1775 redisDb *db = server.db+j;
1776 dict *dict;
1777
1778 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1779 server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
1780 {
1781 dict = server.db[j].dict;
1782 } else {
1783 dict = server.db[j].expires;
1784 }
1785 if (dictSize(dict) == 0) continue;
1786
1787 /* volatile-random and allkeys-random policy */
1788 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
1789 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
1790 {
1791 de = dictGetRandomKey(dict);
c0ba9ebe 1792 bestkey = dictGetKey(de);
165346ca 1793 }
1794
1795 /* volatile-lru and allkeys-lru policy */
1796 else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1797 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1798 {
1799 for (k = 0; k < server.maxmemory_samples; k++) {
1800 sds thiskey;
1801 long thisval;
1802 robj *o;
1803
1804 de = dictGetRandomKey(dict);
c0ba9ebe 1805 thiskey = dictGetKey(de);
0c2f75c6 1806 /* When policy is volatile-lru we need an additonal lookup
1807 * to locate the real key, as dict is set to db->expires. */
1808 if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1809 de = dictFind(db->dict, thiskey);
c0ba9ebe 1810 o = dictGetVal(de);
165346ca 1811 thisval = estimateObjectIdleTime(o);
1812
1813 /* Higher idle time is better candidate for deletion */
1814 if (bestkey == NULL || thisval > bestval) {
1815 bestkey = thiskey;
1816 bestval = thisval;
1817 }
1818 }
1819 }
1820
1821 /* volatile-ttl */
1822 else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
1823 for (k = 0; k < server.maxmemory_samples; k++) {
1824 sds thiskey;
1825 long thisval;
1826
1827 de = dictGetRandomKey(dict);
c0ba9ebe 1828 thiskey = dictGetKey(de);
1829 thisval = (long) dictGetVal(de);
165346ca 1830
1831 /* Expire sooner (minor expire unix timestamp) is better
1832 * candidate for deletion */
1833 if (bestkey == NULL || thisval < bestval) {
1834 bestkey = thiskey;
1835 bestval = thisval;
1836 }
1837 }
1838 }
1839
1840 /* Finally remove the selected key. */
1841 if (bestkey) {
1842 robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
452229b6 1843 propagateExpire(db,keyobj);
165346ca 1844 dbDelete(db,keyobj);
f21779ff 1845 server.stat_evictedkeys++;
165346ca 1846 decrRefCount(keyobj);
1847 freed++;
1848 }
1849 }
1850 if (!freed) return; /* nothing to free... */
1851 }
e2641e09 1852}
1853
1854/* =================================== Main! ================================ */
1855
1856#ifdef __linux__
1857int linuxOvercommitMemoryValue(void) {
1858 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
1859 char buf[64];
1860
1861 if (!fp) return -1;
1862 if (fgets(buf,64,fp) == NULL) {
1863 fclose(fp);
1864 return -1;
1865 }
1866 fclose(fp);
1867
1868 return atoi(buf);
1869}
1870
1871void linuxOvercommitMemoryWarning(void) {
1872 if (linuxOvercommitMemoryValue() == 0) {
1873 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.");
1874 }
1875}
1876#endif /* __linux__ */
1877
695fe874 1878void createPidFile(void) {
1879 /* Try to write the pid file in a best-effort way. */
1880 FILE *fp = fopen(server.pidfile,"w");
1881 if (fp) {
8ce39260 1882 fprintf(fp,"%d\n",(int)getpid());
695fe874 1883 fclose(fp);
1884 }
1885}
1886
e2641e09 1887void daemonize(void) {
1888 int fd;
e2641e09 1889
1890 if (fork() != 0) exit(0); /* parent exits */
1891 setsid(); /* create a new session */
1892
1893 /* Every output goes to /dev/null. If Redis is daemonized but
1894 * the 'logfile' is set to 'stdout' in the configuration file
1895 * it will not log at all. */
1896 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
1897 dup2(fd, STDIN_FILENO);
1898 dup2(fd, STDOUT_FILENO);
1899 dup2(fd, STDERR_FILENO);
1900 if (fd > STDERR_FILENO) close(fd);
1901 }
e2641e09 1902}
1903
1904void version() {
1905 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
1906 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1907 exit(0);
1908}
1909
1910void usage() {
9268a5b5 1911 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n");
e2641e09 1912 fprintf(stderr," ./redis-server - (read config from stdin)\n");
9268a5b5 1913 fprintf(stderr," ./redis-server -v or --version\n");
1914 fprintf(stderr," ./redis-server -h or --help\n\n");
1915 fprintf(stderr,"Examples:\n");
1916 fprintf(stderr," ./redis-server (run the server with default conf)\n");
1917 fprintf(stderr," ./redis-server /etc/redis/6379.conf\n");
1918 fprintf(stderr," ./redis-server --port 7777\n");
1919 fprintf(stderr," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n");
1920 fprintf(stderr," ./redis-server /etc/myredis.conf --loglevel verbose\n");
e2641e09 1921 exit(1);
1922}
1923
996d503d 1924void redisAsciiArt(void) {
1925#include "asciilogo.h"
1926 char *buf = zmalloc(1024*16);
1927
1928 snprintf(buf,1024*16,ascii_logo,
1929 REDIS_VERSION,
1930 redisGitSHA1(),
1931 strtol(redisGitDirty(),NULL,10) > 0,
1932 (sizeof(long) == 8) ? "64" : "32",
1933 server.cluster_enabled ? "cluster" : "stand alone",
1934 server.port,
1935 (long) getpid()
1936 );
1937 redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf);
1938 zfree(buf);
1939}
1940
633a9410 1941static void sigtermHandler(int sig) {
e2641e09 1942 REDIS_NOTUSED(sig);
1943
633a9410 1944 redisLog(REDIS_WARNING,"Received SIGTERM, scheduling shutdown...");
e2641e09 1945 server.shutdown_asap = 1;
1946}
1947
633a9410 1948void setupSignalHandlers(void) {
e2641e09 1949 struct sigaction act;
1950
633a9410
PN
1951 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1952 * Otherwise, sa_handler is used. */
1953 sigemptyset(&act.sa_mask);
e2641e09 1954 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1955 act.sa_handler = sigtermHandler;
633a9410 1956 sigaction(SIGTERM, &act, NULL);
e2641e09 1957
633a9410
PN
1958#ifdef HAVE_BACKTRACE
1959 sigemptyset(&act.sa_mask);
1960 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
1961 act.sa_sigaction = sigsegvHandler;
1962 sigaction(SIGSEGV, &act, NULL);
1963 sigaction(SIGBUS, &act, NULL);
1964 sigaction(SIGFPE, &act, NULL);
1965 sigaction(SIGILL, &act, NULL);
1966#endif
1967 return;
e2641e09 1968}
e2641e09 1969
39ca1713 1970int main(int argc, char **argv) {
1971 long long start;
a48c8d87 1972 struct timeval tv;
39ca1713 1973
06c5523a 1974 /* We need to initialize our libraries, and the server configuration. */
39ca1713 1975 zmalloc_enable_thread_safeness();
a48c8d87 1976 srand(time(NULL)^getpid());
1977 gettimeofday(&tv,NULL);
1978 dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid());
39ca1713 1979 initServerConfig();
a48c8d87 1980
67c6f0f6 1981 if (argc >= 2) {
1982 int j = 1; /* First option to parse in argv[] */
1983 sds options = sdsempty();
1984 char *configfile = NULL;
1985
1986 /* Handle special options --help and --version */
39ca1713 1987 if (strcmp(argv[1], "-v") == 0 ||
1988 strcmp(argv[1], "--version") == 0) version();
4c8bd905 1989 if (strcmp(argv[1], "--help") == 0 ||
1990 strcmp(argv[1], "-h") == 0) usage();
67c6f0f6 1991 /* First argument is the config file name? */
1992 if (argv[j][0] != '-' || argv[j][1] != '-')
1993 configfile = argv[j++];
1994 /* All the other options are parsed and conceptually appended to the
1995 * configuration file. For instance --port 6380 will generate the
1996 * string "port 6380\n" to be parsed after the actual file name
1997 * is parsed, if any. */
1998 while(j != argc) {
1999 if (argv[j][0] == '-' && argv[j][1] == '-') {
2000 /* Option name */
2001 if (sdslen(options)) options = sdscat(options,"\n");
2002 options = sdscat(options,argv[j]+2);
2003 options = sdscat(options," ");
2004 } else {
2005 /* Option argument */
2006 options = sdscatrepr(options,argv[j],strlen(argv[j]));
2007 options = sdscat(options," ");
2008 }
2009 j++;
2010 }
39ca1713 2011 resetServerSaveParams();
67c6f0f6 2012 loadServerConfig(configfile,options);
2013 sdsfree(options);
39ca1713 2014 } else {
2015 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'");
2016 }
2017 if (server.daemonize) daemonize();
2018 initServer();
2019 if (server.daemonize) createPidFile();
2020 redisAsciiArt();
27ccb94a 2021 redisLog(REDIS_WARNING,"Server started, Redis version " REDIS_VERSION);
39ca1713 2022#ifdef __linux__
2023 linuxOvercommitMemoryWarning();
2024#endif
2025 start = ustime();
e394114d 2026 if (server.aof_state == REDIS_AOF_ON) {
2c915bcf 2027 if (loadAppendOnlyFile(server.aof_filename) == REDIS_OK)
39ca1713 2028 redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000);
2029 } else {
f48cd4b9 2030 if (rdbLoad(server.rdb_filename) == REDIS_OK) {
39ca1713 2031 redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds",
2032 (float)(ustime()-start)/1000000);
2033 } else if (errno != ENOENT) {
2034 redisLog(REDIS_WARNING,"Fatal error loading the DB. Exiting.");
2035 exit(1);
2036 }
2037 }
2038 if (server.ipfd > 0)
2039 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
2040 if (server.sofd > 0)
2041 redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
2042 aeSetBeforeSleepProc(server.el,beforeSleep);
2043 aeMain(server.el);
2044 aeDeleteEventLoop(server.el);
2045 return 0;
2046}
2047
e2641e09 2048/* The End */