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