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