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