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