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