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