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