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