]> git.saurik.com Git - redis.git/blob - src/redis.c
b19ee89188d9897784f71441346f29ea983a7b65
[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 /* Record the max memory used since the server was started. */
589 if (zmalloc_used_memory() > server.stat_peak_memory)
590 server.stat_peak_memory = zmalloc_used_memory();
591
592 /* We received a SIGTERM, shutting down here in a safe way, as it is
593 * not ok doing so inside the signal handler. */
594 if (server.shutdown_asap) {
595 if (prepareForShutdown() == REDIS_OK) exit(0);
596 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
597 }
598
599 /* Show some info about non-empty databases */
600 for (j = 0; j < server.dbnum; j++) {
601 long long size, used, vkeys;
602
603 size = dictSlots(server.db[j].dict);
604 used = dictSize(server.db[j].dict);
605 vkeys = dictSize(server.db[j].expires);
606 if (!(loops % 50) && (used || vkeys)) {
607 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
608 /* dictPrintStats(server.dict); */
609 }
610 }
611
612 /* We don't want to resize the hash tables while a bacground saving
613 * is in progress: the saving child is created using fork() that is
614 * implemented with a copy-on-write semantic in most modern systems, so
615 * if we resize the HT while there is the saving child at work actually
616 * a lot of memory movements in the parent will cause a lot of pages
617 * copied. */
618 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
619 if (!(loops % 10)) tryResizeHashTables();
620 if (server.activerehashing) incrementallyRehash();
621 }
622
623 /* Show information about connected clients */
624 if (!(loops % 50)) {
625 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
626 listLength(server.clients)-listLength(server.slaves),
627 listLength(server.slaves),
628 zmalloc_used_memory());
629 }
630
631 /* Close connections of timedout clients */
632 if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients)
633 closeTimedoutClients();
634
635 /* Check if a background saving or AOF rewrite in progress terminated. */
636 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
637 int statloc;
638 pid_t pid;
639
640 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
641 int exitcode = WEXITSTATUS(statloc);
642 int bysignal = 0;
643
644 if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);
645
646 if (pid == server.bgsavechildpid) {
647 backgroundSaveDoneHandler(exitcode,bysignal);
648 } else {
649 backgroundRewriteDoneHandler(exitcode,bysignal);
650 }
651 updateDictResizePolicy();
652 }
653 } else if (server.bgsavethread != (pthread_t) -1) {
654 if (server.bgsavethread != (pthread_t) -1) {
655 int state;
656
657 pthread_mutex_lock(&server.bgsavethread_mutex);
658 state = server.bgsavethread_state;
659 pthread_mutex_unlock(&server.bgsavethread_mutex);
660
661 if (state == REDIS_BGSAVE_THREAD_DONE_OK ||
662 state == REDIS_BGSAVE_THREAD_DONE_ERR)
663 {
664 backgroundSaveDoneHandler(
665 (state == REDIS_BGSAVE_THREAD_DONE_OK) ? 0 : 1, 0);
666 }
667 }
668 } else if (!server.ds_enabled) {
669 /* If there is not a background saving in progress check if
670 * we have to save now */
671 time_t now = time(NULL);
672 for (j = 0; j < server.saveparamslen; j++) {
673 struct saveparam *sp = server.saveparams+j;
674
675 if (server.dirty >= sp->changes &&
676 now-server.lastsave > sp->seconds) {
677 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
678 sp->changes, sp->seconds);
679 rdbSaveBackground(server.dbfilename);
680 break;
681 }
682 }
683 }
684
685 /* Expire a few keys per cycle, only if this is a master.
686 * On slaves we wait for DEL operations synthesized by the master
687 * in order to guarantee a strict consistency. */
688 if (server.masterhost == NULL) activeExpireCycle();
689
690 /* Remove a few cached objects from memory if we are over the
691 * configured memory limit */
692 if (server.ds_enabled) cacheCron();
693
694 /* Replication cron function -- used to reconnect to master and
695 * to detect transfer failures. */
696 if (!(loops % 10)) replicationCron();
697
698 /* Run other sub-systems specific cron jobs */
699 if (server.cluster_enabled && !(loops % 10)) clusterCron();
700
701 server.cronloops++;
702 return 100;
703 }
704
705 /* This function gets called every time Redis is entering the
706 * main loop of the event driven library, that is, before to sleep
707 * for ready file descriptors. */
708 void beforeSleep(struct aeEventLoop *eventLoop) {
709 REDIS_NOTUSED(eventLoop);
710 listNode *ln;
711 redisClient *c;
712
713 /* Awake clients that got all the on disk keys they requested */
714 if (server.ds_enabled && listLength(server.io_ready_clients)) {
715 listIter li;
716
717 listRewind(server.io_ready_clients,&li);
718 while((ln = listNext(&li))) {
719 c = ln->value;
720 struct redisCommand *cmd;
721
722 /* Resume the client. */
723 listDelNode(server.io_ready_clients,ln);
724 c->flags &= (~REDIS_IO_WAIT);
725 server.cache_blocked_clients--;
726 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
727 readQueryFromClient, c);
728 cmd = lookupCommand(c->argv[0]->ptr);
729 redisAssert(cmd != NULL);
730 call(c,cmd);
731 resetClient(c);
732 /* There may be more data to process in the input buffer. */
733 if (c->querybuf && sdslen(c->querybuf) > 0)
734 processInputBuffer(c);
735 }
736 }
737
738 /* Try to process pending commands for clients that were just unblocked. */
739 while (listLength(server.unblocked_clients)) {
740 ln = listFirst(server.unblocked_clients);
741 redisAssert(ln != NULL);
742 c = ln->value;
743 listDelNode(server.unblocked_clients,ln);
744 c->flags &= ~REDIS_UNBLOCKED;
745
746 /* Process remaining data in the input buffer. */
747 if (c->querybuf && sdslen(c->querybuf) > 0)
748 processInputBuffer(c);
749 }
750
751 /* Write the AOF buffer on disk */
752 flushAppendOnlyFile();
753 }
754
755 /* =========================== Server initialization ======================== */
756
757 void createSharedObjects(void) {
758 int j;
759
760 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
761 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
762 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
763 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
764 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
765 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
766 shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n"));
767 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
768 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
769 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
770 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
771 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
772 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
773 "-ERR Operation against a key holding the wrong kind of value\r\n"));
774 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
775 "-ERR no such key\r\n"));
776 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
777 "-ERR syntax error\r\n"));
778 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
779 "-ERR source and destination objects are the same\r\n"));
780 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
781 "-ERR index out of range\r\n"));
782 shared.loadingerr = createObject(REDIS_STRING,sdsnew(
783 "-LOADING Redis is loading the dataset in memory\r\n"));
784 shared.space = createObject(REDIS_STRING,sdsnew(" "));
785 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
786 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
787 shared.select0 = createStringObject("select 0\r\n",10);
788 shared.select1 = createStringObject("select 1\r\n",10);
789 shared.select2 = createStringObject("select 2\r\n",10);
790 shared.select3 = createStringObject("select 3\r\n",10);
791 shared.select4 = createStringObject("select 4\r\n",10);
792 shared.select5 = createStringObject("select 5\r\n",10);
793 shared.select6 = createStringObject("select 6\r\n",10);
794 shared.select7 = createStringObject("select 7\r\n",10);
795 shared.select8 = createStringObject("select 8\r\n",10);
796 shared.select9 = createStringObject("select 9\r\n",10);
797 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
798 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
799 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
800 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
801 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
802 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
803 shared.mbulk3 = createStringObject("*3\r\n",4);
804 shared.mbulk4 = createStringObject("*4\r\n",4);
805 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
806 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
807 shared.integers[j]->encoding = REDIS_ENCODING_INT;
808 }
809 }
810
811 void initServerConfig() {
812 server.port = REDIS_SERVERPORT;
813 server.bindaddr = NULL;
814 server.unixsocket = NULL;
815 server.ipfd = -1;
816 server.sofd = -1;
817 server.dbnum = REDIS_DEFAULT_DBNUM;
818 server.verbosity = REDIS_VERBOSE;
819 server.maxidletime = REDIS_MAXIDLETIME;
820 server.saveparams = NULL;
821 server.loading = 0;
822 server.logfile = NULL; /* NULL = log on standard output */
823 server.syslog_enabled = 0;
824 server.syslog_ident = zstrdup("redis");
825 server.syslog_facility = LOG_LOCAL0;
826 server.daemonize = 0;
827 server.appendonly = 0;
828 server.appendfsync = APPENDFSYNC_EVERYSEC;
829 server.no_appendfsync_on_rewrite = 0;
830 server.lastfsync = time(NULL);
831 server.appendfd = -1;
832 server.appendseldb = -1; /* Make sure the first time will not match */
833 server.pidfile = zstrdup("/var/run/redis.pid");
834 server.dbfilename = zstrdup("dump.rdb");
835 server.appendfilename = zstrdup("appendonly.aof");
836 server.requirepass = NULL;
837 server.rdbcompression = 1;
838 server.activerehashing = 1;
839 server.maxclients = 0;
840 server.bpop_blocked_clients = 0;
841 server.maxmemory = 0;
842 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
843 server.maxmemory_samples = 3;
844 server.ds_enabled = 0;
845 server.ds_path = sdsnew("/tmp/redis.ds");
846 server.cache_max_memory = 64LL*1024*1024; /* 64 MB of RAM */
847 server.cache_blocked_clients = 0;
848 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
849 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
850 server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
851 server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
852 server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
853 server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES;
854 server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE;
855 server.shutdown_asap = 0;
856 server.cache_flush_delay = 0;
857 server.cluster_enabled = 0;
858 server.cluster.configfile = zstrdup("nodes.conf");
859
860 updateLRUClock();
861 resetServerSaveParams();
862
863 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
864 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
865 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
866 /* Replication related */
867 server.isslave = 0;
868 server.masterauth = NULL;
869 server.masterhost = NULL;
870 server.masterport = 6379;
871 server.master = NULL;
872 server.replstate = REDIS_REPL_NONE;
873 server.repl_serve_stale_data = 1;
874
875 /* Double constants initialization */
876 R_Zero = 0.0;
877 R_PosInf = 1.0/R_Zero;
878 R_NegInf = -1.0/R_Zero;
879 R_Nan = R_Zero/R_Zero;
880
881 /* Command table -- we intiialize it here as it is part of the
882 * initial configuration, since command names may be changed via
883 * redis.conf using the rename-command directive. */
884 server.commands = dictCreate(&commandTableDictType,NULL);
885 populateCommandTable();
886 server.delCommand = lookupCommandByCString("del");
887 server.multiCommand = lookupCommandByCString("multi");
888 }
889
890 void initServer() {
891 int j;
892
893 signal(SIGHUP, SIG_IGN);
894 signal(SIGPIPE, SIG_IGN);
895 setupSignalHandlers();
896
897 if (server.syslog_enabled) {
898 openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT,
899 server.syslog_facility);
900 }
901
902 server.mainthread = pthread_self();
903 server.clients = listCreate();
904 server.slaves = listCreate();
905 server.monitors = listCreate();
906 server.unblocked_clients = listCreate();
907 server.cache_io_queue = listCreate();
908
909 createSharedObjects();
910 server.el = aeCreateEventLoop();
911 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
912
913 if (server.port != 0) {
914 server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr);
915 if (server.ipfd == ANET_ERR) {
916 redisLog(REDIS_WARNING, "Opening port: %s", server.neterr);
917 exit(1);
918 }
919 }
920 if (server.unixsocket != NULL) {
921 unlink(server.unixsocket); /* don't care if this fails */
922 server.sofd = anetUnixServer(server.neterr,server.unixsocket);
923 if (server.sofd == ANET_ERR) {
924 redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
925 exit(1);
926 }
927 }
928 if (server.ipfd < 0 && server.sofd < 0) {
929 redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
930 exit(1);
931 }
932 for (j = 0; j < server.dbnum; j++) {
933 server.db[j].dict = dictCreate(&dbDictType,NULL);
934 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
935 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
936 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
937 if (server.ds_enabled) {
938 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
939 server.db[j].io_negcache = dictCreate(&setDictType,NULL);
940 server.db[j].io_queued = dictCreate(&setDictType,NULL);
941 }
942 server.db[j].id = j;
943 }
944 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
945 server.pubsub_patterns = listCreate();
946 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
947 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
948 server.cronloops = 0;
949 server.bgsavechildpid = -1;
950 server.bgrewritechildpid = -1;
951 server.bgsavethread_state = REDIS_BGSAVE_THREAD_UNACTIVE;
952 server.bgsavethread = (pthread_t) -1;
953 server.bgrewritebuf = sdsempty();
954 server.aofbuf = sdsempty();
955 server.lastsave = time(NULL);
956 server.dirty = 0;
957 server.stat_numcommands = 0;
958 server.stat_numconnections = 0;
959 server.stat_expiredkeys = 0;
960 server.stat_evictedkeys = 0;
961 server.stat_starttime = time(NULL);
962 server.stat_keyspace_misses = 0;
963 server.stat_keyspace_hits = 0;
964 server.stat_peak_memory = 0;
965 server.unixtime = time(NULL);
966 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
967 if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
968 acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
969 if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
970 acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");
971
972 if (server.appendonly) {
973 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
974 if (server.appendfd == -1) {
975 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
976 strerror(errno));
977 exit(1);
978 }
979 }
980
981 if (server.ds_enabled) dsInit();
982 if (server.cluster_enabled) clusterInit();
983 srand(time(NULL)^getpid());
984 }
985
986 /* Populates the Redis Command Table starting from the hard coded list
987 * we have on top of redis.c file. */
988 void populateCommandTable(void) {
989 int j;
990 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
991
992 for (j = 0; j < numcommands; j++) {
993 struct redisCommand *c = redisCommandTable+j;
994 int retval;
995
996 retval = dictAdd(server.commands, sdsnew(c->name), c);
997 assert(retval == DICT_OK);
998 }
999 }
1000
1001 void resetCommandTableStats(void) {
1002 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1003 int j;
1004
1005 for (j = 0; j < numcommands; j++) {
1006 struct redisCommand *c = redisCommandTable+j;
1007
1008 c->microseconds = 0;
1009 c->calls = 0;
1010 }
1011 }
1012
1013 /* ====================== Commands lookup and execution ===================== */
1014
1015 struct redisCommand *lookupCommand(sds name) {
1016 return dictFetchValue(server.commands, name);
1017 }
1018
1019 struct redisCommand *lookupCommandByCString(char *s) {
1020 struct redisCommand *cmd;
1021 sds name = sdsnew(s);
1022
1023 cmd = dictFetchValue(server.commands, name);
1024 sdsfree(name);
1025 return cmd;
1026 }
1027
1028 /* Call() is the core of Redis execution of a command */
1029 void call(redisClient *c, struct redisCommand *cmd) {
1030 long long dirty, start = ustime();
1031
1032 dirty = server.dirty;
1033 cmd->proc(c);
1034 dirty = server.dirty-dirty;
1035 cmd->microseconds += ustime()-start;
1036 cmd->calls++;
1037
1038 if (server.appendonly && dirty)
1039 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
1040 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
1041 listLength(server.slaves))
1042 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
1043 if (listLength(server.monitors))
1044 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
1045 server.stat_numcommands++;
1046 }
1047
1048 /* If this function gets called we already read a whole
1049 * command, argments are in the client argv/argc fields.
1050 * processCommand() execute the command or prepare the
1051 * server for a bulk read from the client.
1052 *
1053 * If 1 is returned the client is still alive and valid and
1054 * and other operations can be performed by the caller. Otherwise
1055 * if 0 is returned the client was destroied (i.e. after QUIT). */
1056 int processCommand(redisClient *c) {
1057 struct redisCommand *cmd;
1058
1059 /* The QUIT command is handled separately. Normal command procs will
1060 * go through checking for replication and QUIT will cause trouble
1061 * when FORCE_REPLICATION is enabled and would be implemented in
1062 * a regular command proc. */
1063 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
1064 addReply(c,shared.ok);
1065 c->flags |= REDIS_CLOSE_AFTER_REPLY;
1066 return REDIS_ERR;
1067 }
1068
1069 /* Now lookup the command and check ASAP about trivial error conditions
1070 * such wrong arity, bad command name and so forth. */
1071 cmd = lookupCommand(c->argv[0]->ptr);
1072 if (!cmd) {
1073 addReplyErrorFormat(c,"unknown command '%s'",
1074 (char*)c->argv[0]->ptr);
1075 return REDIS_OK;
1076 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
1077 (c->argc < -cmd->arity)) {
1078 addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
1079 cmd->name);
1080 return REDIS_OK;
1081 }
1082
1083 /* Check if the user is authenticated */
1084 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
1085 addReplyError(c,"operation not permitted");
1086 return REDIS_OK;
1087 }
1088
1089 /* If cluster is enabled, redirect here */
1090 if (server.cluster_enabled &&
1091 !(cmd->getkeys_proc == NULL && cmd->firstkey == 0)) {
1092 int hashslot;
1093
1094 if (server.cluster.state != REDIS_CLUSTER_OK) {
1095 addReplyError(c,"The cluster is down. Check with CLUSTER INFO for more information");
1096 return REDIS_OK;
1097 } else {
1098 clusterNode *n = getNodeByQuery(c,cmd,c->argv,c->argc,&hashslot);
1099 if (n == NULL) {
1100 addReplyError(c,"Invalid cross-node request");
1101 return REDIS_OK;
1102 } else if (n != server.cluster.myself) {
1103 addReplySds(c,sdscatprintf(sdsempty(),
1104 "-MOVED %d %s:%d\r\n",hashslot,n->ip,n->port));
1105 return REDIS_OK;
1106 }
1107 }
1108 }
1109
1110 /* Handle the maxmemory directive.
1111 *
1112 * First we try to free some memory if possible (if there are volatile
1113 * keys in the dataset). If there are not the only thing we can do
1114 * is returning an error. */
1115 if (server.maxmemory) freeMemoryIfNeeded();
1116 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
1117 zmalloc_used_memory() > server.maxmemory)
1118 {
1119 addReplyError(c,"command not allowed when used memory > 'maxmemory'");
1120 return REDIS_OK;
1121 }
1122
1123 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1124 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
1125 &&
1126 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
1127 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
1128 addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1129 return REDIS_OK;
1130 }
1131
1132 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1133 * we are a slave with a broken link with master. */
1134 if (server.masterhost && server.replstate != REDIS_REPL_CONNECTED &&
1135 server.repl_serve_stale_data == 0 &&
1136 cmd->proc != infoCommand && cmd->proc != slaveofCommand)
1137 {
1138 addReplyError(c,
1139 "link with MASTER is down and slave-serve-stale-data is set to no");
1140 return REDIS_OK;
1141 }
1142
1143 /* Loading DB? Return an error if the command is not INFO */
1144 if (server.loading && cmd->proc != infoCommand) {
1145 addReply(c, shared.loadingerr);
1146 return REDIS_OK;
1147 }
1148
1149 /* Exec the command */
1150 if (c->flags & REDIS_MULTI &&
1151 cmd->proc != execCommand && cmd->proc != discardCommand &&
1152 cmd->proc != multiCommand && cmd->proc != watchCommand)
1153 {
1154 queueMultiCommand(c,cmd);
1155 addReply(c,shared.queued);
1156 } else {
1157 if (server.ds_enabled && blockClientOnSwappedKeys(c,cmd))
1158 return REDIS_ERR;
1159 call(c,cmd);
1160 }
1161 return REDIS_OK;
1162 }
1163
1164 /*================================== Shutdown =============================== */
1165
1166 int prepareForShutdown() {
1167 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
1168 /* Kill the saving child if there is a background saving in progress.
1169 We want to avoid race conditions, for instance our saving child may
1170 overwrite the synchronous saving did by SHUTDOWN. */
1171 if (server.bgsavechildpid != -1) {
1172 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
1173 kill(server.bgsavechildpid,SIGKILL);
1174 rdbRemoveTempFile(server.bgsavechildpid);
1175 }
1176 if (server.ds_enabled) {
1177 /* FIXME: flush all objects on disk */
1178 } else if (server.appendonly) {
1179 /* Append only file: fsync() the AOF and exit */
1180 aof_fsync(server.appendfd);
1181 } else if (server.saveparamslen > 0) {
1182 /* Snapshotting. Perform a SYNC SAVE and exit */
1183 if (rdbSave(server.dbfilename) != REDIS_OK) {
1184 /* Ooops.. error saving! The best we can do is to continue
1185 * operating. Note that if there was a background saving process,
1186 * in the next cron() Redis will be notified that the background
1187 * saving aborted, handling special stuff like slaves pending for
1188 * synchronization... */
1189 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
1190 return REDIS_ERR;
1191 }
1192 } else {
1193 redisLog(REDIS_WARNING,"Not saving DB.");
1194 }
1195 if (server.daemonize) unlink(server.pidfile);
1196 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
1197 return REDIS_OK;
1198 }
1199
1200 /*================================== Commands =============================== */
1201
1202 void authCommand(redisClient *c) {
1203 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
1204 c->authenticated = 1;
1205 addReply(c,shared.ok);
1206 } else {
1207 c->authenticated = 0;
1208 addReplyError(c,"invalid password");
1209 }
1210 }
1211
1212 void pingCommand(redisClient *c) {
1213 addReply(c,shared.pong);
1214 }
1215
1216 void echoCommand(redisClient *c) {
1217 addReplyBulk(c,c->argv[1]);
1218 }
1219
1220 /* Convert an amount of bytes into a human readable string in the form
1221 * of 100B, 2G, 100M, 4K, and so forth. */
1222 void bytesToHuman(char *s, unsigned long long n) {
1223 double d;
1224
1225 if (n < 1024) {
1226 /* Bytes */
1227 sprintf(s,"%lluB",n);
1228 return;
1229 } else if (n < (1024*1024)) {
1230 d = (double)n/(1024);
1231 sprintf(s,"%.2fK",d);
1232 } else if (n < (1024LL*1024*1024)) {
1233 d = (double)n/(1024*1024);
1234 sprintf(s,"%.2fM",d);
1235 } else if (n < (1024LL*1024*1024*1024)) {
1236 d = (double)n/(1024LL*1024*1024);
1237 sprintf(s,"%.2fG",d);
1238 }
1239 }
1240
1241 /* Create the string returned by the INFO command. This is decoupled
1242 * by the INFO command itself as we need to report the same information
1243 * on memory corruption problems. */
1244 sds genRedisInfoString(char *section) {
1245 sds info = sdsempty();
1246 time_t uptime = time(NULL)-server.stat_starttime;
1247 int j, numcommands;
1248 struct rusage self_ru, c_ru;
1249 unsigned long lol, bib;
1250 int allsections = 0, defsections = 0;
1251 int sections = 0;
1252
1253 if (section) {
1254 allsections = strcasecmp(section,"all") == 0;
1255 defsections = strcasecmp(section,"default") == 0;
1256 }
1257
1258 getrusage(RUSAGE_SELF, &self_ru);
1259 getrusage(RUSAGE_CHILDREN, &c_ru);
1260 getClientsMaxBuffers(&lol,&bib);
1261
1262 /* Server */
1263 if (allsections || defsections || !strcasecmp(section,"server")) {
1264 if (sections++) info = sdscat(info,"\r\n");
1265 info = sdscatprintf(info,
1266 "# Server\r\n"
1267 "redis_version:%s\r\n"
1268 "redis_git_sha1:%s\r\n"
1269 "redis_git_dirty:%d\r\n"
1270 "arch_bits:%s\r\n"
1271 "multiplexing_api:%s\r\n"
1272 "process_id:%ld\r\n"
1273 "tcp_port:%d\r\n"
1274 "uptime_in_seconds:%ld\r\n"
1275 "uptime_in_days:%ld\r\n"
1276 "lru_clock:%ld\r\n",
1277 REDIS_VERSION,
1278 redisGitSHA1(),
1279 strtol(redisGitDirty(),NULL,10) > 0,
1280 (sizeof(long) == 8) ? "64" : "32",
1281 aeGetApiName(),
1282 (long) getpid(),
1283 server.port,
1284 uptime,
1285 uptime/(3600*24),
1286 (unsigned long) server.lruclock);
1287 }
1288
1289 /* Clients */
1290 if (allsections || defsections || !strcasecmp(section,"clients")) {
1291 if (sections++) info = sdscat(info,"\r\n");
1292 info = sdscatprintf(info,
1293 "# Clients\r\n"
1294 "connected_clients:%d\r\n"
1295 "client_longest_output_list:%lu\r\n"
1296 "client_biggest_input_buf:%lu\r\n"
1297 "blocked_clients:%d\r\n",
1298 listLength(server.clients)-listLength(server.slaves),
1299 lol, bib,
1300 server.bpop_blocked_clients);
1301 }
1302
1303 /* Memory */
1304 if (allsections || defsections || !strcasecmp(section,"memory")) {
1305 char hmem[64];
1306 char peak_hmem[64];
1307
1308 bytesToHuman(hmem,zmalloc_used_memory());
1309 bytesToHuman(peak_hmem,server.stat_peak_memory);
1310 if (sections++) info = sdscat(info,"\r\n");
1311 info = sdscatprintf(info,
1312 "# Memory\r\n"
1313 "used_memory:%zu\r\n"
1314 "used_memory_human:%s\r\n"
1315 "used_memory_rss:%zu\r\n"
1316 "used_memory_peak:%zu\r\n"
1317 "used_memory_peak_human:%s\r\n"
1318 "mem_fragmentation_ratio:%.2f\r\n"
1319 "peak_mem_fragmentation_ratio:%.2f\r\n"
1320 "use_tcmalloc:%d\r\n",
1321 zmalloc_used_memory(),
1322 hmem,
1323 zmalloc_get_rss(),
1324 server.stat_peak_memory,
1325 peak_hmem,
1326 zmalloc_get_fragmentation_ratio(),
1327 (float)zmalloc_get_rss()/server.stat_peak_memory,
1328 #ifdef USE_TCMALLOC
1329 1
1330 #else
1331 0
1332 #endif
1333 );
1334 }
1335
1336 /* Allocation statistics */
1337 if (allsections || !strcasecmp(section,"allocstats")) {
1338 if (sections++) info = sdscat(info,"\r\n");
1339 info = sdscat(info, "# Allocstats\r\nallocation_stats:");
1340 for (j = 0; j <= ZMALLOC_MAX_ALLOC_STAT; j++) {
1341 size_t count = zmalloc_allocations_for_size(j);
1342 if (count) {
1343 if (info[sdslen(info)-1] != ':') info = sdscatlen(info,",",1);
1344 info = sdscatprintf(info,"%s%d=%zu",
1345 (j == ZMALLOC_MAX_ALLOC_STAT) ? ">=" : "",
1346 j,count);
1347 }
1348 }
1349 info = sdscat(info,"\r\n");
1350 }
1351
1352 /* Persistence */
1353 if (allsections || defsections || !strcasecmp(section,"persistence")) {
1354 if (sections++) info = sdscat(info,"\r\n");
1355 info = sdscatprintf(info,
1356 "# Persistence\r\n"
1357 "loading:%d\r\n"
1358 "aof_enabled:%d\r\n"
1359 "changes_since_last_save:%lld\r\n"
1360 "bgsave_in_progress:%d\r\n"
1361 "last_save_time:%ld\r\n"
1362 "bgrewriteaof_in_progress:%d\r\n",
1363 server.loading,
1364 server.appendonly,
1365 server.dirty,
1366 server.bgsavechildpid != -1 ||
1367 server.bgsavethread != (pthread_t) -1,
1368 server.lastsave,
1369 server.bgrewritechildpid != -1);
1370
1371 if (server.loading) {
1372 double perc;
1373 time_t eta, elapsed;
1374 off_t remaining_bytes = server.loading_total_bytes-
1375 server.loading_loaded_bytes;
1376
1377 perc = ((double)server.loading_loaded_bytes /
1378 server.loading_total_bytes) * 100;
1379
1380 elapsed = time(NULL)-server.loading_start_time;
1381 if (elapsed == 0) {
1382 eta = 1; /* A fake 1 second figure if we don't have
1383 enough info */
1384 } else {
1385 eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
1386 }
1387
1388 info = sdscatprintf(info,
1389 "loading_start_time:%ld\r\n"
1390 "loading_total_bytes:%llu\r\n"
1391 "loading_loaded_bytes:%llu\r\n"
1392 "loading_loaded_perc:%.2f\r\n"
1393 "loading_eta_seconds:%ld\r\n"
1394 ,(unsigned long) server.loading_start_time,
1395 (unsigned long long) server.loading_total_bytes,
1396 (unsigned long long) server.loading_loaded_bytes,
1397 perc,
1398 eta
1399 );
1400 }
1401 }
1402
1403 /* Diskstore */
1404 if (allsections || defsections || !strcasecmp(section,"diskstore")) {
1405 if (sections++) info = sdscat(info,"\r\n");
1406 info = sdscatprintf(info,
1407 "# Diskstore\r\n"
1408 "ds_enabled:%d\r\n",
1409 server.ds_enabled != 0);
1410 if (server.ds_enabled) {
1411 lockThreadedIO();
1412 info = sdscatprintf(info,
1413 "cache_max_memory:%llu\r\n"
1414 "cache_blocked_clients:%lu\r\n"
1415 "cache_io_queue_len:%lu\r\n"
1416 "cache_io_jobs_new:%lu\r\n"
1417 "cache_io_jobs_processing:%lu\r\n"
1418 "cache_io_jobs_processed:%lu\r\n"
1419 "cache_io_ready_clients:%lu\r\n"
1420 ,(unsigned long long) server.cache_max_memory,
1421 (unsigned long) server.cache_blocked_clients,
1422 (unsigned long) listLength(server.cache_io_queue),
1423 (unsigned long) listLength(server.io_newjobs),
1424 (unsigned long) listLength(server.io_processing),
1425 (unsigned long) listLength(server.io_processed),
1426 (unsigned long) listLength(server.io_ready_clients)
1427 );
1428 unlockThreadedIO();
1429 }
1430 }
1431
1432 /* Stats */
1433 if (allsections || defsections || !strcasecmp(section,"stats")) {
1434 if (sections++) info = sdscat(info,"\r\n");
1435 info = sdscatprintf(info,
1436 "# Stats\r\n"
1437 "total_connections_received:%lld\r\n"
1438 "total_commands_processed:%lld\r\n"
1439 "expired_keys:%lld\r\n"
1440 "evicted_keys:%lld\r\n"
1441 "keyspace_hits:%lld\r\n"
1442 "keyspace_misses:%lld\r\n"
1443 "pubsub_channels:%ld\r\n"
1444 "pubsub_patterns:%u\r\n",
1445 server.stat_numconnections,
1446 server.stat_numcommands,
1447 server.stat_expiredkeys,
1448 server.stat_evictedkeys,
1449 server.stat_keyspace_hits,
1450 server.stat_keyspace_misses,
1451 dictSize(server.pubsub_channels),
1452 listLength(server.pubsub_patterns));
1453 }
1454
1455 /* Replication */
1456 if (allsections || defsections || !strcasecmp(section,"replication")) {
1457 if (sections++) info = sdscat(info,"\r\n");
1458 info = sdscatprintf(info,
1459 "# Replication\r\n"
1460 "role:%s\r\n",
1461 server.masterhost == NULL ? "master" : "slave");
1462 if (server.masterhost) {
1463 info = sdscatprintf(info,
1464 "master_host:%s\r\n"
1465 "master_port:%d\r\n"
1466 "master_link_status:%s\r\n"
1467 "master_last_io_seconds_ago:%d\r\n"
1468 "master_sync_in_progress:%d\r\n"
1469 ,server.masterhost,
1470 server.masterport,
1471 (server.replstate == REDIS_REPL_CONNECTED) ?
1472 "up" : "down",
1473 server.master ?
1474 ((int)(time(NULL)-server.master->lastinteraction)) : -1,
1475 server.replstate == REDIS_REPL_TRANSFER
1476 );
1477
1478 if (server.replstate == REDIS_REPL_TRANSFER) {
1479 info = sdscatprintf(info,
1480 "master_sync_left_bytes:%ld\r\n"
1481 "master_sync_last_io_seconds_ago:%d\r\n"
1482 ,(long)server.repl_transfer_left,
1483 (int)(time(NULL)-server.repl_transfer_lastio)
1484 );
1485 }
1486 }
1487 info = sdscatprintf(info,
1488 "connected_slaves:%d\r\n",
1489 listLength(server.slaves));
1490 }
1491
1492 /* CPU */
1493 if (allsections || defsections || !strcasecmp(section,"cpu")) {
1494 if (sections++) info = sdscat(info,"\r\n");
1495 info = sdscatprintf(info,
1496 "# CPU\r\n"
1497 "used_cpu_sys:%.2f\r\n"
1498 "used_cpu_user:%.2f\r\n"
1499 "used_cpu_sys_childrens:%.2f\r\n"
1500 "used_cpu_user_childrens:%.2f\r\n",
1501 (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000,
1502 (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000,
1503 (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000,
1504 (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000);
1505 }
1506
1507 /* cmdtime */
1508 if (allsections || !strcasecmp(section,"commandstats")) {
1509 if (sections++) info = sdscat(info,"\r\n");
1510 info = sdscatprintf(info, "# Commandstats\r\n");
1511 numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1512 for (j = 0; j < numcommands; j++) {
1513 struct redisCommand *c = redisCommandTable+j;
1514
1515 if (!c->calls) continue;
1516 info = sdscatprintf(info,
1517 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1518 c->name, c->calls, c->microseconds,
1519 (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls));
1520 }
1521 }
1522
1523 /* Clusetr */
1524 if (allsections || defsections || !strcasecmp(section,"cluster")) {
1525 if (sections++) info = sdscat(info,"\r\n");
1526 info = sdscatprintf(info,
1527 "# Cluster\r\n"
1528 "cluster_enabled:%d\r\n",
1529 server.cluster_enabled);
1530 }
1531
1532 /* Key space */
1533 if (allsections || defsections || !strcasecmp(section,"keyspace")) {
1534 if (sections++) info = sdscat(info,"\r\n");
1535 info = sdscatprintf(info, "# Keyspace\r\n");
1536 for (j = 0; j < server.dbnum; j++) {
1537 long long keys, vkeys;
1538
1539 keys = dictSize(server.db[j].dict);
1540 vkeys = dictSize(server.db[j].expires);
1541 if (keys || vkeys) {
1542 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
1543 j, keys, vkeys);
1544 }
1545 }
1546 }
1547 return info;
1548 }
1549
1550 void infoCommand(redisClient *c) {
1551 char *section = c->argc == 2 ? c->argv[1]->ptr : "default";
1552
1553 if (c->argc > 2) {
1554 addReply(c,shared.syntaxerr);
1555 return;
1556 }
1557 sds info = genRedisInfoString(section);
1558 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
1559 (unsigned long)sdslen(info)));
1560 addReplySds(c,info);
1561 addReply(c,shared.crlf);
1562 }
1563
1564 void monitorCommand(redisClient *c) {
1565 /* ignore MONITOR if aleady slave or in monitor mode */
1566 if (c->flags & REDIS_SLAVE) return;
1567
1568 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
1569 c->slaveseldb = 0;
1570 listAddNodeTail(server.monitors,c);
1571 addReply(c,shared.ok);
1572 }
1573
1574 /* ============================ Maxmemory directive ======================== */
1575
1576 /* This function gets called when 'maxmemory' is set on the config file to limit
1577 * the max memory used by the server, and we are out of memory.
1578 * This function will try to, in order:
1579 *
1580 * - Free objects from the free list
1581 * - Try to remove keys with an EXPIRE set
1582 *
1583 * It is not possible to free enough memory to reach used-memory < maxmemory
1584 * the server will start refusing commands that will enlarge even more the
1585 * memory usage.
1586 */
1587 void freeMemoryIfNeeded(void) {
1588 /* Remove keys accordingly to the active policy as long as we are
1589 * over the memory limit. */
1590 if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return;
1591
1592 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
1593 int j, k, freed = 0;
1594
1595 for (j = 0; j < server.dbnum; j++) {
1596 long bestval = 0; /* just to prevent warning */
1597 sds bestkey = NULL;
1598 struct dictEntry *de;
1599 redisDb *db = server.db+j;
1600 dict *dict;
1601
1602 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1603 server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
1604 {
1605 dict = server.db[j].dict;
1606 } else {
1607 dict = server.db[j].expires;
1608 }
1609 if (dictSize(dict) == 0) continue;
1610
1611 /* volatile-random and allkeys-random policy */
1612 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
1613 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
1614 {
1615 de = dictGetRandomKey(dict);
1616 bestkey = dictGetEntryKey(de);
1617 }
1618
1619 /* volatile-lru and allkeys-lru policy */
1620 else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1621 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1622 {
1623 for (k = 0; k < server.maxmemory_samples; k++) {
1624 sds thiskey;
1625 long thisval;
1626 robj *o;
1627
1628 de = dictGetRandomKey(dict);
1629 thiskey = dictGetEntryKey(de);
1630 /* When policy is volatile-lru we need an additonal lookup
1631 * to locate the real key, as dict is set to db->expires. */
1632 if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1633 de = dictFind(db->dict, thiskey);
1634 o = dictGetEntryVal(de);
1635 thisval = estimateObjectIdleTime(o);
1636
1637 /* Higher idle time is better candidate for deletion */
1638 if (bestkey == NULL || thisval > bestval) {
1639 bestkey = thiskey;
1640 bestval = thisval;
1641 }
1642 }
1643 }
1644
1645 /* volatile-ttl */
1646 else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
1647 for (k = 0; k < server.maxmemory_samples; k++) {
1648 sds thiskey;
1649 long thisval;
1650
1651 de = dictGetRandomKey(dict);
1652 thiskey = dictGetEntryKey(de);
1653 thisval = (long) dictGetEntryVal(de);
1654
1655 /* Expire sooner (minor expire unix timestamp) is better
1656 * candidate for deletion */
1657 if (bestkey == NULL || thisval < bestval) {
1658 bestkey = thiskey;
1659 bestval = thisval;
1660 }
1661 }
1662 }
1663
1664 /* Finally remove the selected key. */
1665 if (bestkey) {
1666 robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
1667 propagateExpire(db,keyobj);
1668 dbDelete(db,keyobj);
1669 server.stat_evictedkeys++;
1670 decrRefCount(keyobj);
1671 freed++;
1672 }
1673 }
1674 if (!freed) return; /* nothing to free... */
1675 }
1676 }
1677
1678 /* =================================== Main! ================================ */
1679
1680 #ifdef __linux__
1681 int linuxOvercommitMemoryValue(void) {
1682 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
1683 char buf[64];
1684
1685 if (!fp) return -1;
1686 if (fgets(buf,64,fp) == NULL) {
1687 fclose(fp);
1688 return -1;
1689 }
1690 fclose(fp);
1691
1692 return atoi(buf);
1693 }
1694
1695 void linuxOvercommitMemoryWarning(void) {
1696 if (linuxOvercommitMemoryValue() == 0) {
1697 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.");
1698 }
1699 }
1700 #endif /* __linux__ */
1701
1702 void createPidFile(void) {
1703 /* Try to write the pid file in a best-effort way. */
1704 FILE *fp = fopen(server.pidfile,"w");
1705 if (fp) {
1706 fprintf(fp,"%d\n",(int)getpid());
1707 fclose(fp);
1708 }
1709 }
1710
1711 void daemonize(void) {
1712 int fd;
1713
1714 if (fork() != 0) exit(0); /* parent exits */
1715 setsid(); /* create a new session */
1716
1717 /* Every output goes to /dev/null. If Redis is daemonized but
1718 * the 'logfile' is set to 'stdout' in the configuration file
1719 * it will not log at all. */
1720 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
1721 dup2(fd, STDIN_FILENO);
1722 dup2(fd, STDOUT_FILENO);
1723 dup2(fd, STDERR_FILENO);
1724 if (fd > STDERR_FILENO) close(fd);
1725 }
1726 }
1727
1728 void version() {
1729 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
1730 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1731 exit(0);
1732 }
1733
1734 void usage() {
1735 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
1736 fprintf(stderr," ./redis-server - (read config from stdin)\n");
1737 exit(1);
1738 }
1739
1740 void redisAsciiArt(void) {
1741 #include "asciilogo.h"
1742 char *buf = zmalloc(1024*16);
1743
1744 snprintf(buf,1024*16,ascii_logo,
1745 REDIS_VERSION,
1746 redisGitSHA1(),
1747 strtol(redisGitDirty(),NULL,10) > 0,
1748 (sizeof(long) == 8) ? "64" : "32",
1749 server.cluster_enabled ? "cluster" : "stand alone",
1750 server.port,
1751 (long) getpid()
1752 );
1753 redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf);
1754 zfree(buf);
1755 }
1756
1757 int main(int argc, char **argv) {
1758 long long start;
1759
1760 initServerConfig();
1761 if (argc == 2) {
1762 if (strcmp(argv[1], "-v") == 0 ||
1763 strcmp(argv[1], "--version") == 0) version();
1764 if (strcmp(argv[1], "--help") == 0) usage();
1765 resetServerSaveParams();
1766 loadServerConfig(argv[1]);
1767 } else if ((argc > 2)) {
1768 usage();
1769 } else {
1770 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'");
1771 }
1772 if (server.daemonize) daemonize();
1773 initServer();
1774 if (server.daemonize) createPidFile();
1775 redisAsciiArt();
1776 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
1777 #ifdef __linux__
1778 linuxOvercommitMemoryWarning();
1779 #endif
1780 start = ustime();
1781 if (server.ds_enabled) {
1782 redisLog(REDIS_NOTICE,"DB not loaded (running with disk back end)");
1783 } else if (server.appendonly) {
1784 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
1785 redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000);
1786 } else {
1787 if (rdbLoad(server.dbfilename) == REDIS_OK)
1788 redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds",(float)(ustime()-start)/1000000);
1789 }
1790 if (server.ipfd > 0)
1791 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
1792 if (server.sofd > 0)
1793 redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
1794 aeSetBeforeSleepProc(server.el,beforeSleep);
1795 aeMain(server.el);
1796 aeDeleteEventLoop(server.el);
1797 return 0;
1798 }
1799
1800 #ifdef HAVE_BACKTRACE
1801 static void *getMcontextEip(ucontext_t *uc) {
1802 #if defined(__FreeBSD__)
1803 return (void*) uc->uc_mcontext.mc_eip;
1804 #elif defined(__dietlibc__)
1805 return (void*) uc->uc_mcontext.eip;
1806 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1807 #if __x86_64__
1808 return (void*) uc->uc_mcontext->__ss.__rip;
1809 #else
1810 return (void*) uc->uc_mcontext->__ss.__eip;
1811 #endif
1812 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1813 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1814 return (void*) uc->uc_mcontext->__ss.__rip;
1815 #else
1816 return (void*) uc->uc_mcontext->__ss.__eip;
1817 #endif
1818 #elif defined(__i386__)
1819 return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
1820 #elif defined(__X86_64__) || defined(__x86_64__)
1821 return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
1822 #elif defined(__ia64__) /* Linux IA64 */
1823 return (void*) uc->uc_mcontext.sc_ip;
1824 #else
1825 return NULL;
1826 #endif
1827 }
1828
1829 static void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
1830 void *trace[100];
1831 char **messages = NULL;
1832 int i, trace_size = 0;
1833 ucontext_t *uc = (ucontext_t*) secret;
1834 sds infostring;
1835 struct sigaction act;
1836 REDIS_NOTUSED(info);
1837
1838 redisLog(REDIS_WARNING,
1839 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
1840 infostring = genRedisInfoString("all");
1841 redisLogRaw(REDIS_WARNING, infostring);
1842 /* It's not safe to sdsfree() the returned string under memory
1843 * corruption conditions. Let it leak as we are going to abort */
1844
1845 trace_size = backtrace(trace, 100);
1846 /* overwrite sigaction with caller's address */
1847 if (getMcontextEip(uc) != NULL) {
1848 trace[1] = getMcontextEip(uc);
1849 }
1850 messages = backtrace_symbols(trace, trace_size);
1851
1852 for (i=1; i<trace_size; ++i)
1853 redisLog(REDIS_WARNING,"%s", messages[i]);
1854
1855 /* free(messages); Don't call free() with possibly corrupted memory. */
1856 if (server.daemonize) unlink(server.pidfile);
1857
1858 /* Make sure we exit with the right signal at the end. So for instance
1859 * the core will be dumped if enabled. */
1860 sigemptyset (&act.sa_mask);
1861 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1862 * is used. Otherwise, sa_handler is used */
1863 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1864 act.sa_handler = SIG_DFL;
1865 sigaction (sig, &act, NULL);
1866 kill(getpid(),sig);
1867 }
1868 #endif /* HAVE_BACKTRACE */
1869
1870 static void sigtermHandler(int sig) {
1871 REDIS_NOTUSED(sig);
1872
1873 redisLog(REDIS_WARNING,"Received SIGTERM, scheduling shutdown...");
1874 server.shutdown_asap = 1;
1875 }
1876
1877 void setupSignalHandlers(void) {
1878 struct sigaction act;
1879
1880 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1881 * Otherwise, sa_handler is used. */
1882 sigemptyset(&act.sa_mask);
1883 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1884 act.sa_handler = sigtermHandler;
1885 sigaction(SIGTERM, &act, NULL);
1886
1887 #ifdef HAVE_BACKTRACE
1888 sigemptyset(&act.sa_mask);
1889 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
1890 act.sa_sigaction = sigsegvHandler;
1891 sigaction(SIGSEGV, &act, NULL);
1892 sigaction(SIGBUS, &act, NULL);
1893 sigaction(SIGFPE, &act, NULL);
1894 sigaction(SIGILL, &act, NULL);
1895 #endif
1896 return;
1897 }
1898
1899 /* The End */