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