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