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