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