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