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