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