2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
35 #endif /* HAVE_BACKTRACE */
44 #include <arpa/inet.h>
48 #include <sys/resource.h>
54 #include <sys/resource.h>
56 /* Our shared "common" objects */
58 struct sharedObjectsStruct shared
;
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. */
64 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
66 /*================================= Globals ================================= */
69 struct redisServer server
; /* server global state */
70 struct redisCommand
*commandTable
;
71 struct redisCommand readonlyCommandTable
[] = {
72 {"get",getCommand
,2,0,NULL
,1,1,1},
73 {"set",setCommand
,3,REDIS_CMD_DENYOOM
,NULL
,0,0,0},
74 {"setnx",setnxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,0,0,0},
75 {"setex",setexCommand
,4,REDIS_CMD_DENYOOM
,NULL
,0,0,0},
76 {"append",appendCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
77 {"strlen",strlenCommand
,2,0,NULL
,1,1,1},
78 {"del",delCommand
,-2,0,NULL
,0,0,0},
79 {"exists",existsCommand
,2,0,NULL
,1,1,1},
80 {"setbit",setbitCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
81 {"getbit",getbitCommand
,3,0,NULL
,1,1,1},
82 {"setrange",setrangeCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
83 {"getrange",getrangeCommand
,4,0,NULL
,1,1,1},
84 {"substr",getrangeCommand
,4,0,NULL
,1,1,1},
85 {"incr",incrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
86 {"decr",decrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
87 {"mget",mgetCommand
,-2,0,NULL
,1,-1,1},
88 {"rpush",rpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
89 {"lpush",lpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
90 {"rpushx",rpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
91 {"lpushx",lpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
92 {"linsert",linsertCommand
,5,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
93 {"rpop",rpopCommand
,2,0,NULL
,1,1,1},
94 {"lpop",lpopCommand
,2,0,NULL
,1,1,1},
95 {"brpop",brpopCommand
,-3,0,NULL
,1,1,1},
96 {"brpoplpush",brpoplpushCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,2,1},
97 {"blpop",blpopCommand
,-3,0,NULL
,1,1,1},
98 {"llen",llenCommand
,2,0,NULL
,1,1,1},
99 {"lindex",lindexCommand
,3,0,NULL
,1,1,1},
100 {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
101 {"lrange",lrangeCommand
,4,0,NULL
,1,1,1},
102 {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1},
103 {"lrem",lremCommand
,4,0,NULL
,1,1,1},
104 {"rpoplpush",rpoplpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1},
105 {"sadd",saddCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
106 {"srem",sremCommand
,3,0,NULL
,1,1,1},
107 {"smove",smoveCommand
,4,0,NULL
,1,2,1},
108 {"sismember",sismemberCommand
,3,0,NULL
,1,1,1},
109 {"scard",scardCommand
,2,0,NULL
,1,1,1},
110 {"spop",spopCommand
,2,0,NULL
,1,1,1},
111 {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1},
112 {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
113 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
114 {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
115 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
116 {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
117 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
118 {"smembers",sinterCommand
,2,0,NULL
,1,1,1},
119 {"zadd",zaddCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
120 {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
121 {"zrem",zremCommand
,3,0,NULL
,1,1,1},
122 {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1},
123 {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1},
124 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
125 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
126 {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1},
127 {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1},
128 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1},
129 {"zcount",zcountCommand
,4,0,NULL
,1,1,1},
130 {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1},
131 {"zcard",zcardCommand
,2,0,NULL
,1,1,1},
132 {"zscore",zscoreCommand
,3,0,NULL
,1,1,1},
133 {"zrank",zrankCommand
,3,0,NULL
,1,1,1},
134 {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1},
135 {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
136 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
137 {"hget",hgetCommand
,3,0,NULL
,1,1,1},
138 {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
139 {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1},
140 {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
141 {"hdel",hdelCommand
,3,0,NULL
,1,1,1},
142 {"hlen",hlenCommand
,2,0,NULL
,1,1,1},
143 {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1},
144 {"hvals",hvalsCommand
,2,0,NULL
,1,1,1},
145 {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1},
146 {"hexists",hexistsCommand
,3,0,NULL
,1,1,1},
147 {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
148 {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
149 {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
150 {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
151 {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
152 {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0},
153 {"select",selectCommand
,2,0,NULL
,0,0,0},
154 {"move",moveCommand
,3,0,NULL
,1,1,1},
155 {"rename",renameCommand
,3,0,NULL
,1,1,1},
156 {"renamenx",renamenxCommand
,3,0,NULL
,1,1,1},
157 {"expire",expireCommand
,3,0,NULL
,0,0,0},
158 {"expireat",expireatCommand
,3,0,NULL
,0,0,0},
159 {"keys",keysCommand
,2,0,NULL
,0,0,0},
160 {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0},
161 {"auth",authCommand
,2,0,NULL
,0,0,0},
162 {"ping",pingCommand
,1,0,NULL
,0,0,0},
163 {"echo",echoCommand
,2,0,NULL
,0,0,0},
164 {"save",saveCommand
,1,0,NULL
,0,0,0},
165 {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0},
166 {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0},
167 {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0},
168 {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0},
169 {"type",typeCommand
,2,0,NULL
,1,1,1},
170 {"multi",multiCommand
,1,0,NULL
,0,0,0},
171 {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
172 {"discard",discardCommand
,1,0,NULL
,0,0,0},
173 {"sync",syncCommand
,1,0,NULL
,0,0,0},
174 {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0},
175 {"flushall",flushallCommand
,1,0,NULL
,0,0,0},
176 {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
177 {"info",infoCommand
,1,0,NULL
,0,0,0},
178 {"monitor",monitorCommand
,1,0,NULL
,0,0,0},
179 {"ttl",ttlCommand
,2,0,NULL
,1,1,1},
180 {"persist",persistCommand
,2,0,NULL
,1,1,1},
181 {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0},
182 {"debug",debugCommand
,-2,0,NULL
,0,0,0},
183 {"config",configCommand
,-2,0,NULL
,0,0,0},
184 {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0},
185 {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0},
186 {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0},
187 {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0},
188 {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
189 {"watch",watchCommand
,-2,0,NULL
,0,0,0},
190 {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0}
193 /*============================ Utility functions ============================ */
195 void redisLog(int level
, const char *fmt
, ...) {
196 const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
};
197 const char *c
= ".-*#";
198 time_t now
= time(NULL
);
202 char msg
[REDIS_MAX_LOGMSG_LEN
];
204 if (level
< server
.verbosity
) return;
206 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
210 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
213 strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
));
214 fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
);
217 if (server
.logfile
) fclose(fp
);
219 if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
);
222 /* Redis generally does not try to recover from out of memory conditions
223 * when allocating objects or strings, it is not clear if it will be possible
224 * to report this condition to the client since the networking layer itself
225 * is based on heap allocation for send buffers, so we simply abort.
226 * At least the code will be simpler to read... */
227 void oom(const char *msg
) {
228 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
233 /*====================== Hash table type implementation ==================== */
235 /* This is an hash table type that uses the SDS dynamic strings libary as
236 * keys and radis objects as values (objects can hold SDS strings,
239 void dictVanillaFree(void *privdata
, void *val
)
241 DICT_NOTUSED(privdata
);
245 void dictListDestructor(void *privdata
, void *val
)
247 DICT_NOTUSED(privdata
);
248 listRelease((list
*)val
);
251 int dictSdsKeyCompare(void *privdata
, const void *key1
,
255 DICT_NOTUSED(privdata
);
257 l1
= sdslen((sds
)key1
);
258 l2
= sdslen((sds
)key2
);
259 if (l1
!= l2
) return 0;
260 return memcmp(key1
, key2
, l1
) == 0;
263 /* A case insensitive version used for the command lookup table. */
264 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
267 DICT_NOTUSED(privdata
);
269 return strcasecmp(key1
, key2
) == 0;
272 void dictRedisObjectDestructor(void *privdata
, void *val
)
274 DICT_NOTUSED(privdata
);
276 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
280 void dictSdsDestructor(void *privdata
, void *val
)
282 DICT_NOTUSED(privdata
);
287 int dictObjKeyCompare(void *privdata
, const void *key1
,
290 const robj
*o1
= key1
, *o2
= key2
;
291 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
294 unsigned int dictObjHash(const void *key
) {
296 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
299 unsigned int dictSdsHash(const void *key
) {
300 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
303 unsigned int dictSdsCaseHash(const void *key
) {
304 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
307 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
310 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
313 if (o1
->encoding
== REDIS_ENCODING_INT
&&
314 o2
->encoding
== REDIS_ENCODING_INT
)
315 return o1
->ptr
== o2
->ptr
;
317 o1
= getDecodedObject(o1
);
318 o2
= getDecodedObject(o2
);
319 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
325 unsigned int dictEncObjHash(const void *key
) {
326 robj
*o
= (robj
*) key
;
328 if (o
->encoding
== REDIS_ENCODING_RAW
) {
329 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
331 if (o
->encoding
== REDIS_ENCODING_INT
) {
335 len
= ll2string(buf
,32,(long)o
->ptr
);
336 return dictGenHashFunction((unsigned char*)buf
, len
);
340 o
= getDecodedObject(o
);
341 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
349 dictType setDictType
= {
350 dictEncObjHash
, /* hash function */
353 dictEncObjKeyCompare
, /* key compare */
354 dictRedisObjectDestructor
, /* key destructor */
355 NULL
/* val destructor */
358 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
359 dictType zsetDictType
= {
360 dictEncObjHash
, /* hash function */
363 dictEncObjKeyCompare
, /* key compare */
364 dictRedisObjectDestructor
, /* key destructor */
365 NULL
/* val destructor */
368 /* Db->dict, keys are sds strings, vals are Redis objects. */
369 dictType dbDictType
= {
370 dictSdsHash
, /* hash function */
373 dictSdsKeyCompare
, /* key compare */
374 dictSdsDestructor
, /* key destructor */
375 dictRedisObjectDestructor
/* val destructor */
379 dictType keyptrDictType
= {
380 dictSdsHash
, /* hash function */
383 dictSdsKeyCompare
, /* key compare */
384 NULL
, /* key destructor */
385 NULL
/* val destructor */
388 /* Command table. sds string -> command struct pointer. */
389 dictType commandTableDictType
= {
390 dictSdsCaseHash
, /* hash function */
393 dictSdsKeyCaseCompare
, /* key compare */
394 dictSdsDestructor
, /* key destructor */
395 NULL
/* val destructor */
398 /* Hash type hash table (note that small hashes are represented with zimpaps) */
399 dictType hashDictType
= {
400 dictEncObjHash
, /* hash function */
403 dictEncObjKeyCompare
, /* key compare */
404 dictRedisObjectDestructor
, /* key destructor */
405 dictRedisObjectDestructor
/* val destructor */
408 /* Keylist hash table type has unencoded redis objects as keys and
409 * lists as values. It's used for blocking operations (BLPOP) and to
410 * map swapped keys to a list of clients waiting for this keys to be loaded. */
411 dictType keylistDictType
= {
412 dictObjHash
, /* hash function */
415 dictObjKeyCompare
, /* key compare */
416 dictRedisObjectDestructor
, /* key destructor */
417 dictListDestructor
/* val destructor */
420 int htNeedsResize(dict
*dict
) {
421 long long size
, used
;
423 size
= dictSlots(dict
);
424 used
= dictSize(dict
);
425 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
426 (used
*100/size
< REDIS_HT_MINFILL
));
429 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
430 * we resize the hash table to save memory */
431 void tryResizeHashTables(void) {
434 for (j
= 0; j
< server
.dbnum
; j
++) {
435 if (htNeedsResize(server
.db
[j
].dict
))
436 dictResize(server
.db
[j
].dict
);
437 if (htNeedsResize(server
.db
[j
].expires
))
438 dictResize(server
.db
[j
].expires
);
442 /* Our hash table implementation performs rehashing incrementally while
443 * we write/read from the hash table. Still if the server is idle, the hash
444 * table will use two tables for a long time. So we try to use 1 millisecond
445 * of CPU time at every serverCron() loop in order to rehash some key. */
446 void incrementallyRehash(void) {
449 for (j
= 0; j
< server
.dbnum
; j
++) {
450 if (dictIsRehashing(server
.db
[j
].dict
)) {
451 dictRehashMilliseconds(server
.db
[j
].dict
,1);
452 break; /* already used our millisecond for this loop... */
457 /* This function is called once a background process of some kind terminates,
458 * as we want to avoid resizing the hash tables when there is a child in order
459 * to play well with copy-on-write (otherwise when a resize happens lots of
460 * memory pages are copied). The goal of this function is to update the ability
461 * for dict.c to resize the hash tables accordingly to the fact we have o not
463 void updateDictResizePolicy(void) {
464 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
470 /* ======================= Cron: called every 100 ms ======================== */
472 /* Try to expire a few timed out keys. The algorithm used is adaptive and
473 * will use few CPU cycles if there are few expiring keys, otherwise
474 * it will get more aggressive to avoid that too much memory is used by
475 * keys that can be removed from the keyspace. */
476 void activeExpireCycle(void) {
479 for (j
= 0; j
< server
.dbnum
; j
++) {
481 redisDb
*db
= server
.db
+j
;
483 /* Continue to expire if at the end of the cycle more than 25%
484 * of the keys were expired. */
486 long num
= dictSize(db
->expires
);
487 time_t now
= time(NULL
);
490 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
491 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
496 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
497 t
= (time_t) dictGetEntryVal(de
);
499 sds key
= dictGetEntryKey(de
);
500 robj
*keyobj
= createStringObject(key
,sdslen(key
));
502 propagateExpire(db
,keyobj
);
504 decrRefCount(keyobj
);
506 server
.stat_expiredkeys
++;
509 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
513 void updateLRUClock(void) {
514 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
518 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
519 int j
, loops
= server
.cronloops
++;
520 REDIS_NOTUSED(eventLoop
);
522 REDIS_NOTUSED(clientData
);
524 /* We take a cached value of the unix time in the global state because
525 * with virtual memory and aging there is to store the current time
526 * in objects at every object access, and accuracy is not needed.
527 * To access a global var is faster than calling time(NULL) */
528 server
.unixtime
= time(NULL
);
529 /* We have just 22 bits per object for LRU information.
530 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
531 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
533 * Note that even if this will wrap after 1.5 years it's not a problem,
534 * everything will still work but just some object will appear younger
535 * to Redis. But for this to happen a given object should never be touched
538 * Note that you can change the resolution altering the
539 * REDIS_LRU_CLOCK_RESOLUTION define.
543 /* We received a SIGTERM, shutting down here in a safe way, as it is
544 * not ok doing so inside the signal handler. */
545 if (server
.shutdown_asap
) {
546 if (prepareForShutdown() == REDIS_OK
) exit(0);
547 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
550 /* Show some info about non-empty databases */
551 for (j
= 0; j
< server
.dbnum
; j
++) {
552 long long size
, used
, vkeys
;
554 size
= dictSlots(server
.db
[j
].dict
);
555 used
= dictSize(server
.db
[j
].dict
);
556 vkeys
= dictSize(server
.db
[j
].expires
);
557 if (!(loops
% 50) && (used
|| vkeys
)) {
558 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
559 /* dictPrintStats(server.dict); */
563 /* We don't want to resize the hash tables while a bacground saving
564 * is in progress: the saving child is created using fork() that is
565 * implemented with a copy-on-write semantic in most modern systems, so
566 * if we resize the HT while there is the saving child at work actually
567 * a lot of memory movements in the parent will cause a lot of pages
569 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
570 if (!(loops
% 10)) tryResizeHashTables();
571 if (server
.activerehashing
) incrementallyRehash();
574 /* Show information about connected clients */
576 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
577 listLength(server
.clients
)-listLength(server
.slaves
),
578 listLength(server
.slaves
),
579 zmalloc_used_memory());
582 /* Close connections of timedout clients */
583 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
584 closeTimedoutClients();
586 /* Check if a background saving or AOF rewrite in progress terminated */
587 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
591 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
592 if (pid
== server
.bgsavechildpid
) {
593 backgroundSaveDoneHandler(statloc
);
595 backgroundRewriteDoneHandler(statloc
);
597 updateDictResizePolicy();
600 /* If there is not a background saving in progress check if
601 * we have to save now */
602 time_t now
= time(NULL
);
603 for (j
= 0; j
< server
.saveparamslen
; j
++) {
604 struct saveparam
*sp
= server
.saveparams
+j
;
606 if (server
.dirty
>= sp
->changes
&&
607 now
-server
.lastsave
> sp
->seconds
) {
608 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
609 sp
->changes
, sp
->seconds
);
610 rdbSaveBackground(server
.dbfilename
);
616 /* Expire a few keys per cycle, only if this is a master.
617 * On slaves we wait for DEL operations synthesized by the master
618 * in order to guarantee a strict consistency. */
619 if (server
.masterhost
== NULL
) activeExpireCycle();
621 /* Remove a few cached objects from memory if we are over the
622 * configured memory limit */
623 while (server
.ds_enabled
&& zmalloc_used_memory() >
624 server
.cache_max_memory
)
626 if (cacheFreeOneEntry() == REDIS_ERR
) break;
629 /* Replication cron function -- used to reconnect to master and
630 * to detect transfer failures. */
631 if (!(loops
% 10)) replicationCron();
636 /* This function gets called every time Redis is entering the
637 * main loop of the event driven library, that is, before to sleep
638 * for ready file descriptors. */
639 void beforeSleep(struct aeEventLoop
*eventLoop
) {
640 REDIS_NOTUSED(eventLoop
);
644 /* Awake clients that got all the on disk keys they requested */
645 if (server
.ds_enabled
&& listLength(server
.io_ready_clients
)) {
648 listRewind(server
.io_ready_clients
,&li
);
649 while((ln
= listNext(&li
))) {
651 struct redisCommand
*cmd
;
653 /* Resume the client. */
654 listDelNode(server
.io_ready_clients
,ln
);
655 c
->flags
&= (~REDIS_IO_WAIT
);
656 server
.cache_blocked_clients
--;
657 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
658 readQueryFromClient
, c
);
659 cmd
= lookupCommand(c
->argv
[0]->ptr
);
660 redisAssert(cmd
!= NULL
);
663 /* There may be more data to process in the input buffer. */
664 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
665 processInputBuffer(c
);
669 /* Try to process pending commands for clients that were just unblocked. */
670 while (listLength(server
.unblocked_clients
)) {
671 ln
= listFirst(server
.unblocked_clients
);
672 redisAssert(ln
!= NULL
);
674 listDelNode(server
.unblocked_clients
,ln
);
676 /* Process remaining data in the input buffer. */
677 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
678 processInputBuffer(c
);
681 /* Write the AOF buffer on disk */
682 flushAppendOnlyFile();
685 /* =========================== Server initialization ======================== */
687 void createSharedObjects(void) {
690 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
691 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
692 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
693 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
694 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
695 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
696 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
697 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
698 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
699 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
700 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
701 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
702 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
703 "-ERR Operation against a key holding the wrong kind of value\r\n"));
704 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
705 "-ERR no such key\r\n"));
706 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
707 "-ERR syntax error\r\n"));
708 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
709 "-ERR source and destination objects are the same\r\n"));
710 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
711 "-ERR index out of range\r\n"));
712 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
713 "-LOADING Redis is loading the dataset in memory\r\n"));
714 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
715 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
716 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
717 shared
.select0
= createStringObject("select 0\r\n",10);
718 shared
.select1
= createStringObject("select 1\r\n",10);
719 shared
.select2
= createStringObject("select 2\r\n",10);
720 shared
.select3
= createStringObject("select 3\r\n",10);
721 shared
.select4
= createStringObject("select 4\r\n",10);
722 shared
.select5
= createStringObject("select 5\r\n",10);
723 shared
.select6
= createStringObject("select 6\r\n",10);
724 shared
.select7
= createStringObject("select 7\r\n",10);
725 shared
.select8
= createStringObject("select 8\r\n",10);
726 shared
.select9
= createStringObject("select 9\r\n",10);
727 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
728 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
729 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
730 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
731 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
732 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
733 shared
.mbulk3
= createStringObject("*3\r\n",4);
734 shared
.mbulk4
= createStringObject("*4\r\n",4);
735 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
736 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
737 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
741 void initServerConfig() {
742 server
.port
= REDIS_SERVERPORT
;
743 server
.bindaddr
= NULL
;
744 server
.unixsocket
= NULL
;
747 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
748 server
.verbosity
= REDIS_VERBOSE
;
749 server
.maxidletime
= REDIS_MAXIDLETIME
;
750 server
.saveparams
= NULL
;
752 server
.logfile
= NULL
; /* NULL = log on standard output */
753 server
.syslog_enabled
= 0;
754 server
.syslog_ident
= zstrdup("redis");
755 server
.syslog_facility
= LOG_LOCAL0
;
756 server
.glueoutputbuf
= 1;
757 server
.daemonize
= 0;
758 server
.appendonly
= 0;
759 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
760 server
.no_appendfsync_on_rewrite
= 0;
761 server
.lastfsync
= time(NULL
);
762 server
.appendfd
= -1;
763 server
.appendseldb
= -1; /* Make sure the first time will not match */
764 server
.pidfile
= zstrdup("/var/run/redis.pid");
765 server
.dbfilename
= zstrdup("dump.rdb");
766 server
.appendfilename
= zstrdup("appendonly.aof");
767 server
.requirepass
= NULL
;
768 server
.rdbcompression
= 1;
769 server
.activerehashing
= 1;
770 server
.maxclients
= 0;
771 server
.bpop_blocked_clients
= 0;
772 server
.maxmemory
= 0;
773 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
774 server
.maxmemory_samples
= 3;
775 server
.ds_enabled
= 0;
776 server
.ds_path
= zstrdup("/tmp/redis.ds");
777 server
.cache_max_memory
= 64LL*1024*1024; /* 64 MB of RAM */
778 server
.cache_blocked_clients
= 0;
779 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
780 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
781 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
782 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
783 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
784 server
.shutdown_asap
= 0;
787 resetServerSaveParams();
789 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
790 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
791 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
792 /* Replication related */
794 server
.masterauth
= NULL
;
795 server
.masterhost
= NULL
;
796 server
.masterport
= 6379;
797 server
.master
= NULL
;
798 server
.replstate
= REDIS_REPL_NONE
;
799 server
.repl_serve_stale_data
= 1;
801 /* Double constants initialization */
803 R_PosInf
= 1.0/R_Zero
;
804 R_NegInf
= -1.0/R_Zero
;
805 R_Nan
= R_Zero
/R_Zero
;
807 /* Command table -- we intiialize it here as it is part of the
808 * initial configuration, since command names may be changed via
809 * redis.conf using the rename-command directive. */
810 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
811 populateCommandTable();
812 server
.delCommand
= lookupCommandByCString("del");
813 server
.multiCommand
= lookupCommandByCString("multi");
819 signal(SIGHUP
, SIG_IGN
);
820 signal(SIGPIPE
, SIG_IGN
);
821 setupSigSegvAction();
823 if (server
.syslog_enabled
) {
824 openlog(server
.syslog_ident
, LOG_PID
| LOG_NDELAY
| LOG_NOWAIT
,
825 server
.syslog_facility
);
828 server
.mainthread
= pthread_self();
829 server
.clients
= listCreate();
830 server
.slaves
= listCreate();
831 server
.monitors
= listCreate();
832 server
.unblocked_clients
= listCreate();
833 server
.cache_flush_queue
= listCreate();
834 server
.cache_flush_delay
= 0;
836 createSharedObjects();
837 server
.el
= aeCreateEventLoop();
838 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
839 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
840 if (server
.ipfd
== ANET_ERR
) {
841 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
844 if (server
.unixsocket
!= NULL
) {
845 unlink(server
.unixsocket
); /* don't care if this fails */
846 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
847 if (server
.sofd
== ANET_ERR
) {
848 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
852 if (server
.ipfd
< 0 && server
.sofd
< 0) {
853 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
856 for (j
= 0; j
< server
.dbnum
; j
++) {
857 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
858 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
859 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
860 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
861 if (server
.ds_enabled
)
862 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
865 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
866 server
.pubsub_patterns
= listCreate();
867 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
868 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
869 server
.cronloops
= 0;
870 server
.bgsavechildpid
= -1;
871 server
.bgrewritechildpid
= -1;
872 server
.bgrewritebuf
= sdsempty();
873 server
.aofbuf
= sdsempty();
874 server
.lastsave
= time(NULL
);
876 server
.stat_numcommands
= 0;
877 server
.stat_numconnections
= 0;
878 server
.stat_expiredkeys
= 0;
879 server
.stat_evictedkeys
= 0;
880 server
.stat_starttime
= time(NULL
);
881 server
.stat_keyspace_misses
= 0;
882 server
.stat_keyspace_hits
= 0;
883 server
.unixtime
= time(NULL
);
884 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
885 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
886 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
887 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
888 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
890 if (server
.appendonly
) {
891 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
892 if (server
.appendfd
== -1) {
893 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
899 if (server
.ds_enabled
) dsInit();
902 /* Populates the Redis Command Table starting from the hard coded list
903 * we have on top of redis.c file. */
904 void populateCommandTable(void) {
906 int numcommands
= sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
);
908 for (j
= 0; j
< numcommands
; j
++) {
909 struct redisCommand
*c
= readonlyCommandTable
+j
;
912 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
913 assert(retval
== DICT_OK
);
917 /* ====================== Commands lookup and execution ===================== */
919 struct redisCommand
*lookupCommand(sds name
) {
920 return dictFetchValue(server
.commands
, name
);
923 struct redisCommand
*lookupCommandByCString(char *s
) {
924 struct redisCommand
*cmd
;
925 sds name
= sdsnew(s
);
927 cmd
= dictFetchValue(server
.commands
, name
);
932 /* Call() is the core of Redis execution of a command */
933 void call(redisClient
*c
, struct redisCommand
*cmd
) {
936 dirty
= server
.dirty
;
938 dirty
= server
.dirty
-dirty
;
940 if (server
.appendonly
&& dirty
)
941 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
942 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
943 listLength(server
.slaves
))
944 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
945 if (listLength(server
.monitors
))
946 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
947 server
.stat_numcommands
++;
950 /* If this function gets called we already read a whole
951 * command, argments are in the client argv/argc fields.
952 * processCommand() execute the command or prepare the
953 * server for a bulk read from the client.
955 * If 1 is returned the client is still alive and valid and
956 * and other operations can be performed by the caller. Otherwise
957 * if 0 is returned the client was destroied (i.e. after QUIT). */
958 int processCommand(redisClient
*c
) {
959 struct redisCommand
*cmd
;
961 /* The QUIT command is handled separately. Normal command procs will
962 * go through checking for replication and QUIT will cause trouble
963 * when FORCE_REPLICATION is enabled and would be implemented in
964 * a regular command proc. */
965 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
966 addReply(c
,shared
.ok
);
967 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
971 /* Now lookup the command and check ASAP about trivial error conditions
972 * such wrong arity, bad command name and so forth. */
973 cmd
= lookupCommand(c
->argv
[0]->ptr
);
975 addReplyErrorFormat(c
,"unknown command '%s'",
976 (char*)c
->argv
[0]->ptr
);
978 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
979 (c
->argc
< -cmd
->arity
)) {
980 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
985 /* Check if the user is authenticated */
986 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
987 addReplyError(c
,"operation not permitted");
991 /* Handle the maxmemory directive.
993 * First we try to free some memory if possible (if there are volatile
994 * keys in the dataset). If there are not the only thing we can do
995 * is returning an error. */
996 if (server
.maxmemory
) freeMemoryIfNeeded();
997 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
998 zmalloc_used_memory() > server
.maxmemory
)
1000 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1004 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1005 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1007 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
1008 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
1009 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1013 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1014 * we are a slave with a broken link with master. */
1015 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1016 server
.repl_serve_stale_data
== 0 &&
1017 cmd
->proc
!= infoCommand
&& cmd
->proc
!= slaveofCommand
)
1020 "link with MASTER is down and slave-serve-stale-data is set to no");
1024 /* Loading DB? Return an error if the command is not INFO */
1025 if (server
.loading
&& cmd
->proc
!= infoCommand
) {
1026 addReply(c
, shared
.loadingerr
);
1030 /* Exec the command */
1031 if (c
->flags
& REDIS_MULTI
&&
1032 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
1033 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
1035 queueMultiCommand(c
,cmd
);
1036 addReply(c
,shared
.queued
);
1038 if (server
.ds_enabled
&& blockClientOnSwappedKeys(c
,cmd
))
1045 /*================================== Shutdown =============================== */
1047 int prepareForShutdown() {
1048 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1049 /* Kill the saving child if there is a background saving in progress.
1050 We want to avoid race conditions, for instance our saving child may
1051 overwrite the synchronous saving did by SHUTDOWN. */
1052 if (server
.bgsavechildpid
!= -1) {
1053 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
1054 kill(server
.bgsavechildpid
,SIGKILL
);
1055 rdbRemoveTempFile(server
.bgsavechildpid
);
1057 if (server
.appendonly
) {
1058 /* Append only file: fsync() the AOF and exit */
1059 aof_fsync(server
.appendfd
);
1060 } else if (server
.saveparamslen
> 0) {
1061 /* Snapshotting. Perform a SYNC SAVE and exit */
1062 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1063 /* Ooops.. error saving! The best we can do is to continue
1064 * operating. Note that if there was a background saving process,
1065 * in the next cron() Redis will be notified that the background
1066 * saving aborted, handling special stuff like slaves pending for
1067 * synchronization... */
1068 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1072 redisLog(REDIS_WARNING
,"Not saving DB.");
1074 if (server
.daemonize
) unlink(server
.pidfile
);
1075 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1079 /*================================== Commands =============================== */
1081 void authCommand(redisClient
*c
) {
1082 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1083 c
->authenticated
= 1;
1084 addReply(c
,shared
.ok
);
1086 c
->authenticated
= 0;
1087 addReplyError(c
,"invalid password");
1091 void pingCommand(redisClient
*c
) {
1092 addReply(c
,shared
.pong
);
1095 void echoCommand(redisClient
*c
) {
1096 addReplyBulk(c
,c
->argv
[1]);
1099 /* Convert an amount of bytes into a human readable string in the form
1100 * of 100B, 2G, 100M, 4K, and so forth. */
1101 void bytesToHuman(char *s
, unsigned long long n
) {
1106 sprintf(s
,"%lluB",n
);
1108 } else if (n
< (1024*1024)) {
1109 d
= (double)n
/(1024);
1110 sprintf(s
,"%.2fK",d
);
1111 } else if (n
< (1024LL*1024*1024)) {
1112 d
= (double)n
/(1024*1024);
1113 sprintf(s
,"%.2fM",d
);
1114 } else if (n
< (1024LL*1024*1024*1024)) {
1115 d
= (double)n
/(1024LL*1024*1024);
1116 sprintf(s
,"%.2fG",d
);
1120 /* Create the string returned by the INFO command. This is decoupled
1121 * by the INFO command itself as we need to report the same information
1122 * on memory corruption problems. */
1123 sds
genRedisInfoString(void) {
1125 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1128 struct rusage self_ru
, c_ru
;
1130 getrusage(RUSAGE_SELF
, &self_ru
);
1131 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1133 bytesToHuman(hmem
,zmalloc_used_memory());
1134 info
= sdscatprintf(sdsempty(),
1135 "redis_version:%s\r\n"
1136 "redis_git_sha1:%s\r\n"
1137 "redis_git_dirty:%d\r\n"
1139 "multiplexing_api:%s\r\n"
1140 "process_id:%ld\r\n"
1141 "uptime_in_seconds:%ld\r\n"
1142 "uptime_in_days:%ld\r\n"
1144 "used_cpu_sys:%.2f\r\n"
1145 "used_cpu_user:%.2f\r\n"
1146 "used_cpu_sys_childrens:%.2f\r\n"
1147 "used_cpu_user_childrens:%.2f\r\n"
1148 "connected_clients:%d\r\n"
1149 "connected_slaves:%d\r\n"
1150 "blocked_clients:%d\r\n"
1151 "used_memory:%zu\r\n"
1152 "used_memory_human:%s\r\n"
1153 "used_memory_rss:%zu\r\n"
1154 "mem_fragmentation_ratio:%.2f\r\n"
1155 "use_tcmalloc:%d\r\n"
1157 "aof_enabled:%d\r\n"
1158 "changes_since_last_save:%lld\r\n"
1159 "bgsave_in_progress:%d\r\n"
1160 "last_save_time:%ld\r\n"
1161 "bgrewriteaof_in_progress:%d\r\n"
1162 "total_connections_received:%lld\r\n"
1163 "total_commands_processed:%lld\r\n"
1164 "expired_keys:%lld\r\n"
1165 "evicted_keys:%lld\r\n"
1166 "keyspace_hits:%lld\r\n"
1167 "keyspace_misses:%lld\r\n"
1168 "hash_max_zipmap_entries:%zu\r\n"
1169 "hash_max_zipmap_value:%zu\r\n"
1170 "pubsub_channels:%ld\r\n"
1171 "pubsub_patterns:%u\r\n"
1176 strtol(redisGitDirty(),NULL
,10) > 0,
1177 (sizeof(long) == 8) ? "64" : "32",
1182 (unsigned long) server
.lruclock
,
1183 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1184 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1185 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1186 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1187 listLength(server
.clients
)-listLength(server
.slaves
),
1188 listLength(server
.slaves
),
1189 server
.bpop_blocked_clients
,
1190 zmalloc_used_memory(),
1193 zmalloc_get_fragmentation_ratio(),
1202 server
.bgsavechildpid
!= -1,
1204 server
.bgrewritechildpid
!= -1,
1205 server
.stat_numconnections
,
1206 server
.stat_numcommands
,
1207 server
.stat_expiredkeys
,
1208 server
.stat_evictedkeys
,
1209 server
.stat_keyspace_hits
,
1210 server
.stat_keyspace_misses
,
1211 server
.hash_max_zipmap_entries
,
1212 server
.hash_max_zipmap_value
,
1213 dictSize(server
.pubsub_channels
),
1214 listLength(server
.pubsub_patterns
),
1215 server
.ds_enabled
!= 0,
1216 server
.masterhost
== NULL
? "master" : "slave"
1218 if (server
.masterhost
) {
1219 info
= sdscatprintf(info
,
1220 "master_host:%s\r\n"
1221 "master_port:%d\r\n"
1222 "master_link_status:%s\r\n"
1223 "master_last_io_seconds_ago:%d\r\n"
1224 "master_sync_in_progress:%d\r\n"
1227 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1229 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1230 server
.replstate
== REDIS_REPL_TRANSFER
1233 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1234 info
= sdscatprintf(info
,
1235 "master_sync_left_bytes:%ld\r\n"
1236 "master_sync_last_io_seconds_ago:%d\r\n"
1237 ,(long)server
.repl_transfer_left
,
1238 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1242 if (server
.ds_enabled
) {
1244 info
= sdscatprintf(info
,
1245 "cache_max_memory:%llu\r\n"
1246 "cache_blocked_clients:%lu\r\n"
1247 ,(unsigned long long) server
.cache_max_memory
,
1248 (unsigned long) server
.cache_blocked_clients
1252 if (server
.loading
) {
1254 time_t eta
, elapsed
;
1255 off_t remaining_bytes
= server
.loading_total_bytes
-
1256 server
.loading_loaded_bytes
;
1258 perc
= ((double)server
.loading_loaded_bytes
/
1259 server
.loading_total_bytes
) * 100;
1261 elapsed
= time(NULL
)-server
.loading_start_time
;
1263 eta
= 1; /* A fake 1 second figure if we don't have enough info */
1265 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1268 info
= sdscatprintf(info
,
1269 "loading_start_time:%ld\r\n"
1270 "loading_total_bytes:%llu\r\n"
1271 "loading_loaded_bytes:%llu\r\n"
1272 "loading_loaded_perc:%.2f\r\n"
1273 "loading_eta_seconds:%ld\r\n"
1274 ,(unsigned long) server
.loading_start_time
,
1275 (unsigned long long) server
.loading_total_bytes
,
1276 (unsigned long long) server
.loading_loaded_bytes
,
1281 for (j
= 0; j
< server
.dbnum
; j
++) {
1282 long long keys
, vkeys
;
1284 keys
= dictSize(server
.db
[j
].dict
);
1285 vkeys
= dictSize(server
.db
[j
].expires
);
1286 if (keys
|| vkeys
) {
1287 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1294 void infoCommand(redisClient
*c
) {
1295 sds info
= genRedisInfoString();
1296 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1297 (unsigned long)sdslen(info
)));
1298 addReplySds(c
,info
);
1299 addReply(c
,shared
.crlf
);
1302 void monitorCommand(redisClient
*c
) {
1303 /* ignore MONITOR if aleady slave or in monitor mode */
1304 if (c
->flags
& REDIS_SLAVE
) return;
1306 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1308 listAddNodeTail(server
.monitors
,c
);
1309 addReply(c
,shared
.ok
);
1312 /* ============================ Maxmemory directive ======================== */
1314 /* This function gets called when 'maxmemory' is set on the config file to limit
1315 * the max memory used by the server, and we are out of memory.
1316 * This function will try to, in order:
1318 * - Free objects from the free list
1319 * - Try to remove keys with an EXPIRE set
1321 * It is not possible to free enough memory to reach used-memory < maxmemory
1322 * the server will start refusing commands that will enlarge even more the
1325 void freeMemoryIfNeeded(void) {
1326 /* Remove keys accordingly to the active policy as long as we are
1327 * over the memory limit. */
1328 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1330 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1331 int j
, k
, freed
= 0;
1333 for (j
= 0; j
< server
.dbnum
; j
++) {
1334 long bestval
= 0; /* just to prevent warning */
1336 struct dictEntry
*de
;
1337 redisDb
*db
= server
.db
+j
;
1340 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1341 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1343 dict
= server
.db
[j
].dict
;
1345 dict
= server
.db
[j
].expires
;
1347 if (dictSize(dict
) == 0) continue;
1349 /* volatile-random and allkeys-random policy */
1350 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1351 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1353 de
= dictGetRandomKey(dict
);
1354 bestkey
= dictGetEntryKey(de
);
1357 /* volatile-lru and allkeys-lru policy */
1358 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1359 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1361 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1366 de
= dictGetRandomKey(dict
);
1367 thiskey
= dictGetEntryKey(de
);
1368 /* When policy is volatile-lru we need an additonal lookup
1369 * to locate the real key, as dict is set to db->expires. */
1370 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1371 de
= dictFind(db
->dict
, thiskey
);
1372 o
= dictGetEntryVal(de
);
1373 thisval
= estimateObjectIdleTime(o
);
1375 /* Higher idle time is better candidate for deletion */
1376 if (bestkey
== NULL
|| thisval
> bestval
) {
1384 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1385 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1389 de
= dictGetRandomKey(dict
);
1390 thiskey
= dictGetEntryKey(de
);
1391 thisval
= (long) dictGetEntryVal(de
);
1393 /* Expire sooner (minor expire unix timestamp) is better
1394 * candidate for deletion */
1395 if (bestkey
== NULL
|| thisval
< bestval
) {
1402 /* Finally remove the selected key. */
1404 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1405 dbDelete(db
,keyobj
);
1406 server
.stat_evictedkeys
++;
1407 decrRefCount(keyobj
);
1411 if (!freed
) return; /* nothing to free... */
1415 /* =================================== Main! ================================ */
1418 int linuxOvercommitMemoryValue(void) {
1419 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1423 if (fgets(buf
,64,fp
) == NULL
) {
1432 void linuxOvercommitMemoryWarning(void) {
1433 if (linuxOvercommitMemoryValue() == 0) {
1434 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.");
1437 #endif /* __linux__ */
1439 void createPidFile(void) {
1440 /* Try to write the pid file in a best-effort way. */
1441 FILE *fp
= fopen(server
.pidfile
,"w");
1443 fprintf(fp
,"%d\n",getpid());
1448 void daemonize(void) {
1451 if (fork() != 0) exit(0); /* parent exits */
1452 setsid(); /* create a new session */
1454 /* Every output goes to /dev/null. If Redis is daemonized but
1455 * the 'logfile' is set to 'stdout' in the configuration file
1456 * it will not log at all. */
1457 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1458 dup2(fd
, STDIN_FILENO
);
1459 dup2(fd
, STDOUT_FILENO
);
1460 dup2(fd
, STDERR_FILENO
);
1461 if (fd
> STDERR_FILENO
) close(fd
);
1466 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1467 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1472 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1473 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1477 int main(int argc
, char **argv
) {
1482 if (strcmp(argv
[1], "-v") == 0 ||
1483 strcmp(argv
[1], "--version") == 0) version();
1484 if (strcmp(argv
[1], "--help") == 0) usage();
1485 resetServerSaveParams();
1486 loadServerConfig(argv
[1]);
1487 } else if ((argc
> 2)) {
1490 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'");
1492 if (server
.daemonize
) daemonize();
1494 if (server
.daemonize
) createPidFile();
1495 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1497 linuxOvercommitMemoryWarning();
1500 if (server
.appendonly
) {
1501 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1502 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
1504 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1505 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
1507 if (server
.ipfd
> 0)
1508 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1509 if (server
.sofd
> 0)
1510 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1511 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1513 aeDeleteEventLoop(server
.el
);
1517 /* ============================= Backtrace support ========================= */
1519 #ifdef HAVE_BACKTRACE
1520 void *getMcontextEip(ucontext_t
*uc
) {
1521 #if defined(__FreeBSD__)
1522 return (void*) uc
->uc_mcontext
.mc_eip
;
1523 #elif defined(__dietlibc__)
1524 return (void*) uc
->uc_mcontext
.eip
;
1525 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1527 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1529 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1531 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1532 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1533 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1535 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1537 #elif defined(__i386__)
1538 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1539 #elif defined(__X86_64__) || defined(__x86_64__)
1540 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1541 #elif defined(__ia64__) /* Linux IA64 */
1542 return (void*) uc
->uc_mcontext
.sc_ip
;
1548 void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1550 char **messages
= NULL
;
1551 int i
, trace_size
= 0;
1552 ucontext_t
*uc
= (ucontext_t
*) secret
;
1554 struct sigaction act
;
1555 REDIS_NOTUSED(info
);
1557 redisLog(REDIS_WARNING
,
1558 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1559 infostring
= genRedisInfoString();
1560 redisLog(REDIS_WARNING
, "%s",infostring
);
1561 /* It's not safe to sdsfree() the returned string under memory
1562 * corruption conditions. Let it leak as we are going to abort */
1564 trace_size
= backtrace(trace
, 100);
1565 /* overwrite sigaction with caller's address */
1566 if (getMcontextEip(uc
) != NULL
) {
1567 trace
[1] = getMcontextEip(uc
);
1569 messages
= backtrace_symbols(trace
, trace_size
);
1571 for (i
=1; i
<trace_size
; ++i
)
1572 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1574 /* free(messages); Don't call free() with possibly corrupted memory. */
1575 if (server
.daemonize
) unlink(server
.pidfile
);
1577 /* Make sure we exit with the right signal at the end. So for instance
1578 * the core will be dumped if enabled. */
1579 sigemptyset (&act
.sa_mask
);
1580 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1581 * is used. Otherwise, sa_handler is used */
1582 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1583 act
.sa_handler
= SIG_DFL
;
1584 sigaction (sig
, &act
, NULL
);
1588 void sigtermHandler(int sig
) {
1591 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
1592 server
.shutdown_asap
= 1;
1595 void setupSigSegvAction(void) {
1596 struct sigaction act
;
1598 sigemptyset (&act
.sa_mask
);
1599 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1600 * is used. Otherwise, sa_handler is used */
1601 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1602 act
.sa_sigaction
= segvHandler
;
1603 sigaction (SIGSEGV
, &act
, NULL
);
1604 sigaction (SIGBUS
, &act
, NULL
);
1605 sigaction (SIGFPE
, &act
, NULL
);
1606 sigaction (SIGILL
, &act
, NULL
);
1607 sigaction (SIGBUS
, &act
, NULL
);
1609 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1610 act
.sa_handler
= sigtermHandler
;
1611 sigaction (SIGTERM
, &act
, NULL
);
1615 #else /* HAVE_BACKTRACE */
1616 void setupSigSegvAction(void) {
1618 #endif /* HAVE_BACKTRACE */