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