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