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 {"substr",substrCommand
,4,0,NULL
,1,1,1},
78 {"strlen",strlenCommand
,2,0,NULL
,1,1,1},
79 {"del",delCommand
,-2,0,NULL
,0,0,0},
80 {"exists",existsCommand
,2,0,NULL
,1,1,1},
81 {"setbit",setbitCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
82 {"getbit",getbitCommand
,3,0,NULL
,1,1,1},
83 {"setrange",setrangeCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
84 {"incr",incrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
85 {"decr",decrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
86 {"mget",mgetCommand
,-2,0,NULL
,1,-1,1},
87 {"rpush",rpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
88 {"lpush",lpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
89 {"rpushx",rpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
90 {"lpushx",lpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
91 {"linsert",linsertCommand
,5,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
92 {"rpop",rpopCommand
,2,0,NULL
,1,1,1},
93 {"lpop",lpopCommand
,2,0,NULL
,1,1,1},
94 {"brpop",brpopCommand
,-3,0,NULL
,1,1,1},
95 {"blpop",blpopCommand
,-3,0,NULL
,1,1,1},
96 {"llen",llenCommand
,2,0,NULL
,1,1,1},
97 {"lindex",lindexCommand
,3,0,NULL
,1,1,1},
98 {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
99 {"lrange",lrangeCommand
,4,0,NULL
,1,1,1},
100 {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1},
101 {"lrem",lremCommand
,4,0,NULL
,1,1,1},
102 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1},
103 {"sadd",saddCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
104 {"srem",sremCommand
,3,0,NULL
,1,1,1},
105 {"smove",smoveCommand
,4,0,NULL
,1,2,1},
106 {"sismember",sismemberCommand
,3,0,NULL
,1,1,1},
107 {"scard",scardCommand
,2,0,NULL
,1,1,1},
108 {"spop",spopCommand
,2,0,NULL
,1,1,1},
109 {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1},
110 {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
111 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
112 {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
113 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
114 {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
115 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
116 {"smembers",sinterCommand
,2,0,NULL
,1,1,1},
117 {"zadd",zaddCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
118 {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
119 {"zrem",zremCommand
,3,0,NULL
,1,1,1},
120 {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1},
121 {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1},
122 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
123 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
124 {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1},
125 {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1},
126 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1},
127 {"zcount",zcountCommand
,4,0,NULL
,1,1,1},
128 {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1},
129 {"zcard",zcardCommand
,2,0,NULL
,1,1,1},
130 {"zscore",zscoreCommand
,3,0,NULL
,1,1,1},
131 {"zrank",zrankCommand
,3,0,NULL
,1,1,1},
132 {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1},
133 {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
134 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
135 {"hget",hgetCommand
,3,0,NULL
,1,1,1},
136 {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
137 {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1},
138 {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
139 {"hdel",hdelCommand
,3,0,NULL
,1,1,1},
140 {"hlen",hlenCommand
,2,0,NULL
,1,1,1},
141 {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1},
142 {"hvals",hvalsCommand
,2,0,NULL
,1,1,1},
143 {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1},
144 {"hexists",hexistsCommand
,3,0,NULL
,1,1,1},
145 {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
146 {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
147 {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
148 {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
149 {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
150 {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0},
151 {"select",selectCommand
,2,0,NULL
,0,0,0},
152 {"move",moveCommand
,3,0,NULL
,1,1,1},
153 {"rename",renameCommand
,3,0,NULL
,1,1,1},
154 {"renamenx",renamenxCommand
,3,0,NULL
,1,1,1},
155 {"expire",expireCommand
,3,0,NULL
,0,0,0},
156 {"expireat",expireatCommand
,3,0,NULL
,0,0,0},
157 {"keys",keysCommand
,2,0,NULL
,0,0,0},
158 {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0},
159 {"auth",authCommand
,2,0,NULL
,0,0,0},
160 {"ping",pingCommand
,1,0,NULL
,0,0,0},
161 {"echo",echoCommand
,2,0,NULL
,0,0,0},
162 {"save",saveCommand
,1,0,NULL
,0,0,0},
163 {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0},
164 {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0},
165 {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0},
166 {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0},
167 {"type",typeCommand
,2,0,NULL
,1,1,1},
168 {"multi",multiCommand
,1,0,NULL
,0,0,0},
169 {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
170 {"discard",discardCommand
,1,0,NULL
,0,0,0},
171 {"sync",syncCommand
,1,0,NULL
,0,0,0},
172 {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0},
173 {"flushall",flushallCommand
,1,0,NULL
,0,0,0},
174 {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
175 {"info",infoCommand
,1,0,NULL
,0,0,0},
176 {"monitor",monitorCommand
,1,0,NULL
,0,0,0},
177 {"ttl",ttlCommand
,2,0,NULL
,1,1,1},
178 {"persist",persistCommand
,2,0,NULL
,1,1,1},
179 {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0},
180 {"debug",debugCommand
,-2,0,NULL
,0,0,0},
181 {"config",configCommand
,-2,0,NULL
,0,0,0},
182 {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0},
183 {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0},
184 {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0},
185 {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0},
186 {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
187 {"watch",watchCommand
,-2,0,NULL
,0,0,0},
188 {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0}
191 /*============================ Utility functions ============================ */
193 void redisLog(int level
, const char *fmt
, ...) {
200 if (level
< server
.verbosity
) return;
202 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
207 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
208 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
209 vfprintf(fp
, fmt
, ap
);
214 if (server
.logfile
) fclose(fp
);
217 /* Redis generally does not try to recover from out of memory conditions
218 * when allocating objects or strings, it is not clear if it will be possible
219 * to report this condition to the client since the networking layer itself
220 * is based on heap allocation for send buffers, so we simply abort.
221 * At least the code will be simpler to read... */
222 void oom(const char *msg
) {
223 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
228 /*====================== Hash table type implementation ==================== */
230 /* This is an hash table type that uses the SDS dynamic strings libary as
231 * keys and radis objects as values (objects can hold SDS strings,
234 void dictVanillaFree(void *privdata
, void *val
)
236 DICT_NOTUSED(privdata
);
240 void dictListDestructor(void *privdata
, void *val
)
242 DICT_NOTUSED(privdata
);
243 listRelease((list
*)val
);
246 int dictSdsKeyCompare(void *privdata
, const void *key1
,
250 DICT_NOTUSED(privdata
);
252 l1
= sdslen((sds
)key1
);
253 l2
= sdslen((sds
)key2
);
254 if (l1
!= l2
) return 0;
255 return memcmp(key1
, key2
, l1
) == 0;
258 /* A case insensitive version used for the command lookup table. */
259 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
262 DICT_NOTUSED(privdata
);
264 return strcasecmp(key1
, key2
) == 0;
267 void dictRedisObjectDestructor(void *privdata
, void *val
)
269 DICT_NOTUSED(privdata
);
271 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
275 void dictSdsDestructor(void *privdata
, void *val
)
277 DICT_NOTUSED(privdata
);
282 int dictObjKeyCompare(void *privdata
, const void *key1
,
285 const robj
*o1
= key1
, *o2
= key2
;
286 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
289 unsigned int dictObjHash(const void *key
) {
291 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
294 unsigned int dictSdsHash(const void *key
) {
295 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
298 unsigned int dictSdsCaseHash(const void *key
) {
299 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
302 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
305 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
308 if (o1
->encoding
== REDIS_ENCODING_INT
&&
309 o2
->encoding
== REDIS_ENCODING_INT
)
310 return o1
->ptr
== o2
->ptr
;
312 o1
= getDecodedObject(o1
);
313 o2
= getDecodedObject(o2
);
314 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
320 unsigned int dictEncObjHash(const void *key
) {
321 robj
*o
= (robj
*) key
;
323 if (o
->encoding
== REDIS_ENCODING_RAW
) {
324 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
326 if (o
->encoding
== REDIS_ENCODING_INT
) {
330 len
= ll2string(buf
,32,(long)o
->ptr
);
331 return dictGenHashFunction((unsigned char*)buf
, len
);
335 o
= getDecodedObject(o
);
336 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
344 dictType setDictType
= {
345 dictEncObjHash
, /* hash function */
348 dictEncObjKeyCompare
, /* key compare */
349 dictRedisObjectDestructor
, /* key destructor */
350 NULL
/* val destructor */
353 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
354 dictType zsetDictType
= {
355 dictEncObjHash
, /* hash function */
358 dictEncObjKeyCompare
, /* key compare */
359 dictRedisObjectDestructor
, /* key destructor */
360 NULL
/* val destructor */
363 /* Db->dict, keys are sds strings, vals are Redis objects. */
364 dictType dbDictType
= {
365 dictSdsHash
, /* hash function */
368 dictSdsKeyCompare
, /* key compare */
369 dictSdsDestructor
, /* key destructor */
370 dictRedisObjectDestructor
/* val destructor */
374 dictType keyptrDictType
= {
375 dictSdsHash
, /* hash function */
378 dictSdsKeyCompare
, /* key compare */
379 NULL
, /* key destructor */
380 NULL
/* val destructor */
383 /* Command table. sds string -> command struct pointer. */
384 dictType commandTableDictType
= {
385 dictSdsCaseHash
, /* hash function */
388 dictSdsKeyCaseCompare
, /* key compare */
389 dictSdsDestructor
, /* key destructor */
390 NULL
/* val destructor */
393 /* Hash type hash table (note that small hashes are represented with zimpaps) */
394 dictType hashDictType
= {
395 dictEncObjHash
, /* hash function */
398 dictEncObjKeyCompare
, /* key compare */
399 dictRedisObjectDestructor
, /* key destructor */
400 dictRedisObjectDestructor
/* val destructor */
403 /* Keylist hash table type has unencoded redis objects as keys and
404 * lists as values. It's used for blocking operations (BLPOP) and to
405 * map swapped keys to a list of clients waiting for this keys to be loaded. */
406 dictType keylistDictType
= {
407 dictObjHash
, /* hash function */
410 dictObjKeyCompare
, /* key compare */
411 dictRedisObjectDestructor
, /* key destructor */
412 dictListDestructor
/* val destructor */
415 int htNeedsResize(dict
*dict
) {
416 long long size
, used
;
418 size
= dictSlots(dict
);
419 used
= dictSize(dict
);
420 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
421 (used
*100/size
< REDIS_HT_MINFILL
));
424 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
425 * we resize the hash table to save memory */
426 void tryResizeHashTables(void) {
429 for (j
= 0; j
< server
.dbnum
; j
++) {
430 if (htNeedsResize(server
.db
[j
].dict
))
431 dictResize(server
.db
[j
].dict
);
432 if (htNeedsResize(server
.db
[j
].expires
))
433 dictResize(server
.db
[j
].expires
);
437 /* Our hash table implementation performs rehashing incrementally while
438 * we write/read from the hash table. Still if the server is idle, the hash
439 * table will use two tables for a long time. So we try to use 1 millisecond
440 * of CPU time at every serverCron() loop in order to rehash some key. */
441 void incrementallyRehash(void) {
444 for (j
= 0; j
< server
.dbnum
; j
++) {
445 if (dictIsRehashing(server
.db
[j
].dict
)) {
446 dictRehashMilliseconds(server
.db
[j
].dict
,1);
447 break; /* already used our millisecond for this loop... */
452 /* This function is called once a background process of some kind terminates,
453 * as we want to avoid resizing the hash tables when there is a child in order
454 * to play well with copy-on-write (otherwise when a resize happens lots of
455 * memory pages are copied). The goal of this function is to update the ability
456 * for dict.c to resize the hash tables accordingly to the fact we have o not
458 void updateDictResizePolicy(void) {
459 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
465 /* ======================= Cron: called every 100 ms ======================== */
467 /* Try to expire a few timed out keys. The algorithm used is adaptive and
468 * will use few CPU cycles if there are few expiring keys, otherwise
469 * it will get more aggressive to avoid that too much memory is used by
470 * keys that can be removed from the keyspace. */
471 void activeExpireCycle(void) {
474 for (j
= 0; j
< server
.dbnum
; j
++) {
476 redisDb
*db
= server
.db
+j
;
478 /* Continue to expire if at the end of the cycle more than 25%
479 * of the keys were expired. */
481 long num
= dictSize(db
->expires
);
482 time_t now
= time(NULL
);
485 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
486 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
491 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
492 t
= (time_t) dictGetEntryVal(de
);
494 sds key
= dictGetEntryKey(de
);
495 robj
*keyobj
= createStringObject(key
,sdslen(key
));
497 propagateExpire(db
,keyobj
);
499 decrRefCount(keyobj
);
501 server
.stat_expiredkeys
++;
504 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
508 void updateLRUClock(void) {
509 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
513 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
514 int j
, loops
= server
.cronloops
++;
515 REDIS_NOTUSED(eventLoop
);
517 REDIS_NOTUSED(clientData
);
519 /* We take a cached value of the unix time in the global state because
520 * with virtual memory and aging there is to store the current time
521 * in objects at every object access, and accuracy is not needed.
522 * To access a global var is faster than calling time(NULL) */
523 server
.unixtime
= time(NULL
);
524 /* We have just 22 bits per object for LRU information.
525 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
526 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
528 * Note that even if this will wrap after 1.5 years it's not a problem,
529 * everything will still work but just some object will appear younger
530 * to Redis. But for this to happen a given object should never be touched
533 * Note that you can change the resolution altering the
534 * REDIS_LRU_CLOCK_RESOLUTION define.
538 /* We received a SIGTERM, shutting down here in a safe way, as it is
539 * not ok doing so inside the signal handler. */
540 if (server
.shutdown_asap
) {
541 if (prepareForShutdown() == REDIS_OK
) exit(0);
542 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
545 /* Show some info about non-empty databases */
546 for (j
= 0; j
< server
.dbnum
; j
++) {
547 long long size
, used
, vkeys
;
549 size
= dictSlots(server
.db
[j
].dict
);
550 used
= dictSize(server
.db
[j
].dict
);
551 vkeys
= dictSize(server
.db
[j
].expires
);
552 if (!(loops
% 50) && (used
|| vkeys
)) {
553 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
554 /* dictPrintStats(server.dict); */
558 /* We don't want to resize the hash tables while a bacground saving
559 * is in progress: the saving child is created using fork() that is
560 * implemented with a copy-on-write semantic in most modern systems, so
561 * if we resize the HT while there is the saving child at work actually
562 * a lot of memory movements in the parent will cause a lot of pages
564 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
565 if (!(loops
% 10)) tryResizeHashTables();
566 if (server
.activerehashing
) incrementallyRehash();
569 /* Show information about connected clients */
571 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
572 listLength(server
.clients
)-listLength(server
.slaves
),
573 listLength(server
.slaves
),
574 zmalloc_used_memory());
577 /* Close connections of timedout clients */
578 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
579 closeTimedoutClients();
581 /* Check if a background saving or AOF rewrite in progress terminated */
582 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
586 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
587 if (pid
== server
.bgsavechildpid
) {
588 backgroundSaveDoneHandler(statloc
);
590 backgroundRewriteDoneHandler(statloc
);
592 updateDictResizePolicy();
595 /* If there is not a background saving in progress check if
596 * we have to save now */
597 time_t now
= time(NULL
);
598 for (j
= 0; j
< server
.saveparamslen
; j
++) {
599 struct saveparam
*sp
= server
.saveparams
+j
;
601 if (server
.dirty
>= sp
->changes
&&
602 now
-server
.lastsave
> sp
->seconds
) {
603 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
604 sp
->changes
, sp
->seconds
);
605 rdbSaveBackground(server
.dbfilename
);
611 /* Expire a few keys per cycle, only if this is a master.
612 * On slaves we wait for DEL operations synthesized by the master
613 * in order to guarantee a strict consistency. */
614 if (server
.masterhost
== NULL
) activeExpireCycle();
616 /* Swap a few keys on disk if we are over the memory limit and VM
617 * is enbled. Try to free objects from the free list first. */
618 if (vmCanSwapOut()) {
619 while (server
.vm_enabled
&& zmalloc_used_memory() >
620 server
.vm_max_memory
)
622 int retval
= (server
.vm_max_threads
== 0) ?
623 vmSwapOneObjectBlocking() :
624 vmSwapOneObjectThreaded();
625 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
626 zmalloc_used_memory() >
627 (server
.vm_max_memory
+server
.vm_max_memory
/10))
629 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
631 /* Note that when using threade I/O we free just one object,
632 * because anyway when the I/O thread in charge to swap this
633 * object out will finish, the handler of completed jobs
634 * will try to swap more objects if we are still out of memory. */
635 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
639 /* Replication cron function -- used to reconnect to master and
640 * to detect transfer failures. */
641 if (!(loops
% 10)) replicationCron();
646 /* This function gets called every time Redis is entering the
647 * main loop of the event driven library, that is, before to sleep
648 * for ready file descriptors. */
649 void beforeSleep(struct aeEventLoop
*eventLoop
) {
650 REDIS_NOTUSED(eventLoop
);
652 /* Awake clients that got all the swapped keys they requested */
653 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
657 listRewind(server
.io_ready_clients
,&li
);
658 while((ln
= listNext(&li
))) {
659 redisClient
*c
= ln
->value
;
660 struct redisCommand
*cmd
;
662 /* Resume the client. */
663 listDelNode(server
.io_ready_clients
,ln
);
664 c
->flags
&= (~REDIS_IO_WAIT
);
665 server
.vm_blocked_clients
--;
666 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
667 readQueryFromClient
, c
);
668 cmd
= lookupCommand(c
->argv
[0]->ptr
);
669 redisAssert(cmd
!= NULL
);
672 /* There may be more data to process in the input buffer. */
673 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
674 processInputBuffer(c
);
677 /* Write the AOF buffer on disk */
678 flushAppendOnlyFile();
681 /* =========================== Server initialization ======================== */
683 void createSharedObjects(void) {
686 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
687 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
688 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
689 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
690 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
691 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
692 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
693 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
694 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
695 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
696 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
697 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
698 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
699 "-ERR Operation against a key holding the wrong kind of value\r\n"));
700 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
701 "-ERR no such key\r\n"));
702 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
703 "-ERR syntax error\r\n"));
704 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
705 "-ERR source and destination objects are the same\r\n"));
706 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
707 "-ERR index out of range\r\n"));
708 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
709 "-LOADING Redis is loading the dataset in memory\r\n"));
710 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
711 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
712 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
713 shared
.select0
= createStringObject("select 0\r\n",10);
714 shared
.select1
= createStringObject("select 1\r\n",10);
715 shared
.select2
= createStringObject("select 2\r\n",10);
716 shared
.select3
= createStringObject("select 3\r\n",10);
717 shared
.select4
= createStringObject("select 4\r\n",10);
718 shared
.select5
= createStringObject("select 5\r\n",10);
719 shared
.select6
= createStringObject("select 6\r\n",10);
720 shared
.select7
= createStringObject("select 7\r\n",10);
721 shared
.select8
= createStringObject("select 8\r\n",10);
722 shared
.select9
= createStringObject("select 9\r\n",10);
723 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
724 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
725 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
726 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
727 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
728 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
729 shared
.mbulk3
= createStringObject("*3\r\n",4);
730 shared
.mbulk4
= createStringObject("*4\r\n",4);
731 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
732 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
733 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
737 void initServerConfig() {
738 server
.port
= REDIS_SERVERPORT
;
739 server
.bindaddr
= NULL
;
740 server
.unixsocket
= NULL
;
743 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
744 server
.verbosity
= REDIS_VERBOSE
;
745 server
.maxidletime
= REDIS_MAXIDLETIME
;
746 server
.saveparams
= NULL
;
748 server
.logfile
= NULL
; /* NULL = log on standard output */
749 server
.glueoutputbuf
= 1;
750 server
.daemonize
= 0;
751 server
.appendonly
= 0;
752 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
753 server
.no_appendfsync_on_rewrite
= 0;
754 server
.lastfsync
= time(NULL
);
755 server
.appendfd
= -1;
756 server
.appendseldb
= -1; /* Make sure the first time will not match */
757 server
.pidfile
= zstrdup("/var/run/redis.pid");
758 server
.dbfilename
= zstrdup("dump.rdb");
759 server
.appendfilename
= zstrdup("appendonly.aof");
760 server
.requirepass
= NULL
;
761 server
.rdbcompression
= 1;
762 server
.activerehashing
= 1;
763 server
.maxclients
= 0;
764 server
.blpop_blocked_clients
= 0;
765 server
.maxmemory
= 0;
766 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
767 server
.maxmemory_samples
= 3;
768 server
.vm_enabled
= 0;
769 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
770 server
.vm_page_size
= 256; /* 256 bytes per page */
771 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
772 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
773 server
.vm_max_threads
= 4;
774 server
.vm_blocked_clients
= 0;
775 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
776 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
777 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
778 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
779 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
780 server
.shutdown_asap
= 0;
783 resetServerSaveParams();
785 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
786 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
787 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
788 /* Replication related */
790 server
.masterauth
= NULL
;
791 server
.masterhost
= NULL
;
792 server
.masterport
= 6379;
793 server
.master
= NULL
;
794 server
.replstate
= REDIS_REPL_NONE
;
795 server
.repl_serve_stale_data
= 1;
797 /* Double constants initialization */
799 R_PosInf
= 1.0/R_Zero
;
800 R_NegInf
= -1.0/R_Zero
;
801 R_Nan
= R_Zero
/R_Zero
;
803 /* Command table -- we intiialize it here as it is part of the
804 * initial configuration, since command names may be changed via
805 * redis.conf using the rename-command directive. */
806 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
807 populateCommandTable();
808 server
.delCommand
= lookupCommandByCString("del");
809 server
.multiCommand
= lookupCommandByCString("multi");
815 signal(SIGHUP
, SIG_IGN
);
816 signal(SIGPIPE
, SIG_IGN
);
817 setupSigSegvAction();
819 server
.mainthread
= pthread_self();
820 server
.clients
= listCreate();
821 server
.slaves
= listCreate();
822 server
.monitors
= listCreate();
823 createSharedObjects();
824 server
.el
= aeCreateEventLoop();
825 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
826 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
827 if (server
.ipfd
== ANET_ERR
) {
828 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
831 if (server
.unixsocket
!= NULL
) {
832 unlink(server
.unixsocket
); /* don't care if this fails */
833 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
834 if (server
.sofd
== ANET_ERR
) {
835 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
839 if (server
.ipfd
< 0 && server
.sofd
< 0) {
840 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
843 for (j
= 0; j
< server
.dbnum
; j
++) {
844 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
845 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
846 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
847 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
848 if (server
.vm_enabled
)
849 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
852 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
853 server
.pubsub_patterns
= listCreate();
854 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
855 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
856 server
.cronloops
= 0;
857 server
.bgsavechildpid
= -1;
858 server
.bgrewritechildpid
= -1;
859 server
.bgrewritebuf
= sdsempty();
860 server
.aofbuf
= sdsempty();
861 server
.lastsave
= time(NULL
);
863 server
.stat_numcommands
= 0;
864 server
.stat_numconnections
= 0;
865 server
.stat_expiredkeys
= 0;
866 server
.stat_starttime
= time(NULL
);
867 server
.stat_keyspace_misses
= 0;
868 server
.stat_keyspace_hits
= 0;
869 server
.unixtime
= time(NULL
);
870 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
871 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
872 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
873 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
874 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
876 if (server
.appendonly
) {
877 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
878 if (server
.appendfd
== -1) {
879 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
885 if (server
.vm_enabled
) vmInit();
888 /* Populates the Redis Command Table starting from the hard coded list
889 * we have on top of redis.c file. */
890 void populateCommandTable(void) {
892 int numcommands
= sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
);
894 for (j
= 0; j
< numcommands
; j
++) {
895 struct redisCommand
*c
= readonlyCommandTable
+j
;
898 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
899 assert(retval
== DICT_OK
);
903 /* ====================== Commands lookup and execution ===================== */
905 struct redisCommand
*lookupCommand(sds name
) {
906 return dictFetchValue(server
.commands
, name
);
909 struct redisCommand
*lookupCommandByCString(char *s
) {
910 struct redisCommand
*cmd
;
911 sds name
= sdsnew(s
);
913 cmd
= dictFetchValue(server
.commands
, name
);
918 /* Call() is the core of Redis execution of a command */
919 void call(redisClient
*c
, struct redisCommand
*cmd
) {
922 dirty
= server
.dirty
;
924 dirty
= server
.dirty
-dirty
;
926 if (server
.appendonly
&& dirty
)
927 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
928 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
929 listLength(server
.slaves
))
930 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
931 if (listLength(server
.monitors
))
932 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
933 server
.stat_numcommands
++;
936 /* If this function gets called we already read a whole
937 * command, argments are in the client argv/argc fields.
938 * processCommand() execute the command or prepare the
939 * server for a bulk read from the client.
941 * If 1 is returned the client is still alive and valid and
942 * and other operations can be performed by the caller. Otherwise
943 * if 0 is returned the client was destroied (i.e. after QUIT). */
944 int processCommand(redisClient
*c
) {
945 struct redisCommand
*cmd
;
947 /* The QUIT command is handled separately. Normal command procs will
948 * go through checking for replication and QUIT will cause trouble
949 * when FORCE_REPLICATION is enabled and would be implemented in
950 * a regular command proc. */
951 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
952 addReply(c
,shared
.ok
);
953 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
957 /* Now lookup the command and check ASAP about trivial error conditions
958 * such wrong arity, bad command name and so forth. */
959 cmd
= lookupCommand(c
->argv
[0]->ptr
);
961 addReplyErrorFormat(c
,"unknown command '%s'",
962 (char*)c
->argv
[0]->ptr
);
964 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
965 (c
->argc
< -cmd
->arity
)) {
966 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
971 /* Check if the user is authenticated */
972 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
973 addReplyError(c
,"operation not permitted");
977 /* Handle the maxmemory directive.
979 * First we try to free some memory if possible (if there are volatile
980 * keys in the dataset). If there are not the only thing we can do
981 * is returning an error. */
982 if (server
.maxmemory
) freeMemoryIfNeeded();
983 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
984 zmalloc_used_memory() > server
.maxmemory
)
986 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
990 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
991 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
993 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
994 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
995 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
999 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1000 * we are a slave with a broken link with master. */
1001 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1002 server
.repl_serve_stale_data
== 0 &&
1003 cmd
->proc
!= infoCommand
&& cmd
->proc
!= slaveofCommand
)
1006 "link with MASTER is down and slave-serve-stale-data is set to no");
1010 /* Loading DB? Return an error if the command is not INFO */
1011 if (server
.loading
&& cmd
->proc
!= infoCommand
) {
1012 addReply(c
, shared
.loadingerr
);
1016 /* Exec the command */
1017 if (c
->flags
& REDIS_MULTI
&&
1018 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
1019 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
1021 queueMultiCommand(c
,cmd
);
1022 addReply(c
,shared
.queued
);
1024 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
1025 blockClientOnSwappedKeys(c
,cmd
)) return REDIS_ERR
;
1031 /*================================== Shutdown =============================== */
1033 int prepareForShutdown() {
1034 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1035 /* Kill the saving child if there is a background saving in progress.
1036 We want to avoid race conditions, for instance our saving child may
1037 overwrite the synchronous saving did by SHUTDOWN. */
1038 if (server
.bgsavechildpid
!= -1) {
1039 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
1040 kill(server
.bgsavechildpid
,SIGKILL
);
1041 rdbRemoveTempFile(server
.bgsavechildpid
);
1043 if (server
.appendonly
) {
1044 /* Append only file: fsync() the AOF and exit */
1045 aof_fsync(server
.appendfd
);
1046 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
1047 } else if (server
.saveparamslen
> 0) {
1048 /* Snapshotting. Perform a SYNC SAVE and exit */
1049 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1050 /* Ooops.. error saving! The best we can do is to continue
1051 * operating. Note that if there was a background saving process,
1052 * in the next cron() Redis will be notified that the background
1053 * saving aborted, handling special stuff like slaves pending for
1054 * synchronization... */
1055 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1059 redisLog(REDIS_WARNING
,"Not saving DB.");
1061 if (server
.daemonize
) unlink(server
.pidfile
);
1062 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1066 /*================================== Commands =============================== */
1068 void authCommand(redisClient
*c
) {
1069 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1070 c
->authenticated
= 1;
1071 addReply(c
,shared
.ok
);
1073 c
->authenticated
= 0;
1074 addReplyError(c
,"invalid password");
1078 void pingCommand(redisClient
*c
) {
1079 addReply(c
,shared
.pong
);
1082 void echoCommand(redisClient
*c
) {
1083 addReplyBulk(c
,c
->argv
[1]);
1086 /* Convert an amount of bytes into a human readable string in the form
1087 * of 100B, 2G, 100M, 4K, and so forth. */
1088 void bytesToHuman(char *s
, unsigned long long n
) {
1093 sprintf(s
,"%lluB",n
);
1095 } else if (n
< (1024*1024)) {
1096 d
= (double)n
/(1024);
1097 sprintf(s
,"%.2fK",d
);
1098 } else if (n
< (1024LL*1024*1024)) {
1099 d
= (double)n
/(1024*1024);
1100 sprintf(s
,"%.2fM",d
);
1101 } else if (n
< (1024LL*1024*1024*1024)) {
1102 d
= (double)n
/(1024LL*1024*1024);
1103 sprintf(s
,"%.2fG",d
);
1107 /* Create the string returned by the INFO command. This is decoupled
1108 * by the INFO command itself as we need to report the same information
1109 * on memory corruption problems. */
1110 sds
genRedisInfoString(void) {
1112 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1115 struct rusage self_ru
, c_ru
;
1117 getrusage(RUSAGE_SELF
, &self_ru
);
1118 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1120 bytesToHuman(hmem
,zmalloc_used_memory());
1121 info
= sdscatprintf(sdsempty(),
1122 "redis_version:%s\r\n"
1123 "redis_git_sha1:%s\r\n"
1124 "redis_git_dirty:%d\r\n"
1126 "multiplexing_api:%s\r\n"
1127 "process_id:%ld\r\n"
1128 "uptime_in_seconds:%ld\r\n"
1129 "uptime_in_days:%ld\r\n"
1131 "used_cpu_sys:%.2f\r\n"
1132 "used_cpu_user:%.2f\r\n"
1133 "used_cpu_sys_childrens:%.2f\r\n"
1134 "used_cpu_user_childrens:%.2f\r\n"
1135 "connected_clients:%d\r\n"
1136 "connected_slaves:%d\r\n"
1137 "blocked_clients:%d\r\n"
1138 "used_memory:%zu\r\n"
1139 "used_memory_human:%s\r\n"
1140 "used_memory_rss:%zu\r\n"
1141 "mem_fragmentation_ratio:%.2f\r\n"
1142 "use_tcmalloc:%d\r\n"
1144 "aof_enabled:%d\r\n"
1145 "changes_since_last_save:%lld\r\n"
1146 "bgsave_in_progress:%d\r\n"
1147 "last_save_time:%ld\r\n"
1148 "bgrewriteaof_in_progress:%d\r\n"
1149 "total_connections_received:%lld\r\n"
1150 "total_commands_processed:%lld\r\n"
1151 "expired_keys:%lld\r\n"
1152 "keyspace_hits:%lld\r\n"
1153 "keyspace_misses:%lld\r\n"
1154 "hash_max_zipmap_entries:%zu\r\n"
1155 "hash_max_zipmap_value:%zu\r\n"
1156 "pubsub_channels:%ld\r\n"
1157 "pubsub_patterns:%u\r\n"
1162 strtol(redisGitDirty(),NULL
,10) > 0,
1163 (sizeof(long) == 8) ? "64" : "32",
1168 (unsigned long) server
.lruclock
,
1169 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1170 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1171 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1172 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1173 listLength(server
.clients
)-listLength(server
.slaves
),
1174 listLength(server
.slaves
),
1175 server
.blpop_blocked_clients
,
1176 zmalloc_used_memory(),
1179 zmalloc_get_fragmentation_ratio(),
1188 server
.bgsavechildpid
!= -1,
1190 server
.bgrewritechildpid
!= -1,
1191 server
.stat_numconnections
,
1192 server
.stat_numcommands
,
1193 server
.stat_expiredkeys
,
1194 server
.stat_keyspace_hits
,
1195 server
.stat_keyspace_misses
,
1196 server
.hash_max_zipmap_entries
,
1197 server
.hash_max_zipmap_value
,
1198 dictSize(server
.pubsub_channels
),
1199 listLength(server
.pubsub_patterns
),
1200 server
.vm_enabled
!= 0,
1201 server
.masterhost
== NULL
? "master" : "slave"
1203 if (server
.masterhost
) {
1204 info
= sdscatprintf(info
,
1205 "master_host:%s\r\n"
1206 "master_port:%d\r\n"
1207 "master_link_status:%s\r\n"
1208 "master_last_io_seconds_ago:%d\r\n"
1209 "master_sync_in_progress:%d\r\n"
1212 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1214 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1215 server
.replstate
== REDIS_REPL_TRANSFER
1218 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1219 info
= sdscatprintf(info
,
1220 "master_sync_left_bytes:%ld\r\n"
1221 "master_sync_last_io_seconds_ago:%d\r\n"
1222 ,(long)server
.repl_transfer_left
,
1223 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1227 if (server
.vm_enabled
) {
1229 info
= sdscatprintf(info
,
1230 "vm_conf_max_memory:%llu\r\n"
1231 "vm_conf_page_size:%llu\r\n"
1232 "vm_conf_pages:%llu\r\n"
1233 "vm_stats_used_pages:%llu\r\n"
1234 "vm_stats_swapped_objects:%llu\r\n"
1235 "vm_stats_swappin_count:%llu\r\n"
1236 "vm_stats_swappout_count:%llu\r\n"
1237 "vm_stats_io_newjobs_len:%lu\r\n"
1238 "vm_stats_io_processing_len:%lu\r\n"
1239 "vm_stats_io_processed_len:%lu\r\n"
1240 "vm_stats_io_active_threads:%lu\r\n"
1241 "vm_stats_blocked_clients:%lu\r\n"
1242 ,(unsigned long long) server
.vm_max_memory
,
1243 (unsigned long long) server
.vm_page_size
,
1244 (unsigned long long) server
.vm_pages
,
1245 (unsigned long long) server
.vm_stats_used_pages
,
1246 (unsigned long long) server
.vm_stats_swapped_objects
,
1247 (unsigned long long) server
.vm_stats_swapins
,
1248 (unsigned long long) server
.vm_stats_swapouts
,
1249 (unsigned long) listLength(server
.io_newjobs
),
1250 (unsigned long) listLength(server
.io_processing
),
1251 (unsigned long) listLength(server
.io_processed
),
1252 (unsigned long) server
.io_active_threads
,
1253 (unsigned long) server
.vm_blocked_clients
1257 if (server
.loading
) {
1259 time_t eta
, elapsed
;
1260 off_t remaining_bytes
= server
.loading_total_bytes
-
1261 server
.loading_loaded_bytes
;
1263 perc
= ((double)server
.loading_loaded_bytes
/
1264 server
.loading_total_bytes
) * 100;
1266 elapsed
= time(NULL
)-server
.loading_start_time
;
1268 eta
= 1; /* A fake 1 second figure if we don't have enough info */
1270 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1273 info
= sdscatprintf(info
,
1274 "loading_start_time:%ld\r\n"
1275 "loading_total_bytes:%llu\r\n"
1276 "loading_loaded_bytes:%llu\r\n"
1277 "loading_loaded_perc:%.2f\r\n"
1278 "loading_eta_seconds:%ld\r\n"
1279 ,(unsigned long) server
.loading_start_time
,
1280 (unsigned long long) server
.loading_total_bytes
,
1281 (unsigned long long) server
.loading_loaded_bytes
,
1286 for (j
= 0; j
< server
.dbnum
; j
++) {
1287 long long keys
, vkeys
;
1289 keys
= dictSize(server
.db
[j
].dict
);
1290 vkeys
= dictSize(server
.db
[j
].expires
);
1291 if (keys
|| vkeys
) {
1292 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1299 void infoCommand(redisClient
*c
) {
1300 sds info
= genRedisInfoString();
1301 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1302 (unsigned long)sdslen(info
)));
1303 addReplySds(c
,info
);
1304 addReply(c
,shared
.crlf
);
1307 void monitorCommand(redisClient
*c
) {
1308 /* ignore MONITOR if aleady slave or in monitor mode */
1309 if (c
->flags
& REDIS_SLAVE
) return;
1311 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1313 listAddNodeTail(server
.monitors
,c
);
1314 addReply(c
,shared
.ok
);
1317 /* ============================ Maxmemory directive ======================== */
1319 /* This function gets called when 'maxmemory' is set on the config file to limit
1320 * the max memory used by the server, and we are out of memory.
1321 * This function will try to, in order:
1323 * - Free objects from the free list
1324 * - Try to remove keys with an EXPIRE set
1326 * It is not possible to free enough memory to reach used-memory < maxmemory
1327 * the server will start refusing commands that will enlarge even more the
1330 void freeMemoryIfNeeded(void) {
1331 /* Remove keys accordingly to the active policy as long as we are
1332 * over the memory limit. */
1333 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1335 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1336 int j
, k
, freed
= 0;
1338 for (j
= 0; j
< server
.dbnum
; j
++) {
1339 long bestval
= 0; /* just to prevent warning */
1341 struct dictEntry
*de
;
1342 redisDb
*db
= server
.db
+j
;
1345 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1346 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1348 dict
= server
.db
[j
].dict
;
1350 dict
= server
.db
[j
].expires
;
1352 if (dictSize(dict
) == 0) continue;
1354 /* volatile-random and allkeys-random policy */
1355 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1356 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1358 de
= dictGetRandomKey(dict
);
1359 bestkey
= dictGetEntryKey(de
);
1362 /* volatile-lru and allkeys-lru policy */
1363 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1364 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1366 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1371 de
= dictGetRandomKey(dict
);
1372 thiskey
= dictGetEntryKey(de
);
1373 /* When policy is volatile-lru we need an additonal lookup
1374 * to locate the real key, as dict is set to db->expires. */
1375 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1376 de
= dictFind(db
->dict
, thiskey
);
1377 o
= dictGetEntryVal(de
);
1378 thisval
= estimateObjectIdleTime(o
);
1380 /* Higher idle time is better candidate for deletion */
1381 if (bestkey
== NULL
|| thisval
> bestval
) {
1389 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1390 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1394 de
= dictGetRandomKey(dict
);
1395 thiskey
= dictGetEntryKey(de
);
1396 thisval
= (long) dictGetEntryVal(de
);
1398 /* Expire sooner (minor expire unix timestamp) is better
1399 * candidate for deletion */
1400 if (bestkey
== NULL
|| thisval
< bestval
) {
1407 /* Finally remove the selected key. */
1409 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1410 dbDelete(db
,keyobj
);
1411 server
.stat_expiredkeys
++;
1412 decrRefCount(keyobj
);
1416 if (!freed
) return; /* nothing to free... */
1420 int j
, k
, freed
= 0;
1421 for (j
= 0; j
< server
.dbnum
; j
++) {
1424 robj
*keyobj
= NULL
;
1425 struct dictEntry
*de
;
1427 if (dictSize(server
.db
[j
].expires
)) {
1429 /* From a sample of three keys drop the one nearest to
1430 * the natural expire */
1431 for (k
= 0; k
< 3; k
++) {
1434 de
= dictGetRandomKey(server
.db
[j
].expires
);
1435 t
= (time_t) dictGetEntryVal(de
);
1436 if (minttl
== -1 || t
< minttl
) {
1437 minkey
= dictGetEntryKey(de
);
1441 keyobj
= createStringObject(minkey
,sdslen(minkey
));
1442 dbDelete(server
.db
+j
,keyobj
);
1443 server
.stat_expiredkeys
++;
1444 decrRefCount(keyobj
);
1447 if (!freed
) return; /* nothing to free... */
1451 /* =================================== Main! ================================ */
1454 int linuxOvercommitMemoryValue(void) {
1455 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1459 if (fgets(buf
,64,fp
) == NULL
) {
1468 void linuxOvercommitMemoryWarning(void) {
1469 if (linuxOvercommitMemoryValue() == 0) {
1470 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.");
1473 #endif /* __linux__ */
1475 void createPidFile(void) {
1476 /* Try to write the pid file in a best-effort way. */
1477 FILE *fp
= fopen(server
.pidfile
,"w");
1479 fprintf(fp
,"%d\n",getpid());
1484 void daemonize(void) {
1487 if (fork() != 0) exit(0); /* parent exits */
1488 setsid(); /* create a new session */
1490 /* Every output goes to /dev/null. If Redis is daemonized but
1491 * the 'logfile' is set to 'stdout' in the configuration file
1492 * it will not log at all. */
1493 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1494 dup2(fd
, STDIN_FILENO
);
1495 dup2(fd
, STDOUT_FILENO
);
1496 dup2(fd
, STDERR_FILENO
);
1497 if (fd
> STDERR_FILENO
) close(fd
);
1502 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1503 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1508 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1509 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1513 int main(int argc
, char **argv
) {
1518 if (strcmp(argv
[1], "-v") == 0 ||
1519 strcmp(argv
[1], "--version") == 0) version();
1520 if (strcmp(argv
[1], "--help") == 0) usage();
1521 resetServerSaveParams();
1522 loadServerConfig(argv
[1]);
1523 } else if ((argc
> 2)) {
1526 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'");
1528 if (server
.daemonize
) daemonize();
1530 if (server
.daemonize
) createPidFile();
1531 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1533 linuxOvercommitMemoryWarning();
1536 if (server
.appendonly
) {
1537 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1538 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
1540 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1541 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
1543 if (server
.ipfd
> 0)
1544 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1545 if (server
.sofd
> 0)
1546 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1547 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1549 aeDeleteEventLoop(server
.el
);
1553 /* ============================= Backtrace support ========================= */
1555 #ifdef HAVE_BACKTRACE
1556 void *getMcontextEip(ucontext_t
*uc
) {
1557 #if defined(__FreeBSD__)
1558 return (void*) uc
->uc_mcontext
.mc_eip
;
1559 #elif defined(__dietlibc__)
1560 return (void*) uc
->uc_mcontext
.eip
;
1561 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1563 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1565 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1567 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1568 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1569 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1571 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1573 #elif defined(__i386__)
1574 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1575 #elif defined(__X86_64__) || defined(__x86_64__)
1576 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1577 #elif defined(__ia64__) /* Linux IA64 */
1578 return (void*) uc
->uc_mcontext
.sc_ip
;
1584 void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1586 char **messages
= NULL
;
1587 int i
, trace_size
= 0;
1588 ucontext_t
*uc
= (ucontext_t
*) secret
;
1590 struct sigaction act
;
1591 REDIS_NOTUSED(info
);
1593 redisLog(REDIS_WARNING
,
1594 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1595 infostring
= genRedisInfoString();
1596 redisLog(REDIS_WARNING
, "%s",infostring
);
1597 /* It's not safe to sdsfree() the returned string under memory
1598 * corruption conditions. Let it leak as we are going to abort */
1600 trace_size
= backtrace(trace
, 100);
1601 /* overwrite sigaction with caller's address */
1602 if (getMcontextEip(uc
) != NULL
) {
1603 trace
[1] = getMcontextEip(uc
);
1605 messages
= backtrace_symbols(trace
, trace_size
);
1607 for (i
=1; i
<trace_size
; ++i
)
1608 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1610 /* free(messages); Don't call free() with possibly corrupted memory. */
1611 if (server
.daemonize
) unlink(server
.pidfile
);
1613 /* Make sure we exit with the right signal at the end. So for instance
1614 * the core will be dumped if enabled. */
1615 sigemptyset (&act
.sa_mask
);
1616 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1617 * is used. Otherwise, sa_handler is used */
1618 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1619 act
.sa_handler
= SIG_DFL
;
1620 sigaction (sig
, &act
, NULL
);
1624 void sigtermHandler(int sig
) {
1627 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
1628 server
.shutdown_asap
= 1;
1631 void setupSigSegvAction(void) {
1632 struct sigaction act
;
1634 sigemptyset (&act
.sa_mask
);
1635 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1636 * is used. Otherwise, sa_handler is used */
1637 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1638 act
.sa_sigaction
= segvHandler
;
1639 sigaction (SIGSEGV
, &act
, NULL
);
1640 sigaction (SIGBUS
, &act
, NULL
);
1641 sigaction (SIGFPE
, &act
, NULL
);
1642 sigaction (SIGILL
, &act
, NULL
);
1643 sigaction (SIGBUS
, &act
, NULL
);
1645 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1646 act
.sa_handler
= sigtermHandler
;
1647 sigaction (SIGTERM
, &act
, NULL
);
1651 #else /* HAVE_BACKTRACE */
1652 void setupSigSegvAction(void) {
1654 #endif /* HAVE_BACKTRACE */