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