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
, ...) {
202 if (level
< server
.verbosity
) return;
204 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
209 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
210 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
211 vfprintf(fp
, fmt
, ap
);
216 if (server
.logfile
) fclose(fp
);
219 /* Redis generally does not try to recover from out of memory conditions
220 * when allocating objects or strings, it is not clear if it will be possible
221 * to report this condition to the client since the networking layer itself
222 * is based on heap allocation for send buffers, so we simply abort.
223 * At least the code will be simpler to read... */
224 void oom(const char *msg
) {
225 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
230 /*====================== Hash table type implementation ==================== */
232 /* This is an hash table type that uses the SDS dynamic strings libary as
233 * keys and radis objects as values (objects can hold SDS strings,
236 void dictVanillaFree(void *privdata
, void *val
)
238 DICT_NOTUSED(privdata
);
242 void dictListDestructor(void *privdata
, void *val
)
244 DICT_NOTUSED(privdata
);
245 listRelease((list
*)val
);
248 int dictSdsKeyCompare(void *privdata
, const void *key1
,
252 DICT_NOTUSED(privdata
);
254 l1
= sdslen((sds
)key1
);
255 l2
= sdslen((sds
)key2
);
256 if (l1
!= l2
) return 0;
257 return memcmp(key1
, key2
, l1
) == 0;
260 /* A case insensitive version used for the command lookup table. */
261 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
264 DICT_NOTUSED(privdata
);
266 return strcasecmp(key1
, key2
) == 0;
269 void dictRedisObjectDestructor(void *privdata
, void *val
)
271 DICT_NOTUSED(privdata
);
273 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
277 void dictSdsDestructor(void *privdata
, void *val
)
279 DICT_NOTUSED(privdata
);
284 int dictObjKeyCompare(void *privdata
, const void *key1
,
287 const robj
*o1
= key1
, *o2
= key2
;
288 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
291 unsigned int dictObjHash(const void *key
) {
293 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
296 unsigned int dictSdsHash(const void *key
) {
297 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
300 unsigned int dictSdsCaseHash(const void *key
) {
301 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
304 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
307 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
310 if (o1
->encoding
== REDIS_ENCODING_INT
&&
311 o2
->encoding
== REDIS_ENCODING_INT
)
312 return o1
->ptr
== o2
->ptr
;
314 o1
= getDecodedObject(o1
);
315 o2
= getDecodedObject(o2
);
316 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
322 unsigned int dictEncObjHash(const void *key
) {
323 robj
*o
= (robj
*) key
;
325 if (o
->encoding
== REDIS_ENCODING_RAW
) {
326 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
328 if (o
->encoding
== REDIS_ENCODING_INT
) {
332 len
= ll2string(buf
,32,(long)o
->ptr
);
333 return dictGenHashFunction((unsigned char*)buf
, len
);
337 o
= getDecodedObject(o
);
338 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
346 dictType setDictType
= {
347 dictEncObjHash
, /* hash function */
350 dictEncObjKeyCompare
, /* key compare */
351 dictRedisObjectDestructor
, /* key destructor */
352 NULL
/* val destructor */
355 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
356 dictType zsetDictType
= {
357 dictEncObjHash
, /* hash function */
360 dictEncObjKeyCompare
, /* key compare */
361 dictRedisObjectDestructor
, /* key destructor */
362 NULL
/* val destructor */
365 /* Db->dict, keys are sds strings, vals are Redis objects. */
366 dictType dbDictType
= {
367 dictSdsHash
, /* hash function */
370 dictSdsKeyCompare
, /* key compare */
371 dictSdsDestructor
, /* key destructor */
372 dictRedisObjectDestructor
/* val destructor */
376 dictType keyptrDictType
= {
377 dictSdsHash
, /* hash function */
380 dictSdsKeyCompare
, /* key compare */
381 NULL
, /* key destructor */
382 NULL
/* val destructor */
385 /* Command table. sds string -> command struct pointer. */
386 dictType commandTableDictType
= {
387 dictSdsCaseHash
, /* hash function */
390 dictSdsKeyCaseCompare
, /* key compare */
391 dictSdsDestructor
, /* key destructor */
392 NULL
/* val destructor */
395 /* Hash type hash table (note that small hashes are represented with zimpaps) */
396 dictType hashDictType
= {
397 dictEncObjHash
, /* hash function */
400 dictEncObjKeyCompare
, /* key compare */
401 dictRedisObjectDestructor
, /* key destructor */
402 dictRedisObjectDestructor
/* val destructor */
405 /* Keylist hash table type has unencoded redis objects as keys and
406 * lists as values. It's used for blocking operations (BLPOP) and to
407 * map swapped keys to a list of clients waiting for this keys to be loaded. */
408 dictType keylistDictType
= {
409 dictObjHash
, /* hash function */
412 dictObjKeyCompare
, /* key compare */
413 dictRedisObjectDestructor
, /* key destructor */
414 dictListDestructor
/* val destructor */
417 int htNeedsResize(dict
*dict
) {
418 long long size
, used
;
420 size
= dictSlots(dict
);
421 used
= dictSize(dict
);
422 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
423 (used
*100/size
< REDIS_HT_MINFILL
));
426 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
427 * we resize the hash table to save memory */
428 void tryResizeHashTables(void) {
431 for (j
= 0; j
< server
.dbnum
; j
++) {
432 if (htNeedsResize(server
.db
[j
].dict
))
433 dictResize(server
.db
[j
].dict
);
434 if (htNeedsResize(server
.db
[j
].expires
))
435 dictResize(server
.db
[j
].expires
);
439 /* Our hash table implementation performs rehashing incrementally while
440 * we write/read from the hash table. Still if the server is idle, the hash
441 * table will use two tables for a long time. So we try to use 1 millisecond
442 * of CPU time at every serverCron() loop in order to rehash some key. */
443 void incrementallyRehash(void) {
446 for (j
= 0; j
< server
.dbnum
; j
++) {
447 if (dictIsRehashing(server
.db
[j
].dict
)) {
448 dictRehashMilliseconds(server
.db
[j
].dict
,1);
449 break; /* already used our millisecond for this loop... */
454 /* This function is called once a background process of some kind terminates,
455 * as we want to avoid resizing the hash tables when there is a child in order
456 * to play well with copy-on-write (otherwise when a resize happens lots of
457 * memory pages are copied). The goal of this function is to update the ability
458 * for dict.c to resize the hash tables accordingly to the fact we have o not
460 void updateDictResizePolicy(void) {
461 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
467 /* ======================= Cron: called every 100 ms ======================== */
469 /* Try to expire a few timed out keys. The algorithm used is adaptive and
470 * will use few CPU cycles if there are few expiring keys, otherwise
471 * it will get more aggressive to avoid that too much memory is used by
472 * keys that can be removed from the keyspace. */
473 void activeExpireCycle(void) {
476 for (j
= 0; j
< server
.dbnum
; j
++) {
478 redisDb
*db
= server
.db
+j
;
480 /* Continue to expire if at the end of the cycle more than 25%
481 * of the keys were expired. */
483 long num
= dictSize(db
->expires
);
484 time_t now
= time(NULL
);
487 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
488 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
493 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
494 t
= (time_t) dictGetEntryVal(de
);
496 sds key
= dictGetEntryKey(de
);
497 robj
*keyobj
= createStringObject(key
,sdslen(key
));
499 propagateExpire(db
,keyobj
);
501 decrRefCount(keyobj
);
503 server
.stat_expiredkeys
++;
506 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
510 void updateLRUClock(void) {
511 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
515 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
516 int j
, loops
= server
.cronloops
++;
517 REDIS_NOTUSED(eventLoop
);
519 REDIS_NOTUSED(clientData
);
521 /* We take a cached value of the unix time in the global state because
522 * with virtual memory and aging there is to store the current time
523 * in objects at every object access, and accuracy is not needed.
524 * To access a global var is faster than calling time(NULL) */
525 server
.unixtime
= time(NULL
);
526 /* We have just 22 bits per object for LRU information.
527 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
528 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
530 * Note that even if this will wrap after 1.5 years it's not a problem,
531 * everything will still work but just some object will appear younger
532 * to Redis. But for this to happen a given object should never be touched
535 * Note that you can change the resolution altering the
536 * REDIS_LRU_CLOCK_RESOLUTION define.
540 /* We received a SIGTERM, shutting down here in a safe way, as it is
541 * not ok doing so inside the signal handler. */
542 if (server
.shutdown_asap
) {
543 if (prepareForShutdown() == REDIS_OK
) exit(0);
544 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
547 /* Show some info about non-empty databases */
548 for (j
= 0; j
< server
.dbnum
; j
++) {
549 long long size
, used
, vkeys
;
551 size
= dictSlots(server
.db
[j
].dict
);
552 used
= dictSize(server
.db
[j
].dict
);
553 vkeys
= dictSize(server
.db
[j
].expires
);
554 if (!(loops
% 50) && (used
|| vkeys
)) {
555 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
556 /* dictPrintStats(server.dict); */
560 /* We don't want to resize the hash tables while a bacground saving
561 * is in progress: the saving child is created using fork() that is
562 * implemented with a copy-on-write semantic in most modern systems, so
563 * if we resize the HT while there is the saving child at work actually
564 * a lot of memory movements in the parent will cause a lot of pages
566 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
567 if (!(loops
% 10)) tryResizeHashTables();
568 if (server
.activerehashing
) incrementallyRehash();
571 /* Show information about connected clients */
573 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
574 listLength(server
.clients
)-listLength(server
.slaves
),
575 listLength(server
.slaves
),
576 zmalloc_used_memory());
579 /* Close connections of timedout clients */
580 if ((server
.maxidletime
&& !(loops
% 100)) || server
.bpop_blocked_clients
)
581 closeTimedoutClients();
583 /* Check if a background saving or AOF rewrite in progress terminated */
584 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
588 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
589 if (pid
== server
.bgsavechildpid
) {
590 backgroundSaveDoneHandler(statloc
);
592 backgroundRewriteDoneHandler(statloc
);
594 updateDictResizePolicy();
597 /* If there is not a background saving in progress check if
598 * we have to save now */
599 time_t now
= time(NULL
);
600 for (j
= 0; j
< server
.saveparamslen
; j
++) {
601 struct saveparam
*sp
= server
.saveparams
+j
;
603 if (server
.dirty
>= sp
->changes
&&
604 now
-server
.lastsave
> sp
->seconds
) {
605 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
606 sp
->changes
, sp
->seconds
);
607 rdbSaveBackground(server
.dbfilename
);
613 /* Expire a few keys per cycle, only if this is a master.
614 * On slaves we wait for DEL operations synthesized by the master
615 * in order to guarantee a strict consistency. */
616 if (server
.masterhost
== NULL
) activeExpireCycle();
618 /* Swap a few keys on disk if we are over the memory limit and VM
619 * is enbled. Try to free objects from the free list first. */
620 if (vmCanSwapOut()) {
621 while (server
.vm_enabled
&& zmalloc_used_memory() >
622 server
.vm_max_memory
)
624 int retval
= (server
.vm_max_threads
== 0) ?
625 vmSwapOneObjectBlocking() :
626 vmSwapOneObjectThreaded();
627 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
628 zmalloc_used_memory() >
629 (server
.vm_max_memory
+server
.vm_max_memory
/10))
631 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
633 /* Note that when using threade I/O we free just one object,
634 * because anyway when the I/O thread in charge to swap this
635 * object out will finish, the handler of completed jobs
636 * will try to swap more objects if we are still out of memory. */
637 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
641 /* Replication cron function -- used to reconnect to master and
642 * to detect transfer failures. */
643 if (!(loops
% 10)) replicationCron();
648 /* This function gets called every time Redis is entering the
649 * main loop of the event driven library, that is, before to sleep
650 * for ready file descriptors. */
651 void beforeSleep(struct aeEventLoop
*eventLoop
) {
652 REDIS_NOTUSED(eventLoop
);
656 /* Awake clients that got all the swapped keys they requested */
657 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
660 listRewind(server
.io_ready_clients
,&li
);
661 while((ln
= listNext(&li
))) {
663 struct redisCommand
*cmd
;
665 /* Resume the client. */
666 listDelNode(server
.io_ready_clients
,ln
);
667 c
->flags
&= (~REDIS_IO_WAIT
);
668 server
.vm_blocked_clients
--;
669 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
670 readQueryFromClient
, c
);
671 cmd
= lookupCommand(c
->argv
[0]->ptr
);
672 redisAssert(cmd
!= NULL
);
675 /* There may be more data to process in the input buffer. */
676 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
677 processInputBuffer(c
);
681 /* Try to process pending commands for clients that were just unblocked. */
682 while (listLength(server
.unblocked_clients
)) {
683 ln
= listFirst(server
.unblocked_clients
);
684 redisAssert(ln
!= NULL
);
686 listDelNode(server
.unblocked_clients
,ln
);
688 /* Process remaining data in the input buffer. */
689 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
690 processInputBuffer(c
);
693 /* Write the AOF buffer on disk */
694 flushAppendOnlyFile();
697 /* =========================== Server initialization ======================== */
699 void createSharedObjects(void) {
702 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
703 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
704 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
705 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
706 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
707 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
708 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
709 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
710 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
711 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
712 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
713 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
714 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
715 "-ERR Operation against a key holding the wrong kind of value\r\n"));
716 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
717 "-ERR no such key\r\n"));
718 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
719 "-ERR syntax error\r\n"));
720 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
721 "-ERR source and destination objects are the same\r\n"));
722 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
723 "-ERR index out of range\r\n"));
724 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
725 "-LOADING Redis is loading the dataset in memory\r\n"));
726 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
727 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
728 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
729 shared
.select0
= createStringObject("select 0\r\n",10);
730 shared
.select1
= createStringObject("select 1\r\n",10);
731 shared
.select2
= createStringObject("select 2\r\n",10);
732 shared
.select3
= createStringObject("select 3\r\n",10);
733 shared
.select4
= createStringObject("select 4\r\n",10);
734 shared
.select5
= createStringObject("select 5\r\n",10);
735 shared
.select6
= createStringObject("select 6\r\n",10);
736 shared
.select7
= createStringObject("select 7\r\n",10);
737 shared
.select8
= createStringObject("select 8\r\n",10);
738 shared
.select9
= createStringObject("select 9\r\n",10);
739 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
740 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
741 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
742 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
743 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
744 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
745 shared
.mbulk3
= createStringObject("*3\r\n",4);
746 shared
.mbulk4
= createStringObject("*4\r\n",4);
747 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
748 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
749 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
753 void initServerConfig() {
754 server
.port
= REDIS_SERVERPORT
;
755 server
.bindaddr
= NULL
;
756 server
.unixsocket
= NULL
;
759 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
760 server
.verbosity
= REDIS_VERBOSE
;
761 server
.maxidletime
= REDIS_MAXIDLETIME
;
762 server
.saveparams
= NULL
;
764 server
.logfile
= NULL
; /* NULL = log on standard output */
765 server
.glueoutputbuf
= 1;
766 server
.daemonize
= 0;
767 server
.appendonly
= 0;
768 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
769 server
.no_appendfsync_on_rewrite
= 0;
770 server
.lastfsync
= time(NULL
);
771 server
.appendfd
= -1;
772 server
.appendseldb
= -1; /* Make sure the first time will not match */
773 server
.pidfile
= zstrdup("/var/run/redis.pid");
774 server
.dbfilename
= zstrdup("dump.rdb");
775 server
.appendfilename
= zstrdup("appendonly.aof");
776 server
.requirepass
= NULL
;
777 server
.rdbcompression
= 1;
778 server
.activerehashing
= 1;
779 server
.maxclients
= 0;
780 server
.bpop_blocked_clients
= 0;
781 server
.maxmemory
= 0;
782 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
783 server
.maxmemory_samples
= 3;
784 server
.vm_enabled
= 0;
785 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
786 server
.vm_page_size
= 256; /* 256 bytes per page */
787 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
788 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
789 server
.vm_max_threads
= 4;
790 server
.vm_blocked_clients
= 0;
791 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
792 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
793 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
794 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
795 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
796 server
.shutdown_asap
= 0;
799 resetServerSaveParams();
801 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
802 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
803 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
804 /* Replication related */
806 server
.masterauth
= NULL
;
807 server
.masterhost
= NULL
;
808 server
.masterport
= 6379;
809 server
.master
= NULL
;
810 server
.replstate
= REDIS_REPL_NONE
;
811 server
.repl_serve_stale_data
= 1;
813 /* Double constants initialization */
815 R_PosInf
= 1.0/R_Zero
;
816 R_NegInf
= -1.0/R_Zero
;
817 R_Nan
= R_Zero
/R_Zero
;
819 /* Command table -- we intiialize it here as it is part of the
820 * initial configuration, since command names may be changed via
821 * redis.conf using the rename-command directive. */
822 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
823 populateCommandTable();
824 server
.delCommand
= lookupCommandByCString("del");
825 server
.multiCommand
= lookupCommandByCString("multi");
831 signal(SIGHUP
, SIG_IGN
);
832 signal(SIGPIPE
, SIG_IGN
);
833 setupSigSegvAction();
835 server
.mainthread
= pthread_self();
836 server
.clients
= listCreate();
837 server
.slaves
= listCreate();
838 server
.monitors
= listCreate();
839 server
.unblocked_clients
= listCreate();
840 createSharedObjects();
841 server
.el
= aeCreateEventLoop();
842 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
843 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
844 if (server
.ipfd
== ANET_ERR
) {
845 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
848 if (server
.unixsocket
!= NULL
) {
849 unlink(server
.unixsocket
); /* don't care if this fails */
850 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
851 if (server
.sofd
== ANET_ERR
) {
852 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
856 if (server
.ipfd
< 0 && server
.sofd
< 0) {
857 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
860 for (j
= 0; j
< server
.dbnum
; j
++) {
861 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
862 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
863 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
864 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
865 if (server
.vm_enabled
)
866 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
869 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
870 server
.pubsub_patterns
= listCreate();
871 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
872 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
873 server
.cronloops
= 0;
874 server
.bgsavechildpid
= -1;
875 server
.bgrewritechildpid
= -1;
876 server
.bgrewritebuf
= sdsempty();
877 server
.aofbuf
= sdsempty();
878 server
.lastsave
= time(NULL
);
880 server
.stat_numcommands
= 0;
881 server
.stat_numconnections
= 0;
882 server
.stat_expiredkeys
= 0;
883 server
.stat_starttime
= time(NULL
);
884 server
.stat_keyspace_misses
= 0;
885 server
.stat_keyspace_hits
= 0;
886 server
.unixtime
= time(NULL
);
887 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
888 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
889 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
890 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
891 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
893 if (server
.appendonly
) {
894 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
895 if (server
.appendfd
== -1) {
896 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
902 if (server
.vm_enabled
) vmInit();
905 /* Populates the Redis Command Table starting from the hard coded list
906 * we have on top of redis.c file. */
907 void populateCommandTable(void) {
909 int numcommands
= sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
);
911 for (j
= 0; j
< numcommands
; j
++) {
912 struct redisCommand
*c
= readonlyCommandTable
+j
;
915 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
916 assert(retval
== DICT_OK
);
920 /* ====================== Commands lookup and execution ===================== */
922 struct redisCommand
*lookupCommand(sds name
) {
923 return dictFetchValue(server
.commands
, name
);
926 struct redisCommand
*lookupCommandByCString(char *s
) {
927 struct redisCommand
*cmd
;
928 sds name
= sdsnew(s
);
930 cmd
= dictFetchValue(server
.commands
, name
);
935 /* Call() is the core of Redis execution of a command */
936 void call(redisClient
*c
, struct redisCommand
*cmd
) {
939 dirty
= server
.dirty
;
941 dirty
= server
.dirty
-dirty
;
943 if (server
.appendonly
&& dirty
)
944 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
945 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
946 listLength(server
.slaves
))
947 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
948 if (listLength(server
.monitors
))
949 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
950 server
.stat_numcommands
++;
953 /* If this function gets called we already read a whole
954 * command, argments are in the client argv/argc fields.
955 * processCommand() execute the command or prepare the
956 * server for a bulk read from the client.
958 * If 1 is returned the client is still alive and valid and
959 * and other operations can be performed by the caller. Otherwise
960 * if 0 is returned the client was destroied (i.e. after QUIT). */
961 int processCommand(redisClient
*c
) {
962 struct redisCommand
*cmd
;
964 /* The QUIT command is handled separately. Normal command procs will
965 * go through checking for replication and QUIT will cause trouble
966 * when FORCE_REPLICATION is enabled and would be implemented in
967 * a regular command proc. */
968 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
969 addReply(c
,shared
.ok
);
970 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
974 /* Now lookup the command and check ASAP about trivial error conditions
975 * such wrong arity, bad command name and so forth. */
976 cmd
= lookupCommand(c
->argv
[0]->ptr
);
978 addReplyErrorFormat(c
,"unknown command '%s'",
979 (char*)c
->argv
[0]->ptr
);
981 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
982 (c
->argc
< -cmd
->arity
)) {
983 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
988 /* Check if the user is authenticated */
989 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
990 addReplyError(c
,"operation not permitted");
994 /* Handle the maxmemory directive.
996 * First we try to free some memory if possible (if there are volatile
997 * keys in the dataset). If there are not the only thing we can do
998 * is returning an error. */
999 if (server
.maxmemory
) freeMemoryIfNeeded();
1000 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
1001 zmalloc_used_memory() > server
.maxmemory
)
1003 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
1007 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1008 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
1010 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
1011 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
1012 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1016 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1017 * we are a slave with a broken link with master. */
1018 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1019 server
.repl_serve_stale_data
== 0 &&
1020 cmd
->proc
!= infoCommand
&& cmd
->proc
!= slaveofCommand
)
1023 "link with MASTER is down and slave-serve-stale-data is set to no");
1027 /* Loading DB? Return an error if the command is not INFO */
1028 if (server
.loading
&& cmd
->proc
!= infoCommand
) {
1029 addReply(c
, shared
.loadingerr
);
1033 /* Exec the command */
1034 if (c
->flags
& REDIS_MULTI
&&
1035 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
1036 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
1038 queueMultiCommand(c
,cmd
);
1039 addReply(c
,shared
.queued
);
1041 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
1042 blockClientOnSwappedKeys(c
,cmd
)) return REDIS_ERR
;
1048 /*================================== Shutdown =============================== */
1050 int prepareForShutdown() {
1051 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1052 /* Kill the saving child if there is a background saving in progress.
1053 We want to avoid race conditions, for instance our saving child may
1054 overwrite the synchronous saving did by SHUTDOWN. */
1055 if (server
.bgsavechildpid
!= -1) {
1056 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
1057 kill(server
.bgsavechildpid
,SIGKILL
);
1058 rdbRemoveTempFile(server
.bgsavechildpid
);
1060 if (server
.appendonly
) {
1061 /* Append only file: fsync() the AOF and exit */
1062 aof_fsync(server
.appendfd
);
1063 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
1064 } else if (server
.saveparamslen
> 0) {
1065 /* Snapshotting. Perform a SYNC SAVE and exit */
1066 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1067 /* Ooops.. error saving! The best we can do is to continue
1068 * operating. Note that if there was a background saving process,
1069 * in the next cron() Redis will be notified that the background
1070 * saving aborted, handling special stuff like slaves pending for
1071 * synchronization... */
1072 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1076 redisLog(REDIS_WARNING
,"Not saving DB.");
1078 if (server
.daemonize
) unlink(server
.pidfile
);
1079 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1083 /*================================== Commands =============================== */
1085 void authCommand(redisClient
*c
) {
1086 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1087 c
->authenticated
= 1;
1088 addReply(c
,shared
.ok
);
1090 c
->authenticated
= 0;
1091 addReplyError(c
,"invalid password");
1095 void pingCommand(redisClient
*c
) {
1096 addReply(c
,shared
.pong
);
1099 void echoCommand(redisClient
*c
) {
1100 addReplyBulk(c
,c
->argv
[1]);
1103 /* Convert an amount of bytes into a human readable string in the form
1104 * of 100B, 2G, 100M, 4K, and so forth. */
1105 void bytesToHuman(char *s
, unsigned long long n
) {
1110 sprintf(s
,"%lluB",n
);
1112 } else if (n
< (1024*1024)) {
1113 d
= (double)n
/(1024);
1114 sprintf(s
,"%.2fK",d
);
1115 } else if (n
< (1024LL*1024*1024)) {
1116 d
= (double)n
/(1024*1024);
1117 sprintf(s
,"%.2fM",d
);
1118 } else if (n
< (1024LL*1024*1024*1024)) {
1119 d
= (double)n
/(1024LL*1024*1024);
1120 sprintf(s
,"%.2fG",d
);
1124 /* Create the string returned by the INFO command. This is decoupled
1125 * by the INFO command itself as we need to report the same information
1126 * on memory corruption problems. */
1127 sds
genRedisInfoString(void) {
1129 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1132 struct rusage self_ru
, c_ru
;
1134 getrusage(RUSAGE_SELF
, &self_ru
);
1135 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1137 bytesToHuman(hmem
,zmalloc_used_memory());
1138 info
= sdscatprintf(sdsempty(),
1139 "redis_version:%s\r\n"
1140 "redis_git_sha1:%s\r\n"
1141 "redis_git_dirty:%d\r\n"
1143 "multiplexing_api:%s\r\n"
1144 "process_id:%ld\r\n"
1145 "uptime_in_seconds:%ld\r\n"
1146 "uptime_in_days:%ld\r\n"
1148 "used_cpu_sys:%.2f\r\n"
1149 "used_cpu_user:%.2f\r\n"
1150 "used_cpu_sys_childrens:%.2f\r\n"
1151 "used_cpu_user_childrens:%.2f\r\n"
1152 "connected_clients:%d\r\n"
1153 "connected_slaves:%d\r\n"
1154 "blocked_clients:%d\r\n"
1155 "used_memory:%zu\r\n"
1156 "used_memory_human:%s\r\n"
1157 "used_memory_rss:%zu\r\n"
1158 "mem_fragmentation_ratio:%.2f\r\n"
1159 "use_tcmalloc:%d\r\n"
1161 "aof_enabled:%d\r\n"
1162 "changes_since_last_save:%lld\r\n"
1163 "bgsave_in_progress:%d\r\n"
1164 "last_save_time:%ld\r\n"
1165 "bgrewriteaof_in_progress:%d\r\n"
1166 "total_connections_received:%lld\r\n"
1167 "total_commands_processed:%lld\r\n"
1168 "expired_keys:%lld\r\n"
1169 "keyspace_hits:%lld\r\n"
1170 "keyspace_misses:%lld\r\n"
1171 "hash_max_zipmap_entries:%zu\r\n"
1172 "hash_max_zipmap_value:%zu\r\n"
1173 "pubsub_channels:%ld\r\n"
1174 "pubsub_patterns:%u\r\n"
1179 strtol(redisGitDirty(),NULL
,10) > 0,
1180 (sizeof(long) == 8) ? "64" : "32",
1185 (unsigned long) server
.lruclock
,
1186 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1187 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1188 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1189 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1190 listLength(server
.clients
)-listLength(server
.slaves
),
1191 listLength(server
.slaves
),
1192 server
.bpop_blocked_clients
,
1193 zmalloc_used_memory(),
1196 zmalloc_get_fragmentation_ratio(),
1205 server
.bgsavechildpid
!= -1,
1207 server
.bgrewritechildpid
!= -1,
1208 server
.stat_numconnections
,
1209 server
.stat_numcommands
,
1210 server
.stat_expiredkeys
,
1211 server
.stat_keyspace_hits
,
1212 server
.stat_keyspace_misses
,
1213 server
.hash_max_zipmap_entries
,
1214 server
.hash_max_zipmap_value
,
1215 dictSize(server
.pubsub_channels
),
1216 listLength(server
.pubsub_patterns
),
1217 server
.vm_enabled
!= 0,
1218 server
.masterhost
== NULL
? "master" : "slave"
1220 if (server
.masterhost
) {
1221 info
= sdscatprintf(info
,
1222 "master_host:%s\r\n"
1223 "master_port:%d\r\n"
1224 "master_link_status:%s\r\n"
1225 "master_last_io_seconds_ago:%d\r\n"
1226 "master_sync_in_progress:%d\r\n"
1229 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1231 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1232 server
.replstate
== REDIS_REPL_TRANSFER
1235 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1236 info
= sdscatprintf(info
,
1237 "master_sync_left_bytes:%ld\r\n"
1238 "master_sync_last_io_seconds_ago:%d\r\n"
1239 ,(long)server
.repl_transfer_left
,
1240 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1244 if (server
.vm_enabled
) {
1246 info
= sdscatprintf(info
,
1247 "vm_conf_max_memory:%llu\r\n"
1248 "vm_conf_page_size:%llu\r\n"
1249 "vm_conf_pages:%llu\r\n"
1250 "vm_stats_used_pages:%llu\r\n"
1251 "vm_stats_swapped_objects:%llu\r\n"
1252 "vm_stats_swappin_count:%llu\r\n"
1253 "vm_stats_swappout_count:%llu\r\n"
1254 "vm_stats_io_newjobs_len:%lu\r\n"
1255 "vm_stats_io_processing_len:%lu\r\n"
1256 "vm_stats_io_processed_len:%lu\r\n"
1257 "vm_stats_io_active_threads:%lu\r\n"
1258 "vm_stats_blocked_clients:%lu\r\n"
1259 ,(unsigned long long) server
.vm_max_memory
,
1260 (unsigned long long) server
.vm_page_size
,
1261 (unsigned long long) server
.vm_pages
,
1262 (unsigned long long) server
.vm_stats_used_pages
,
1263 (unsigned long long) server
.vm_stats_swapped_objects
,
1264 (unsigned long long) server
.vm_stats_swapins
,
1265 (unsigned long long) server
.vm_stats_swapouts
,
1266 (unsigned long) listLength(server
.io_newjobs
),
1267 (unsigned long) listLength(server
.io_processing
),
1268 (unsigned long) listLength(server
.io_processed
),
1269 (unsigned long) server
.io_active_threads
,
1270 (unsigned long) server
.vm_blocked_clients
1274 if (server
.loading
) {
1276 time_t eta
, elapsed
;
1277 off_t remaining_bytes
= server
.loading_total_bytes
-
1278 server
.loading_loaded_bytes
;
1280 perc
= ((double)server
.loading_loaded_bytes
/
1281 server
.loading_total_bytes
) * 100;
1283 elapsed
= time(NULL
)-server
.loading_start_time
;
1285 eta
= 1; /* A fake 1 second figure if we don't have enough info */
1287 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1290 info
= sdscatprintf(info
,
1291 "loading_start_time:%ld\r\n"
1292 "loading_total_bytes:%llu\r\n"
1293 "loading_loaded_bytes:%llu\r\n"
1294 "loading_loaded_perc:%.2f\r\n"
1295 "loading_eta_seconds:%ld\r\n"
1296 ,(unsigned long) server
.loading_start_time
,
1297 (unsigned long long) server
.loading_total_bytes
,
1298 (unsigned long long) server
.loading_loaded_bytes
,
1303 for (j
= 0; j
< server
.dbnum
; j
++) {
1304 long long keys
, vkeys
;
1306 keys
= dictSize(server
.db
[j
].dict
);
1307 vkeys
= dictSize(server
.db
[j
].expires
);
1308 if (keys
|| vkeys
) {
1309 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1316 void infoCommand(redisClient
*c
) {
1317 sds info
= genRedisInfoString();
1318 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1319 (unsigned long)sdslen(info
)));
1320 addReplySds(c
,info
);
1321 addReply(c
,shared
.crlf
);
1324 void monitorCommand(redisClient
*c
) {
1325 /* ignore MONITOR if aleady slave or in monitor mode */
1326 if (c
->flags
& REDIS_SLAVE
) return;
1328 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1330 listAddNodeTail(server
.monitors
,c
);
1331 addReply(c
,shared
.ok
);
1334 /* ============================ Maxmemory directive ======================== */
1336 /* This function gets called when 'maxmemory' is set on the config file to limit
1337 * the max memory used by the server, and we are out of memory.
1338 * This function will try to, in order:
1340 * - Free objects from the free list
1341 * - Try to remove keys with an EXPIRE set
1343 * It is not possible to free enough memory to reach used-memory < maxmemory
1344 * the server will start refusing commands that will enlarge even more the
1347 void freeMemoryIfNeeded(void) {
1348 /* Remove keys accordingly to the active policy as long as we are
1349 * over the memory limit. */
1350 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1352 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1353 int j
, k
, freed
= 0;
1355 for (j
= 0; j
< server
.dbnum
; j
++) {
1356 long bestval
= 0; /* just to prevent warning */
1358 struct dictEntry
*de
;
1359 redisDb
*db
= server
.db
+j
;
1362 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1363 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1365 dict
= server
.db
[j
].dict
;
1367 dict
= server
.db
[j
].expires
;
1369 if (dictSize(dict
) == 0) continue;
1371 /* volatile-random and allkeys-random policy */
1372 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1373 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1375 de
= dictGetRandomKey(dict
);
1376 bestkey
= dictGetEntryKey(de
);
1379 /* volatile-lru and allkeys-lru policy */
1380 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1381 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1383 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1388 de
= dictGetRandomKey(dict
);
1389 thiskey
= dictGetEntryKey(de
);
1390 /* When policy is volatile-lru we need an additonal lookup
1391 * to locate the real key, as dict is set to db->expires. */
1392 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1393 de
= dictFind(db
->dict
, thiskey
);
1394 o
= dictGetEntryVal(de
);
1395 thisval
= estimateObjectIdleTime(o
);
1397 /* Higher idle time is better candidate for deletion */
1398 if (bestkey
== NULL
|| thisval
> bestval
) {
1406 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1407 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1411 de
= dictGetRandomKey(dict
);
1412 thiskey
= dictGetEntryKey(de
);
1413 thisval
= (long) dictGetEntryVal(de
);
1415 /* Expire sooner (minor expire unix timestamp) is better
1416 * candidate for deletion */
1417 if (bestkey
== NULL
|| thisval
< bestval
) {
1424 /* Finally remove the selected key. */
1426 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1427 dbDelete(db
,keyobj
);
1428 server
.stat_expiredkeys
++;
1429 decrRefCount(keyobj
);
1433 if (!freed
) return; /* nothing to free... */
1437 int j
, k
, freed
= 0;
1438 for (j
= 0; j
< server
.dbnum
; j
++) {
1441 robj
*keyobj
= NULL
;
1442 struct dictEntry
*de
;
1444 if (dictSize(server
.db
[j
].expires
)) {
1446 /* From a sample of three keys drop the one nearest to
1447 * the natural expire */
1448 for (k
= 0; k
< 3; k
++) {
1451 de
= dictGetRandomKey(server
.db
[j
].expires
);
1452 t
= (time_t) dictGetEntryVal(de
);
1453 if (minttl
== -1 || t
< minttl
) {
1454 minkey
= dictGetEntryKey(de
);
1458 keyobj
= createStringObject(minkey
,sdslen(minkey
));
1459 dbDelete(server
.db
+j
,keyobj
);
1460 server
.stat_expiredkeys
++;
1461 decrRefCount(keyobj
);
1464 if (!freed
) return; /* nothing to free... */
1468 /* =================================== Main! ================================ */
1471 int linuxOvercommitMemoryValue(void) {
1472 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1476 if (fgets(buf
,64,fp
) == NULL
) {
1485 void linuxOvercommitMemoryWarning(void) {
1486 if (linuxOvercommitMemoryValue() == 0) {
1487 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.");
1490 #endif /* __linux__ */
1492 void createPidFile(void) {
1493 /* Try to write the pid file in a best-effort way. */
1494 FILE *fp
= fopen(server
.pidfile
,"w");
1496 fprintf(fp
,"%d\n",getpid());
1501 void daemonize(void) {
1504 if (fork() != 0) exit(0); /* parent exits */
1505 setsid(); /* create a new session */
1507 /* Every output goes to /dev/null. If Redis is daemonized but
1508 * the 'logfile' is set to 'stdout' in the configuration file
1509 * it will not log at all. */
1510 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1511 dup2(fd
, STDIN_FILENO
);
1512 dup2(fd
, STDOUT_FILENO
);
1513 dup2(fd
, STDERR_FILENO
);
1514 if (fd
> STDERR_FILENO
) close(fd
);
1519 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1520 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1525 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1526 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1530 int main(int argc
, char **argv
) {
1535 if (strcmp(argv
[1], "-v") == 0 ||
1536 strcmp(argv
[1], "--version") == 0) version();
1537 if (strcmp(argv
[1], "--help") == 0) usage();
1538 resetServerSaveParams();
1539 loadServerConfig(argv
[1]);
1540 } else if ((argc
> 2)) {
1543 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'");
1545 if (server
.daemonize
) daemonize();
1547 if (server
.daemonize
) createPidFile();
1548 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1550 linuxOvercommitMemoryWarning();
1553 if (server
.appendonly
) {
1554 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1555 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
1557 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1558 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
1560 if (server
.ipfd
> 0)
1561 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1562 if (server
.sofd
> 0)
1563 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1564 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1566 aeDeleteEventLoop(server
.el
);
1570 /* ============================= Backtrace support ========================= */
1572 #ifdef HAVE_BACKTRACE
1573 void *getMcontextEip(ucontext_t
*uc
) {
1574 #if defined(__FreeBSD__)
1575 return (void*) uc
->uc_mcontext
.mc_eip
;
1576 #elif defined(__dietlibc__)
1577 return (void*) uc
->uc_mcontext
.eip
;
1578 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1580 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1582 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1584 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1585 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1586 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1588 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1590 #elif defined(__i386__)
1591 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1592 #elif defined(__X86_64__) || defined(__x86_64__)
1593 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1594 #elif defined(__ia64__) /* Linux IA64 */
1595 return (void*) uc
->uc_mcontext
.sc_ip
;
1601 void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1603 char **messages
= NULL
;
1604 int i
, trace_size
= 0;
1605 ucontext_t
*uc
= (ucontext_t
*) secret
;
1607 struct sigaction act
;
1608 REDIS_NOTUSED(info
);
1610 redisLog(REDIS_WARNING
,
1611 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1612 infostring
= genRedisInfoString();
1613 redisLog(REDIS_WARNING
, "%s",infostring
);
1614 /* It's not safe to sdsfree() the returned string under memory
1615 * corruption conditions. Let it leak as we are going to abort */
1617 trace_size
= backtrace(trace
, 100);
1618 /* overwrite sigaction with caller's address */
1619 if (getMcontextEip(uc
) != NULL
) {
1620 trace
[1] = getMcontextEip(uc
);
1622 messages
= backtrace_symbols(trace
, trace_size
);
1624 for (i
=1; i
<trace_size
; ++i
)
1625 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1627 /* free(messages); Don't call free() with possibly corrupted memory. */
1628 if (server
.daemonize
) unlink(server
.pidfile
);
1630 /* Make sure we exit with the right signal at the end. So for instance
1631 * the core will be dumped if enabled. */
1632 sigemptyset (&act
.sa_mask
);
1633 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1634 * is used. Otherwise, sa_handler is used */
1635 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1636 act
.sa_handler
= SIG_DFL
;
1637 sigaction (sig
, &act
, NULL
);
1641 void sigtermHandler(int sig
) {
1644 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
1645 server
.shutdown_asap
= 1;
1648 void setupSigSegvAction(void) {
1649 struct sigaction act
;
1651 sigemptyset (&act
.sa_mask
);
1652 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1653 * is used. Otherwise, sa_handler is used */
1654 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1655 act
.sa_sigaction
= segvHandler
;
1656 sigaction (SIGSEGV
, &act
, NULL
);
1657 sigaction (SIGBUS
, &act
, NULL
);
1658 sigaction (SIGFPE
, &act
, NULL
);
1659 sigaction (SIGILL
, &act
, NULL
);
1660 sigaction (SIGBUS
, &act
, NULL
);
1662 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1663 act
.sa_handler
= sigtermHandler
;
1664 sigaction (SIGTERM
, &act
, NULL
);
1668 #else /* HAVE_BACKTRACE */
1669 void setupSigSegvAction(void) {
1671 #endif /* HAVE_BACKTRACE */