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