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