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