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