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