]> git.saurik.com Git - redis.git/blob - src/redis.c
Undo rename of function names where something went wrong
[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.shutdown_asap = 0;
825 server.cache_flush_delay = 0;
826
827 updateLRUClock();
828 resetServerSaveParams();
829
830 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
831 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
832 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
833 /* Replication related */
834 server.isslave = 0;
835 server.masterauth = NULL;
836 server.masterhost = NULL;
837 server.masterport = 6379;
838 server.master = NULL;
839 server.replstate = REDIS_REPL_NONE;
840 server.repl_serve_stale_data = 1;
841
842 /* Double constants initialization */
843 R_Zero = 0.0;
844 R_PosInf = 1.0/R_Zero;
845 R_NegInf = -1.0/R_Zero;
846 R_Nan = R_Zero/R_Zero;
847
848 /* Command table -- we intiialize it here as it is part of the
849 * initial configuration, since command names may be changed via
850 * redis.conf using the rename-command directive. */
851 server.commands = dictCreate(&commandTableDictType,NULL);
852 populateCommandTable();
853 server.delCommand = lookupCommandByCString("del");
854 server.multiCommand = lookupCommandByCString("multi");
855 }
856
857 void initServer() {
858 int j;
859
860 signal(SIGHUP, SIG_IGN);
861 signal(SIGPIPE, SIG_IGN);
862 setupSignalHandlers();
863
864 if (server.syslog_enabled) {
865 openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT,
866 server.syslog_facility);
867 }
868
869 server.mainthread = pthread_self();
870 server.clients = listCreate();
871 server.slaves = listCreate();
872 server.monitors = listCreate();
873 server.unblocked_clients = listCreate();
874 server.cache_io_queue = listCreate();
875
876 createSharedObjects();
877 server.el = aeCreateEventLoop();
878 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
879
880 if (server.port != 0) {
881 server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr);
882 if (server.ipfd == ANET_ERR) {
883 redisLog(REDIS_WARNING, "Opening port: %s", server.neterr);
884 exit(1);
885 }
886 }
887 if (server.unixsocket != NULL) {
888 unlink(server.unixsocket); /* don't care if this fails */
889 server.sofd = anetUnixServer(server.neterr,server.unixsocket);
890 if (server.sofd == ANET_ERR) {
891 redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
892 exit(1);
893 }
894 }
895 if (server.ipfd < 0 && server.sofd < 0) {
896 redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
897 exit(1);
898 }
899 for (j = 0; j < server.dbnum; j++) {
900 server.db[j].dict = dictCreate(&dbDictType,NULL);
901 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
902 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
903 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
904 if (server.ds_enabled) {
905 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
906 server.db[j].io_negcache = dictCreate(&setDictType,NULL);
907 server.db[j].io_queued = dictCreate(&setDictType,NULL);
908 }
909 server.db[j].id = j;
910 }
911 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
912 server.pubsub_patterns = listCreate();
913 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
914 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
915 server.cronloops = 0;
916 server.bgsavechildpid = -1;
917 server.bgrewritechildpid = -1;
918 server.bgsavethread_state = REDIS_BGSAVE_THREAD_UNACTIVE;
919 server.bgsavethread = (pthread_t) -1;
920 server.bgrewritebuf = sdsempty();
921 server.aofbuf = sdsempty();
922 server.lastsave = time(NULL);
923 server.dirty = 0;
924 server.stat_numcommands = 0;
925 server.stat_numconnections = 0;
926 server.stat_expiredkeys = 0;
927 server.stat_evictedkeys = 0;
928 server.stat_starttime = time(NULL);
929 server.stat_keyspace_misses = 0;
930 server.stat_keyspace_hits = 0;
931 server.unixtime = time(NULL);
932 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
933 if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
934 acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
935 if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
936 acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");
937
938 if (server.appendonly) {
939 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
940 if (server.appendfd == -1) {
941 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
942 strerror(errno));
943 exit(1);
944 }
945 }
946
947 if (server.ds_enabled) dsInit();
948 srand(time(NULL)^getpid());
949 }
950
951 /* Populates the Redis Command Table starting from the hard coded list
952 * we have on top of redis.c file. */
953 void populateCommandTable(void) {
954 int j;
955 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
956
957 for (j = 0; j < numcommands; j++) {
958 struct redisCommand *c = redisCommandTable+j;
959 int retval;
960
961 retval = dictAdd(server.commands, sdsnew(c->name), c);
962 assert(retval == DICT_OK);
963 }
964 }
965
966 void resetCommandTableStats(void) {
967 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
968 int j;
969
970 for (j = 0; j < numcommands; j++) {
971 struct redisCommand *c = redisCommandTable+j;
972
973 c->microseconds = 0;
974 c->calls = 0;
975 }
976 }
977
978 /* ====================== Commands lookup and execution ===================== */
979
980 struct redisCommand *lookupCommand(sds name) {
981 return dictFetchValue(server.commands, name);
982 }
983
984 struct redisCommand *lookupCommandByCString(char *s) {
985 struct redisCommand *cmd;
986 sds name = sdsnew(s);
987
988 cmd = dictFetchValue(server.commands, name);
989 sdsfree(name);
990 return cmd;
991 }
992
993 /* Call() is the core of Redis execution of a command */
994 void call(redisClient *c, struct redisCommand *cmd) {
995 long long dirty, start = ustime();
996
997 dirty = server.dirty;
998 cmd->proc(c);
999 dirty = server.dirty-dirty;
1000 cmd->microseconds += ustime()-start;
1001 cmd->calls++;
1002
1003 if (server.appendonly && dirty)
1004 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
1005 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
1006 listLength(server.slaves))
1007 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
1008 if (listLength(server.monitors))
1009 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
1010 server.stat_numcommands++;
1011 }
1012
1013 /* If this function gets called we already read a whole
1014 * command, argments are in the client argv/argc fields.
1015 * processCommand() execute the command or prepare the
1016 * server for a bulk read from the client.
1017 *
1018 * If 1 is returned the client is still alive and valid and
1019 * and other operations can be performed by the caller. Otherwise
1020 * if 0 is returned the client was destroied (i.e. after QUIT). */
1021 int processCommand(redisClient *c) {
1022 struct redisCommand *cmd;
1023
1024 /* The QUIT command is handled separately. Normal command procs will
1025 * go through checking for replication and QUIT will cause trouble
1026 * when FORCE_REPLICATION is enabled and would be implemented in
1027 * a regular command proc. */
1028 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
1029 addReply(c,shared.ok);
1030 c->flags |= REDIS_CLOSE_AFTER_REPLY;
1031 return REDIS_ERR;
1032 }
1033
1034 /* Now lookup the command and check ASAP about trivial error conditions
1035 * such wrong arity, bad command name and so forth. */
1036 cmd = lookupCommand(c->argv[0]->ptr);
1037 if (!cmd) {
1038 addReplyErrorFormat(c,"unknown command '%s'",
1039 (char*)c->argv[0]->ptr);
1040 return REDIS_OK;
1041 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
1042 (c->argc < -cmd->arity)) {
1043 addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
1044 cmd->name);
1045 return REDIS_OK;
1046 }
1047
1048 /* Check if the user is authenticated */
1049 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
1050 addReplyError(c,"operation not permitted");
1051 return REDIS_OK;
1052 }
1053
1054 /* Handle the maxmemory directive.
1055 *
1056 * First we try to free some memory if possible (if there are volatile
1057 * keys in the dataset). If there are not the only thing we can do
1058 * is returning an error. */
1059 if (server.maxmemory) freeMemoryIfNeeded();
1060 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
1061 zmalloc_used_memory() > server.maxmemory)
1062 {
1063 addReplyError(c,"command not allowed when used memory > 'maxmemory'");
1064 return REDIS_OK;
1065 }
1066
1067 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1068 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
1069 &&
1070 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
1071 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
1072 addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1073 return REDIS_OK;
1074 }
1075
1076 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1077 * we are a slave with a broken link with master. */
1078 if (server.masterhost && server.replstate != REDIS_REPL_CONNECTED &&
1079 server.repl_serve_stale_data == 0 &&
1080 cmd->proc != infoCommand && cmd->proc != slaveofCommand)
1081 {
1082 addReplyError(c,
1083 "link with MASTER is down and slave-serve-stale-data is set to no");
1084 return REDIS_OK;
1085 }
1086
1087 /* Loading DB? Return an error if the command is not INFO */
1088 if (server.loading && cmd->proc != infoCommand) {
1089 addReply(c, shared.loadingerr);
1090 return REDIS_OK;
1091 }
1092
1093 /* Exec the command */
1094 if (c->flags & REDIS_MULTI &&
1095 cmd->proc != execCommand && cmd->proc != discardCommand &&
1096 cmd->proc != multiCommand && cmd->proc != watchCommand)
1097 {
1098 queueMultiCommand(c,cmd);
1099 addReply(c,shared.queued);
1100 } else {
1101 if (server.ds_enabled && blockClientOnSwappedKeys(c,cmd))
1102 return REDIS_ERR;
1103 call(c,cmd);
1104 }
1105 return REDIS_OK;
1106 }
1107
1108 /*================================== Shutdown =============================== */
1109
1110 int prepareForShutdown() {
1111 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
1112 /* Kill the saving child if there is a background saving in progress.
1113 We want to avoid race conditions, for instance our saving child may
1114 overwrite the synchronous saving did by SHUTDOWN. */
1115 if (server.bgsavechildpid != -1) {
1116 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
1117 kill(server.bgsavechildpid,SIGKILL);
1118 rdbRemoveTempFile(server.bgsavechildpid);
1119 }
1120 if (server.ds_enabled) {
1121 /* FIXME: flush all objects on disk */
1122 } else if (server.appendonly) {
1123 /* Append only file: fsync() the AOF and exit */
1124 aof_fsync(server.appendfd);
1125 } else if (server.saveparamslen > 0) {
1126 /* Snapshotting. Perform a SYNC SAVE and exit */
1127 if (rdbSave(server.dbfilename) != REDIS_OK) {
1128 /* Ooops.. error saving! The best we can do is to continue
1129 * operating. Note that if there was a background saving process,
1130 * in the next cron() Redis will be notified that the background
1131 * saving aborted, handling special stuff like slaves pending for
1132 * synchronization... */
1133 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
1134 return REDIS_ERR;
1135 }
1136 } else {
1137 redisLog(REDIS_WARNING,"Not saving DB.");
1138 }
1139 if (server.daemonize) unlink(server.pidfile);
1140 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
1141 return REDIS_OK;
1142 }
1143
1144 /*================================== Commands =============================== */
1145
1146 void authCommand(redisClient *c) {
1147 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
1148 c->authenticated = 1;
1149 addReply(c,shared.ok);
1150 } else {
1151 c->authenticated = 0;
1152 addReplyError(c,"invalid password");
1153 }
1154 }
1155
1156 void pingCommand(redisClient *c) {
1157 addReply(c,shared.pong);
1158 }
1159
1160 void echoCommand(redisClient *c) {
1161 addReplyBulk(c,c->argv[1]);
1162 }
1163
1164 /* Convert an amount of bytes into a human readable string in the form
1165 * of 100B, 2G, 100M, 4K, and so forth. */
1166 void bytesToHuman(char *s, unsigned long long n) {
1167 double d;
1168
1169 if (n < 1024) {
1170 /* Bytes */
1171 sprintf(s,"%lluB",n);
1172 return;
1173 } else if (n < (1024*1024)) {
1174 d = (double)n/(1024);
1175 sprintf(s,"%.2fK",d);
1176 } else if (n < (1024LL*1024*1024)) {
1177 d = (double)n/(1024*1024);
1178 sprintf(s,"%.2fM",d);
1179 } else if (n < (1024LL*1024*1024*1024)) {
1180 d = (double)n/(1024LL*1024*1024);
1181 sprintf(s,"%.2fG",d);
1182 }
1183 }
1184
1185 /* Create the string returned by the INFO command. This is decoupled
1186 * by the INFO command itself as we need to report the same information
1187 * on memory corruption problems. */
1188 sds genRedisInfoString(char *section) {
1189 sds info = sdsempty();
1190 time_t uptime = time(NULL)-server.stat_starttime;
1191 int j, numcommands;
1192 char hmem[64];
1193 struct rusage self_ru, c_ru;
1194 unsigned long lol, bib;
1195 int allsections = 0, defsections = 0;
1196 int sections = 0;
1197
1198 if (section) {
1199 allsections = strcasecmp(section,"all") == 0;
1200 defsections = strcasecmp(section,"default") == 0;
1201 }
1202
1203 getrusage(RUSAGE_SELF, &self_ru);
1204 getrusage(RUSAGE_CHILDREN, &c_ru);
1205 getClientsMaxBuffers(&lol,&bib);
1206 bytesToHuman(hmem,zmalloc_used_memory());
1207
1208 /* Server */
1209 if (allsections || defsections || !strcasecmp(section,"server")) {
1210 if (sections++) info = sdscat(info,"\r\n");
1211 info = sdscatprintf(info,
1212 "# Server\r\n"
1213 "redis_version:%s\r\n"
1214 "redis_git_sha1:%s\r\n"
1215 "redis_git_dirty:%d\r\n"
1216 "arch_bits:%s\r\n"
1217 "multiplexing_api:%s\r\n"
1218 "process_id:%ld\r\n"
1219 "tcp_port:%d\r\n"
1220 "uptime_in_seconds:%ld\r\n"
1221 "uptime_in_days:%ld\r\n"
1222 "lru_clock:%ld\r\n",
1223 REDIS_VERSION,
1224 redisGitSHA1(),
1225 strtol(redisGitDirty(),NULL,10) > 0,
1226 (sizeof(long) == 8) ? "64" : "32",
1227 aeGetApiName(),
1228 (long) getpid(),
1229 server.port,
1230 uptime,
1231 uptime/(3600*24),
1232 (unsigned long) server.lruclock);
1233 }
1234
1235 /* Clients */
1236 if (allsections || defsections || !strcasecmp(section,"clients")) {
1237 if (sections++) info = sdscat(info,"\r\n");
1238 info = sdscatprintf(info,
1239 "# Clients\r\n"
1240 "connected_clients:%d\r\n"
1241 "client_longest_output_list:%lu\r\n"
1242 "client_biggest_input_buf:%lu\r\n"
1243 "blocked_clients:%d\r\n",
1244 listLength(server.clients)-listLength(server.slaves),
1245 lol, bib,
1246 server.bpop_blocked_clients);
1247 }
1248
1249 /* Memory */
1250 if (allsections || defsections || !strcasecmp(section,"memory")) {
1251 if (sections++) info = sdscat(info,"\r\n");
1252 info = sdscatprintf(info,
1253 "# Memory\r\n"
1254 "used_memory:%zu\r\n"
1255 "used_memory_human:%s\r\n"
1256 "used_memory_rss:%zu\r\n"
1257 "mem_fragmentation_ratio:%.2f\r\n"
1258 "use_tcmalloc:%d\r\n",
1259 zmalloc_used_memory(),
1260 hmem,
1261 zmalloc_get_rss(),
1262 zmalloc_get_fragmentation_ratio(),
1263 #ifdef USE_TCMALLOC
1264 1
1265 #else
1266 0
1267 #endif
1268 );
1269 }
1270
1271 /* Allocation statistics */
1272 if (allsections || !strcasecmp(section,"allocstats")) {
1273 if (sections++) info = sdscat(info,"\r\n");
1274 info = sdscat(info, "# Allocstats\r\nallocation_stats:");
1275 for (j = 0; j <= ZMALLOC_MAX_ALLOC_STAT; j++) {
1276 size_t count = zmalloc_allocations_for_size(j);
1277 if (count) {
1278 if (info[sdslen(info)-1] != ':') info = sdscatlen(info,",",1);
1279 info = sdscatprintf(info,"%s%d=%zu",
1280 (j == ZMALLOC_MAX_ALLOC_STAT) ? ">=" : "",
1281 j,count);
1282 }
1283 }
1284 info = sdscat(info,"\r\n");
1285 }
1286
1287 /* Persistence */
1288 if (allsections || defsections || !strcasecmp(section,"persistence")) {
1289 if (sections++) info = sdscat(info,"\r\n");
1290 info = sdscatprintf(info,
1291 "# Persistence\r\n"
1292 "loading:%d\r\n"
1293 "aof_enabled:%d\r\n"
1294 "changes_since_last_save:%lld\r\n"
1295 "bgsave_in_progress:%d\r\n"
1296 "last_save_time:%ld\r\n"
1297 "bgrewriteaof_in_progress:%d\r\n",
1298 server.loading,
1299 server.appendonly,
1300 server.dirty,
1301 server.bgsavechildpid != -1 ||
1302 server.bgsavethread != (pthread_t) -1,
1303 server.lastsave,
1304 server.bgrewritechildpid != -1);
1305
1306 if (server.loading) {
1307 double perc;
1308 time_t eta, elapsed;
1309 off_t remaining_bytes = server.loading_total_bytes-
1310 server.loading_loaded_bytes;
1311
1312 perc = ((double)server.loading_loaded_bytes /
1313 server.loading_total_bytes) * 100;
1314
1315 elapsed = time(NULL)-server.loading_start_time;
1316 if (elapsed == 0) {
1317 eta = 1; /* A fake 1 second figure if we don't have
1318 enough info */
1319 } else {
1320 eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
1321 }
1322
1323 info = sdscatprintf(info,
1324 "loading_start_time:%ld\r\n"
1325 "loading_total_bytes:%llu\r\n"
1326 "loading_loaded_bytes:%llu\r\n"
1327 "loading_loaded_perc:%.2f\r\n"
1328 "loading_eta_seconds:%ld\r\n"
1329 ,(unsigned long) server.loading_start_time,
1330 (unsigned long long) server.loading_total_bytes,
1331 (unsigned long long) server.loading_loaded_bytes,
1332 perc,
1333 eta
1334 );
1335 }
1336 }
1337
1338 /* Diskstore */
1339 if (allsections || defsections || !strcasecmp(section,"diskstore")) {
1340 if (sections++) info = sdscat(info,"\r\n");
1341 info = sdscatprintf(info,
1342 "# Diskstore\r\n"
1343 "ds_enabled:%d\r\n",
1344 server.ds_enabled != 0);
1345 if (server.ds_enabled) {
1346 lockThreadedIO();
1347 info = sdscatprintf(info,
1348 "cache_max_memory:%llu\r\n"
1349 "cache_blocked_clients:%lu\r\n"
1350 "cache_io_queue_len:%lu\r\n"
1351 "cache_io_jobs_new:%lu\r\n"
1352 "cache_io_jobs_processing:%lu\r\n"
1353 "cache_io_jobs_processed:%lu\r\n"
1354 "cache_io_ready_clients:%lu\r\n"
1355 ,(unsigned long long) server.cache_max_memory,
1356 (unsigned long) server.cache_blocked_clients,
1357 (unsigned long) listLength(server.cache_io_queue),
1358 (unsigned long) listLength(server.io_newjobs),
1359 (unsigned long) listLength(server.io_processing),
1360 (unsigned long) listLength(server.io_processed),
1361 (unsigned long) listLength(server.io_ready_clients)
1362 );
1363 unlockThreadedIO();
1364 }
1365 }
1366
1367 /* Stats */
1368 if (allsections || defsections || !strcasecmp(section,"stats")) {
1369 if (sections++) info = sdscat(info,"\r\n");
1370 info = sdscatprintf(info,
1371 "# Stats\r\n"
1372 "total_connections_received:%lld\r\n"
1373 "total_commands_processed:%lld\r\n"
1374 "expired_keys:%lld\r\n"
1375 "evicted_keys:%lld\r\n"
1376 "keyspace_hits:%lld\r\n"
1377 "keyspace_misses:%lld\r\n"
1378 "pubsub_channels:%ld\r\n"
1379 "pubsub_patterns:%u\r\n",
1380 server.stat_numconnections,
1381 server.stat_numcommands,
1382 server.stat_expiredkeys,
1383 server.stat_evictedkeys,
1384 server.stat_keyspace_hits,
1385 server.stat_keyspace_misses,
1386 dictSize(server.pubsub_channels),
1387 listLength(server.pubsub_patterns));
1388 }
1389
1390 /* Replication */
1391 if (allsections || defsections || !strcasecmp(section,"replication")) {
1392 if (sections++) info = sdscat(info,"\r\n");
1393 info = sdscatprintf(info,
1394 "# Replication\r\n"
1395 "role:%s\r\n",
1396 server.masterhost == NULL ? "master" : "slave");
1397 if (server.masterhost) {
1398 info = sdscatprintf(info,
1399 "master_host:%s\r\n"
1400 "master_port:%d\r\n"
1401 "master_link_status:%s\r\n"
1402 "master_last_io_seconds_ago:%d\r\n"
1403 "master_sync_in_progress:%d\r\n"
1404 ,server.masterhost,
1405 server.masterport,
1406 (server.replstate == REDIS_REPL_CONNECTED) ?
1407 "up" : "down",
1408 server.master ?
1409 ((int)(time(NULL)-server.master->lastinteraction)) : -1,
1410 server.replstate == REDIS_REPL_TRANSFER
1411 );
1412
1413 if (server.replstate == REDIS_REPL_TRANSFER) {
1414 info = sdscatprintf(info,
1415 "master_sync_left_bytes:%ld\r\n"
1416 "master_sync_last_io_seconds_ago:%d\r\n"
1417 ,(long)server.repl_transfer_left,
1418 (int)(time(NULL)-server.repl_transfer_lastio)
1419 );
1420 }
1421 }
1422 info = sdscatprintf(info,
1423 "connected_slaves:%d\r\n",
1424 listLength(server.slaves));
1425 }
1426
1427 /* CPU */
1428 if (allsections || defsections || !strcasecmp(section,"cpu")) {
1429 if (sections++) info = sdscat(info,"\r\n");
1430 info = sdscatprintf(info,
1431 "# CPU\r\n"
1432 "used_cpu_sys:%.2f\r\n"
1433 "used_cpu_user:%.2f\r\n"
1434 "used_cpu_sys_childrens:%.2f\r\n"
1435 "used_cpu_user_childrens:%.2f\r\n",
1436 (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000,
1437 (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000,
1438 (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000,
1439 (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000);
1440 }
1441
1442 /* cmdtime */
1443 if (allsections || !strcasecmp(section,"commandstats")) {
1444 if (sections++) info = sdscat(info,"\r\n");
1445 info = sdscatprintf(info, "# Commandstats\r\n");
1446 numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1447 for (j = 0; j < numcommands; j++) {
1448 struct redisCommand *c = redisCommandTable+j;
1449
1450 if (!c->calls) continue;
1451 info = sdscatprintf(info,
1452 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1453 c->name, c->calls, c->microseconds,
1454 (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls));
1455 }
1456 }
1457
1458 /* Key space */
1459 if (allsections || defsections || !strcasecmp(section,"keyspace")) {
1460 if (sections++) info = sdscat(info,"\r\n");
1461 info = sdscatprintf(info, "# Keyspace\r\n");
1462 for (j = 0; j < server.dbnum; j++) {
1463 long long keys, vkeys;
1464
1465 keys = dictSize(server.db[j].dict);
1466 vkeys = dictSize(server.db[j].expires);
1467 if (keys || vkeys) {
1468 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
1469 j, keys, vkeys);
1470 }
1471 }
1472 }
1473 return info;
1474 }
1475
1476 void infoCommand(redisClient *c) {
1477 char *section = c->argc == 2 ? c->argv[1]->ptr : "default";
1478
1479 if (c->argc > 2) {
1480 addReply(c,shared.syntaxerr);
1481 return;
1482 }
1483 sds info = genRedisInfoString(section);
1484 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
1485 (unsigned long)sdslen(info)));
1486 addReplySds(c,info);
1487 addReply(c,shared.crlf);
1488 }
1489
1490 void monitorCommand(redisClient *c) {
1491 /* ignore MONITOR if aleady slave or in monitor mode */
1492 if (c->flags & REDIS_SLAVE) return;
1493
1494 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
1495 c->slaveseldb = 0;
1496 listAddNodeTail(server.monitors,c);
1497 addReply(c,shared.ok);
1498 }
1499
1500 /* ============================ Maxmemory directive ======================== */
1501
1502 /* This function gets called when 'maxmemory' is set on the config file to limit
1503 * the max memory used by the server, and we are out of memory.
1504 * This function will try to, in order:
1505 *
1506 * - Free objects from the free list
1507 * - Try to remove keys with an EXPIRE set
1508 *
1509 * It is not possible to free enough memory to reach used-memory < maxmemory
1510 * the server will start refusing commands that will enlarge even more the
1511 * memory usage.
1512 */
1513 void freeMemoryIfNeeded(void) {
1514 /* Remove keys accordingly to the active policy as long as we are
1515 * over the memory limit. */
1516 if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return;
1517
1518 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
1519 int j, k, freed = 0;
1520
1521 for (j = 0; j < server.dbnum; j++) {
1522 long bestval = 0; /* just to prevent warning */
1523 sds bestkey = NULL;
1524 struct dictEntry *de;
1525 redisDb *db = server.db+j;
1526 dict *dict;
1527
1528 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1529 server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
1530 {
1531 dict = server.db[j].dict;
1532 } else {
1533 dict = server.db[j].expires;
1534 }
1535 if (dictSize(dict) == 0) continue;
1536
1537 /* volatile-random and allkeys-random policy */
1538 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
1539 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
1540 {
1541 de = dictGetRandomKey(dict);
1542 bestkey = dictGetEntryKey(de);
1543 }
1544
1545 /* volatile-lru and allkeys-lru policy */
1546 else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1547 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1548 {
1549 for (k = 0; k < server.maxmemory_samples; k++) {
1550 sds thiskey;
1551 long thisval;
1552 robj *o;
1553
1554 de = dictGetRandomKey(dict);
1555 thiskey = dictGetEntryKey(de);
1556 /* When policy is volatile-lru we need an additonal lookup
1557 * to locate the real key, as dict is set to db->expires. */
1558 if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1559 de = dictFind(db->dict, thiskey);
1560 o = dictGetEntryVal(de);
1561 thisval = estimateObjectIdleTime(o);
1562
1563 /* Higher idle time is better candidate for deletion */
1564 if (bestkey == NULL || thisval > bestval) {
1565 bestkey = thiskey;
1566 bestval = thisval;
1567 }
1568 }
1569 }
1570
1571 /* volatile-ttl */
1572 else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
1573 for (k = 0; k < server.maxmemory_samples; k++) {
1574 sds thiskey;
1575 long thisval;
1576
1577 de = dictGetRandomKey(dict);
1578 thiskey = dictGetEntryKey(de);
1579 thisval = (long) dictGetEntryVal(de);
1580
1581 /* Expire sooner (minor expire unix timestamp) is better
1582 * candidate for deletion */
1583 if (bestkey == NULL || thisval < bestval) {
1584 bestkey = thiskey;
1585 bestval = thisval;
1586 }
1587 }
1588 }
1589
1590 /* Finally remove the selected key. */
1591 if (bestkey) {
1592 robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
1593 propagateExpire(db,keyobj);
1594 dbDelete(db,keyobj);
1595 server.stat_evictedkeys++;
1596 decrRefCount(keyobj);
1597 freed++;
1598 }
1599 }
1600 if (!freed) return; /* nothing to free... */
1601 }
1602 }
1603
1604 /* =================================== Main! ================================ */
1605
1606 #ifdef __linux__
1607 int linuxOvercommitMemoryValue(void) {
1608 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
1609 char buf[64];
1610
1611 if (!fp) return -1;
1612 if (fgets(buf,64,fp) == NULL) {
1613 fclose(fp);
1614 return -1;
1615 }
1616 fclose(fp);
1617
1618 return atoi(buf);
1619 }
1620
1621 void linuxOvercommitMemoryWarning(void) {
1622 if (linuxOvercommitMemoryValue() == 0) {
1623 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.");
1624 }
1625 }
1626 #endif /* __linux__ */
1627
1628 void createPidFile(void) {
1629 /* Try to write the pid file in a best-effort way. */
1630 FILE *fp = fopen(server.pidfile,"w");
1631 if (fp) {
1632 fprintf(fp,"%d\n",(int)getpid());
1633 fclose(fp);
1634 }
1635 }
1636
1637 void daemonize(void) {
1638 int fd;
1639
1640 if (fork() != 0) exit(0); /* parent exits */
1641 setsid(); /* create a new session */
1642
1643 /* Every output goes to /dev/null. If Redis is daemonized but
1644 * the 'logfile' is set to 'stdout' in the configuration file
1645 * it will not log at all. */
1646 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
1647 dup2(fd, STDIN_FILENO);
1648 dup2(fd, STDOUT_FILENO);
1649 dup2(fd, STDERR_FILENO);
1650 if (fd > STDERR_FILENO) close(fd);
1651 }
1652 }
1653
1654 void version() {
1655 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
1656 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1657 exit(0);
1658 }
1659
1660 void usage() {
1661 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
1662 fprintf(stderr," ./redis-server - (read config from stdin)\n");
1663 exit(1);
1664 }
1665
1666 int main(int argc, char **argv) {
1667 long long start;
1668
1669 initServerConfig();
1670 if (argc == 2) {
1671 if (strcmp(argv[1], "-v") == 0 ||
1672 strcmp(argv[1], "--version") == 0) version();
1673 if (strcmp(argv[1], "--help") == 0) usage();
1674 resetServerSaveParams();
1675 loadServerConfig(argv[1]);
1676 } else if ((argc > 2)) {
1677 usage();
1678 } else {
1679 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'");
1680 }
1681 if (server.daemonize) daemonize();
1682 initServer();
1683 if (server.daemonize) createPidFile();
1684 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
1685 #ifdef __linux__
1686 linuxOvercommitMemoryWarning();
1687 #endif
1688 start = ustime();
1689 if (server.ds_enabled) {
1690 redisLog(REDIS_NOTICE,"DB not loaded (running with disk back end)");
1691 } else if (server.appendonly) {
1692 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
1693 redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000);
1694 } else {
1695 if (rdbLoad(server.dbfilename) == REDIS_OK)
1696 redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds",(float)(ustime()-start)/1000000);
1697 }
1698 if (server.ipfd > 0)
1699 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
1700 if (server.sofd > 0)
1701 redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
1702 aeSetBeforeSleepProc(server.el,beforeSleep);
1703 aeMain(server.el);
1704 aeDeleteEventLoop(server.el);
1705 return 0;
1706 }
1707
1708 #ifdef HAVE_BACKTRACE
1709 static void *getMcontextEip(ucontext_t *uc) {
1710 #if defined(__FreeBSD__)
1711 return (void*) uc->uc_mcontext.mc_eip;
1712 #elif defined(__dietlibc__)
1713 return (void*) uc->uc_mcontext.eip;
1714 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1715 #if __x86_64__
1716 return (void*) uc->uc_mcontext->__ss.__rip;
1717 #else
1718 return (void*) uc->uc_mcontext->__ss.__eip;
1719 #endif
1720 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1721 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1722 return (void*) uc->uc_mcontext->__ss.__rip;
1723 #else
1724 return (void*) uc->uc_mcontext->__ss.__eip;
1725 #endif
1726 #elif defined(__i386__)
1727 return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
1728 #elif defined(__X86_64__) || defined(__x86_64__)
1729 return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
1730 #elif defined(__ia64__) /* Linux IA64 */
1731 return (void*) uc->uc_mcontext.sc_ip;
1732 #else
1733 return NULL;
1734 #endif
1735 }
1736
1737 static void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
1738 void *trace[100];
1739 char **messages = NULL;
1740 int i, trace_size = 0;
1741 ucontext_t *uc = (ucontext_t*) secret;
1742 sds infostring;
1743 struct sigaction act;
1744 REDIS_NOTUSED(info);
1745
1746 redisLog(REDIS_WARNING,
1747 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
1748 infostring = genRedisInfoString("all");
1749 redisLogRaw(REDIS_WARNING, infostring);
1750 /* It's not safe to sdsfree() the returned string under memory
1751 * corruption conditions. Let it leak as we are going to abort */
1752
1753 trace_size = backtrace(trace, 100);
1754 /* overwrite sigaction with caller's address */
1755 if (getMcontextEip(uc) != NULL) {
1756 trace[1] = getMcontextEip(uc);
1757 }
1758 messages = backtrace_symbols(trace, trace_size);
1759
1760 for (i=1; i<trace_size; ++i)
1761 redisLog(REDIS_WARNING,"%s", messages[i]);
1762
1763 /* free(messages); Don't call free() with possibly corrupted memory. */
1764 if (server.daemonize) unlink(server.pidfile);
1765
1766 /* Make sure we exit with the right signal at the end. So for instance
1767 * the core will be dumped if enabled. */
1768 sigemptyset (&act.sa_mask);
1769 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1770 * is used. Otherwise, sa_handler is used */
1771 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1772 act.sa_handler = SIG_DFL;
1773 sigaction (sig, &act, NULL);
1774 kill(getpid(),sig);
1775 }
1776 #endif /* HAVE_BACKTRACE */
1777
1778 static void sigtermHandler(int sig) {
1779 REDIS_NOTUSED(sig);
1780
1781 redisLog(REDIS_WARNING,"Received SIGTERM, scheduling shutdown...");
1782 server.shutdown_asap = 1;
1783 }
1784
1785 void setupSignalHandlers(void) {
1786 struct sigaction act;
1787
1788 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1789 * Otherwise, sa_handler is used. */
1790 sigemptyset(&act.sa_mask);
1791 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1792 act.sa_handler = sigtermHandler;
1793 sigaction(SIGTERM, &act, NULL);
1794
1795 #ifdef HAVE_BACKTRACE
1796 sigemptyset(&act.sa_mask);
1797 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
1798 act.sa_sigaction = sigsegvHandler;
1799 sigaction(SIGSEGV, &act, NULL);
1800 sigaction(SIGBUS, &act, NULL);
1801 sigaction(SIGFPE, &act, NULL);
1802 sigaction(SIGILL, &act, NULL);
1803 #endif
1804 return;
1805 }
1806
1807 /* The End */