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