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 {"blpop",blpopCommand
,-3,0,NULL
,1,1,1},
97 {"llen",llenCommand
,2,0,NULL
,1,1,1},
98 {"lindex",lindexCommand
,3,0,NULL
,1,1,1},
99 {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
100 {"lrange",lrangeCommand
,4,0,NULL
,1,1,1},
101 {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1},
102 {"lrem",lremCommand
,4,0,NULL
,1,1,1},
103 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1},
104 {"sadd",saddCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
105 {"srem",sremCommand
,3,0,NULL
,1,1,1},
106 {"smove",smoveCommand
,4,0,NULL
,1,2,1},
107 {"sismember",sismemberCommand
,3,0,NULL
,1,1,1},
108 {"scard",scardCommand
,2,0,NULL
,1,1,1},
109 {"spop",spopCommand
,2,0,NULL
,1,1,1},
110 {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1},
111 {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
112 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
113 {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
114 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
115 {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
116 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
117 {"smembers",sinterCommand
,2,0,NULL
,1,1,1},
118 {"zadd",zaddCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
119 {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
120 {"zrem",zremCommand
,3,0,NULL
,1,1,1},
121 {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1},
122 {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1},
123 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
124 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
125 {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1},
126 {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1},
127 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1},
128 {"zcount",zcountCommand
,4,0,NULL
,1,1,1},
129 {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1},
130 {"zcard",zcardCommand
,2,0,NULL
,1,1,1},
131 {"zscore",zscoreCommand
,3,0,NULL
,1,1,1},
132 {"zrank",zrankCommand
,3,0,NULL
,1,1,1},
133 {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1},
134 {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
135 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
136 {"hget",hgetCommand
,3,0,NULL
,1,1,1},
137 {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
138 {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1},
139 {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
140 {"hdel",hdelCommand
,3,0,NULL
,1,1,1},
141 {"hlen",hlenCommand
,2,0,NULL
,1,1,1},
142 {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1},
143 {"hvals",hvalsCommand
,2,0,NULL
,1,1,1},
144 {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1},
145 {"hexists",hexistsCommand
,3,0,NULL
,1,1,1},
146 {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
147 {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
148 {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
149 {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
150 {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
151 {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0},
152 {"select",selectCommand
,2,0,NULL
,0,0,0},
153 {"move",moveCommand
,3,0,NULL
,1,1,1},
154 {"rename",renameCommand
,3,0,NULL
,1,1,1},
155 {"renamenx",renamenxCommand
,3,0,NULL
,1,1,1},
156 {"expire",expireCommand
,3,0,NULL
,0,0,0},
157 {"expireat",expireatCommand
,3,0,NULL
,0,0,0},
158 {"keys",keysCommand
,2,0,NULL
,0,0,0},
159 {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0},
160 {"auth",authCommand
,2,0,NULL
,0,0,0},
161 {"ping",pingCommand
,1,0,NULL
,0,0,0},
162 {"echo",echoCommand
,2,0,NULL
,0,0,0},
163 {"save",saveCommand
,1,0,NULL
,0,0,0},
164 {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0},
165 {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0},
166 {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0},
167 {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0},
168 {"type",typeCommand
,2,0,NULL
,1,1,1},
169 {"multi",multiCommand
,1,0,NULL
,0,0,0},
170 {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
171 {"discard",discardCommand
,1,0,NULL
,0,0,0},
172 {"sync",syncCommand
,1,0,NULL
,0,0,0},
173 {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0},
174 {"flushall",flushallCommand
,1,0,NULL
,0,0,0},
175 {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
176 {"info",infoCommand
,1,0,NULL
,0,0,0},
177 {"monitor",monitorCommand
,1,0,NULL
,0,0,0},
178 {"ttl",ttlCommand
,2,0,NULL
,1,1,1},
179 {"persist",persistCommand
,2,0,NULL
,1,1,1},
180 {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0},
181 {"debug",debugCommand
,-2,0,NULL
,0,0,0},
182 {"config",configCommand
,-2,0,NULL
,0,0,0},
183 {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0},
184 {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0},
185 {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0},
186 {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0},
187 {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
188 {"watch",watchCommand
,-2,0,NULL
,0,0,0},
189 {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0}
192 /*============================ Utility functions ============================ */
194 void redisLog(int level
, const char *fmt
, ...) {
201 if (level
< server
.verbosity
) return;
203 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
208 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
209 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
210 vfprintf(fp
, fmt
, ap
);
215 if (server
.logfile
) fclose(fp
);
218 /* Redis generally does not try to recover from out of memory conditions
219 * when allocating objects or strings, it is not clear if it will be possible
220 * to report this condition to the client since the networking layer itself
221 * is based on heap allocation for send buffers, so we simply abort.
222 * At least the code will be simpler to read... */
223 void oom(const char *msg
) {
224 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
229 /*====================== Hash table type implementation ==================== */
231 /* This is an hash table type that uses the SDS dynamic strings libary as
232 * keys and radis objects as values (objects can hold SDS strings,
235 void dictVanillaFree(void *privdata
, void *val
)
237 DICT_NOTUSED(privdata
);
241 void dictListDestructor(void *privdata
, void *val
)
243 DICT_NOTUSED(privdata
);
244 listRelease((list
*)val
);
247 int dictSdsKeyCompare(void *privdata
, const void *key1
,
251 DICT_NOTUSED(privdata
);
253 l1
= sdslen((sds
)key1
);
254 l2
= sdslen((sds
)key2
);
255 if (l1
!= l2
) return 0;
256 return memcmp(key1
, key2
, l1
) == 0;
259 /* A case insensitive version used for the command lookup table. */
260 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
263 DICT_NOTUSED(privdata
);
265 return strcasecmp(key1
, key2
) == 0;
268 void dictRedisObjectDestructor(void *privdata
, void *val
)
270 DICT_NOTUSED(privdata
);
272 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
276 void dictSdsDestructor(void *privdata
, void *val
)
278 DICT_NOTUSED(privdata
);
283 int dictObjKeyCompare(void *privdata
, const void *key1
,
286 const robj
*o1
= key1
, *o2
= key2
;
287 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
290 unsigned int dictObjHash(const void *key
) {
292 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
295 unsigned int dictSdsHash(const void *key
) {
296 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
299 unsigned int dictSdsCaseHash(const void *key
) {
300 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
303 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
306 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
309 if (o1
->encoding
== REDIS_ENCODING_INT
&&
310 o2
->encoding
== REDIS_ENCODING_INT
)
311 return o1
->ptr
== o2
->ptr
;
313 o1
= getDecodedObject(o1
);
314 o2
= getDecodedObject(o2
);
315 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
321 unsigned int dictEncObjHash(const void *key
) {
322 robj
*o
= (robj
*) key
;
324 if (o
->encoding
== REDIS_ENCODING_RAW
) {
325 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
327 if (o
->encoding
== REDIS_ENCODING_INT
) {
331 len
= ll2string(buf
,32,(long)o
->ptr
);
332 return dictGenHashFunction((unsigned char*)buf
, len
);
336 o
= getDecodedObject(o
);
337 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
345 dictType setDictType
= {
346 dictEncObjHash
, /* hash function */
349 dictEncObjKeyCompare
, /* key compare */
350 dictRedisObjectDestructor
, /* key destructor */
351 NULL
/* val destructor */
354 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
355 dictType zsetDictType
= {
356 dictEncObjHash
, /* hash function */
359 dictEncObjKeyCompare
, /* key compare */
360 dictRedisObjectDestructor
, /* key destructor */
361 NULL
/* val destructor */
364 /* Db->dict, keys are sds strings, vals are Redis objects. */
365 dictType dbDictType
= {
366 dictSdsHash
, /* hash function */
369 dictSdsKeyCompare
, /* key compare */
370 dictSdsDestructor
, /* key destructor */
371 dictRedisObjectDestructor
/* val destructor */
375 dictType keyptrDictType
= {
376 dictSdsHash
, /* hash function */
379 dictSdsKeyCompare
, /* key compare */
380 NULL
, /* key destructor */
381 NULL
/* val destructor */
384 /* Command table. sds string -> command struct pointer. */
385 dictType commandTableDictType
= {
386 dictSdsCaseHash
, /* hash function */
389 dictSdsKeyCaseCompare
, /* key compare */
390 dictSdsDestructor
, /* key destructor */
391 NULL
/* val destructor */
394 /* Hash type hash table (note that small hashes are represented with zimpaps) */
395 dictType hashDictType
= {
396 dictEncObjHash
, /* hash function */
399 dictEncObjKeyCompare
, /* key compare */
400 dictRedisObjectDestructor
, /* key destructor */
401 dictRedisObjectDestructor
/* val destructor */
404 /* Keylist hash table type has unencoded redis objects as keys and
405 * lists as values. It's used for blocking operations (BLPOP) and to
406 * map swapped keys to a list of clients waiting for this keys to be loaded. */
407 dictType keylistDictType
= {
408 dictObjHash
, /* hash function */
411 dictObjKeyCompare
, /* key compare */
412 dictRedisObjectDestructor
, /* key destructor */
413 dictListDestructor
/* val destructor */
416 int htNeedsResize(dict
*dict
) {
417 long long size
, used
;
419 size
= dictSlots(dict
);
420 used
= dictSize(dict
);
421 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
422 (used
*100/size
< REDIS_HT_MINFILL
));
425 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
426 * we resize the hash table to save memory */
427 void tryResizeHashTables(void) {
430 for (j
= 0; j
< server
.dbnum
; j
++) {
431 if (htNeedsResize(server
.db
[j
].dict
))
432 dictResize(server
.db
[j
].dict
);
433 if (htNeedsResize(server
.db
[j
].expires
))
434 dictResize(server
.db
[j
].expires
);
438 /* Our hash table implementation performs rehashing incrementally while
439 * we write/read from the hash table. Still if the server is idle, the hash
440 * table will use two tables for a long time. So we try to use 1 millisecond
441 * of CPU time at every serverCron() loop in order to rehash some key. */
442 void incrementallyRehash(void) {
445 for (j
= 0; j
< server
.dbnum
; j
++) {
446 if (dictIsRehashing(server
.db
[j
].dict
)) {
447 dictRehashMilliseconds(server
.db
[j
].dict
,1);
448 break; /* already used our millisecond for this loop... */
453 /* This function is called once a background process of some kind terminates,
454 * as we want to avoid resizing the hash tables when there is a child in order
455 * to play well with copy-on-write (otherwise when a resize happens lots of
456 * memory pages are copied). The goal of this function is to update the ability
457 * for dict.c to resize the hash tables accordingly to the fact we have o not
459 void updateDictResizePolicy(void) {
460 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
466 /* ======================= Cron: called every 100 ms ======================== */
468 /* Try to expire a few timed out keys. The algorithm used is adaptive and
469 * will use few CPU cycles if there are few expiring keys, otherwise
470 * it will get more aggressive to avoid that too much memory is used by
471 * keys that can be removed from the keyspace. */
472 void activeExpireCycle(void) {
475 for (j
= 0; j
< server
.dbnum
; j
++) {
477 redisDb
*db
= server
.db
+j
;
479 /* Continue to expire if at the end of the cycle more than 25%
480 * of the keys were expired. */
482 long num
= dictSize(db
->expires
);
483 time_t now
= time(NULL
);
486 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
487 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
492 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
493 t
= (time_t) dictGetEntryVal(de
);
495 sds key
= dictGetEntryKey(de
);
496 robj
*keyobj
= createStringObject(key
,sdslen(key
));
498 propagateExpire(db
,keyobj
);
500 decrRefCount(keyobj
);
502 server
.stat_expiredkeys
++;
505 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
509 void updateLRUClock(void) {
510 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
514 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
515 int j
, loops
= server
.cronloops
++;
516 REDIS_NOTUSED(eventLoop
);
518 REDIS_NOTUSED(clientData
);
520 /* We take a cached value of the unix time in the global state because
521 * with virtual memory and aging there is to store the current time
522 * in objects at every object access, and accuracy is not needed.
523 * To access a global var is faster than calling time(NULL) */
524 server
.unixtime
= time(NULL
);
525 /* We have just 22 bits per object for LRU information.
526 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
527 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
529 * Note that even if this will wrap after 1.5 years it's not a problem,
530 * everything will still work but just some object will appear younger
531 * to Redis. But for this to happen a given object should never be touched
534 * Note that you can change the resolution altering the
535 * REDIS_LRU_CLOCK_RESOLUTION define.
539 /* We received a SIGTERM, shutting down here in a safe way, as it is
540 * not ok doing so inside the signal handler. */
541 if (server
.shutdown_asap
) {
542 if (prepareForShutdown() == REDIS_OK
) exit(0);
543 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
546 /* Show some info about non-empty databases */
547 for (j
= 0; j
< server
.dbnum
; j
++) {
548 long long size
, used
, vkeys
;
550 size
= dictSlots(server
.db
[j
].dict
);
551 used
= dictSize(server
.db
[j
].dict
);
552 vkeys
= dictSize(server
.db
[j
].expires
);
553 if (!(loops
% 50) && (used
|| vkeys
)) {
554 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
555 /* dictPrintStats(server.dict); */
559 /* We don't want to resize the hash tables while a bacground saving
560 * is in progress: the saving child is created using fork() that is
561 * implemented with a copy-on-write semantic in most modern systems, so
562 * if we resize the HT while there is the saving child at work actually
563 * a lot of memory movements in the parent will cause a lot of pages
565 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
566 if (!(loops
% 10)) tryResizeHashTables();
567 if (server
.activerehashing
) incrementallyRehash();
570 /* Show information about connected clients */
572 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
573 listLength(server
.clients
)-listLength(server
.slaves
),
574 listLength(server
.slaves
),
575 zmalloc_used_memory());
578 /* Close connections of timedout clients */
579 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
580 closeTimedoutClients();
582 /* Check if a background saving or AOF rewrite in progress terminated */
583 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
587 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
588 if (pid
== server
.bgsavechildpid
) {
589 backgroundSaveDoneHandler(statloc
);
591 backgroundRewriteDoneHandler(statloc
);
593 updateDictResizePolicy();
596 /* If there is not a background saving in progress check if
597 * we have to save now */
598 time_t now
= time(NULL
);
599 for (j
= 0; j
< server
.saveparamslen
; j
++) {
600 struct saveparam
*sp
= server
.saveparams
+j
;
602 if (server
.dirty
>= sp
->changes
&&
603 now
-server
.lastsave
> sp
->seconds
) {
604 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
605 sp
->changes
, sp
->seconds
);
606 rdbSaveBackground(server
.dbfilename
);
612 /* Expire a few keys per cycle, only if this is a master.
613 * On slaves we wait for DEL operations synthesized by the master
614 * in order to guarantee a strict consistency. */
615 if (server
.masterhost
== NULL
) activeExpireCycle();
617 /* Swap a few keys on disk if we are over the memory limit and VM
618 * is enbled. Try to free objects from the free list first. */
619 if (vmCanSwapOut()) {
620 while (server
.vm_enabled
&& zmalloc_used_memory() >
621 server
.vm_max_memory
)
623 int retval
= (server
.vm_max_threads
== 0) ?
624 vmSwapOneObjectBlocking() :
625 vmSwapOneObjectThreaded();
626 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
627 zmalloc_used_memory() >
628 (server
.vm_max_memory
+server
.vm_max_memory
/10))
630 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
632 /* Note that when using threade I/O we free just one object,
633 * because anyway when the I/O thread in charge to swap this
634 * object out will finish, the handler of completed jobs
635 * will try to swap more objects if we are still out of memory. */
636 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
640 /* Replication cron function -- used to reconnect to master and
641 * to detect transfer failures. */
642 if (!(loops
% 10)) replicationCron();
647 /* This function gets called every time Redis is entering the
648 * main loop of the event driven library, that is, before to sleep
649 * for ready file descriptors. */
650 void beforeSleep(struct aeEventLoop
*eventLoop
) {
651 REDIS_NOTUSED(eventLoop
);
653 /* Awake clients that got all the swapped keys they requested */
654 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
658 listRewind(server
.io_ready_clients
,&li
);
659 while((ln
= listNext(&li
))) {
660 redisClient
*c
= ln
->value
;
661 struct redisCommand
*cmd
;
663 /* Resume the client. */
664 listDelNode(server
.io_ready_clients
,ln
);
665 c
->flags
&= (~REDIS_IO_WAIT
);
666 server
.vm_blocked_clients
--;
667 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
668 readQueryFromClient
, c
);
669 cmd
= lookupCommand(c
->argv
[0]->ptr
);
670 redisAssert(cmd
!= NULL
);
673 /* There may be more data to process in the input buffer. */
674 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
675 processInputBuffer(c
);
678 /* Write the AOF buffer on disk */
679 flushAppendOnlyFile();
682 /* =========================== Server initialization ======================== */
684 void createSharedObjects(void) {
687 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
688 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
689 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
690 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
691 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
692 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
693 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
694 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
695 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
696 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
697 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
698 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
699 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
700 "-ERR Operation against a key holding the wrong kind of value\r\n"));
701 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
702 "-ERR no such key\r\n"));
703 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
704 "-ERR syntax error\r\n"));
705 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
706 "-ERR source and destination objects are the same\r\n"));
707 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
708 "-ERR index out of range\r\n"));
709 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
710 "-LOADING Redis is loading the dataset in memory\r\n"));
711 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
712 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
713 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
714 shared
.select0
= createStringObject("select 0\r\n",10);
715 shared
.select1
= createStringObject("select 1\r\n",10);
716 shared
.select2
= createStringObject("select 2\r\n",10);
717 shared
.select3
= createStringObject("select 3\r\n",10);
718 shared
.select4
= createStringObject("select 4\r\n",10);
719 shared
.select5
= createStringObject("select 5\r\n",10);
720 shared
.select6
= createStringObject("select 6\r\n",10);
721 shared
.select7
= createStringObject("select 7\r\n",10);
722 shared
.select8
= createStringObject("select 8\r\n",10);
723 shared
.select9
= createStringObject("select 9\r\n",10);
724 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
725 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
726 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
727 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
728 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
729 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
730 shared
.mbulk3
= createStringObject("*3\r\n",4);
731 shared
.mbulk4
= createStringObject("*4\r\n",4);
732 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
733 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
734 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
738 void initServerConfig() {
739 server
.port
= REDIS_SERVERPORT
;
740 server
.bindaddr
= NULL
;
741 server
.unixsocket
= NULL
;
744 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
745 server
.verbosity
= REDIS_VERBOSE
;
746 server
.maxidletime
= REDIS_MAXIDLETIME
;
747 server
.saveparams
= NULL
;
749 server
.logfile
= NULL
; /* NULL = log on standard output */
750 server
.glueoutputbuf
= 1;
751 server
.daemonize
= 0;
752 server
.appendonly
= 0;
753 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
754 server
.no_appendfsync_on_rewrite
= 0;
755 server
.lastfsync
= time(NULL
);
756 server
.appendfd
= -1;
757 server
.appendseldb
= -1; /* Make sure the first time will not match */
758 server
.pidfile
= zstrdup("/var/run/redis.pid");
759 server
.dbfilename
= zstrdup("dump.rdb");
760 server
.appendfilename
= zstrdup("appendonly.aof");
761 server
.requirepass
= NULL
;
762 server
.rdbcompression
= 1;
763 server
.activerehashing
= 1;
764 server
.maxclients
= 0;
765 server
.blpop_blocked_clients
= 0;
766 server
.maxmemory
= 0;
767 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
768 server
.maxmemory_samples
= 3;
769 server
.vm_enabled
= 0;
770 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
771 server
.vm_page_size
= 256; /* 256 bytes per page */
772 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
773 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
774 server
.vm_max_threads
= 4;
775 server
.vm_blocked_clients
= 0;
776 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
777 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
778 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
779 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
780 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
781 server
.shutdown_asap
= 0;
784 resetServerSaveParams();
786 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
787 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
788 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
789 /* Replication related */
791 server
.masterauth
= NULL
;
792 server
.masterhost
= NULL
;
793 server
.masterport
= 6379;
794 server
.master
= NULL
;
795 server
.replstate
= REDIS_REPL_NONE
;
796 server
.repl_serve_stale_data
= 1;
798 /* Double constants initialization */
800 R_PosInf
= 1.0/R_Zero
;
801 R_NegInf
= -1.0/R_Zero
;
802 R_Nan
= R_Zero
/R_Zero
;
804 /* Command table -- we intiialize it here as it is part of the
805 * initial configuration, since command names may be changed via
806 * redis.conf using the rename-command directive. */
807 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
808 populateCommandTable();
809 server
.delCommand
= lookupCommandByCString("del");
810 server
.multiCommand
= lookupCommandByCString("multi");
816 signal(SIGHUP
, SIG_IGN
);
817 signal(SIGPIPE
, SIG_IGN
);
818 setupSigSegvAction();
820 server
.mainthread
= pthread_self();
821 server
.clients
= listCreate();
822 server
.slaves
= listCreate();
823 server
.monitors
= listCreate();
824 createSharedObjects();
825 server
.el
= aeCreateEventLoop();
826 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
827 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
828 if (server
.ipfd
== ANET_ERR
) {
829 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
832 if (server
.unixsocket
!= NULL
) {
833 unlink(server
.unixsocket
); /* don't care if this fails */
834 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
835 if (server
.sofd
== ANET_ERR
) {
836 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
840 if (server
.ipfd
< 0 && server
.sofd
< 0) {
841 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
844 for (j
= 0; j
< server
.dbnum
; j
++) {
845 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
846 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
847 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
848 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
849 if (server
.vm_enabled
)
850 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
853 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
854 server
.pubsub_patterns
= listCreate();
855 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
856 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
857 server
.cronloops
= 0;
858 server
.bgsavechildpid
= -1;
859 server
.bgrewritechildpid
= -1;
860 server
.bgrewritebuf
= sdsempty();
861 server
.aofbuf
= sdsempty();
862 server
.lastsave
= time(NULL
);
864 server
.stat_numcommands
= 0;
865 server
.stat_numconnections
= 0;
866 server
.stat_expiredkeys
= 0;
867 server
.stat_starttime
= time(NULL
);
868 server
.stat_keyspace_misses
= 0;
869 server
.stat_keyspace_hits
= 0;
870 server
.unixtime
= time(NULL
);
871 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
872 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
873 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
874 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
875 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
877 if (server
.appendonly
) {
878 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
879 if (server
.appendfd
== -1) {
880 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
886 if (server
.vm_enabled
) vmInit();
889 /* Populates the Redis Command Table starting from the hard coded list
890 * we have on top of redis.c file. */
891 void populateCommandTable(void) {
893 int numcommands
= sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
);
895 for (j
= 0; j
< numcommands
; j
++) {
896 struct redisCommand
*c
= readonlyCommandTable
+j
;
899 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
900 assert(retval
== DICT_OK
);
904 /* ====================== Commands lookup and execution ===================== */
906 struct redisCommand
*lookupCommand(sds name
) {
907 return dictFetchValue(server
.commands
, name
);
910 struct redisCommand
*lookupCommandByCString(char *s
) {
911 struct redisCommand
*cmd
;
912 sds name
= sdsnew(s
);
914 cmd
= dictFetchValue(server
.commands
, name
);
919 /* Call() is the core of Redis execution of a command */
920 void call(redisClient
*c
, struct redisCommand
*cmd
) {
923 dirty
= server
.dirty
;
925 dirty
= server
.dirty
-dirty
;
927 if (server
.appendonly
&& dirty
)
928 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
929 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
930 listLength(server
.slaves
))
931 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
932 if (listLength(server
.monitors
))
933 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
934 server
.stat_numcommands
++;
937 /* If this function gets called we already read a whole
938 * command, argments are in the client argv/argc fields.
939 * processCommand() execute the command or prepare the
940 * server for a bulk read from the client.
942 * If 1 is returned the client is still alive and valid and
943 * and other operations can be performed by the caller. Otherwise
944 * if 0 is returned the client was destroied (i.e. after QUIT). */
945 int processCommand(redisClient
*c
) {
946 struct redisCommand
*cmd
;
948 /* The QUIT command is handled separately. Normal command procs will
949 * go through checking for replication and QUIT will cause trouble
950 * when FORCE_REPLICATION is enabled and would be implemented in
951 * a regular command proc. */
952 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
953 addReply(c
,shared
.ok
);
954 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
958 /* Now lookup the command and check ASAP about trivial error conditions
959 * such wrong arity, bad command name and so forth. */
960 cmd
= lookupCommand(c
->argv
[0]->ptr
);
962 addReplyErrorFormat(c
,"unknown command '%s'",
963 (char*)c
->argv
[0]->ptr
);
965 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
966 (c
->argc
< -cmd
->arity
)) {
967 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
972 /* Check if the user is authenticated */
973 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
974 addReplyError(c
,"operation not permitted");
978 /* Handle the maxmemory directive.
980 * First we try to free some memory if possible (if there are volatile
981 * keys in the dataset). If there are not the only thing we can do
982 * is returning an error. */
983 if (server
.maxmemory
) freeMemoryIfNeeded();
984 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
985 zmalloc_used_memory() > server
.maxmemory
)
987 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
991 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
992 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
994 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
995 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
996 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1000 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1001 * we are a slave with a broken link with master. */
1002 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1003 server
.repl_serve_stale_data
== 0 &&
1004 cmd
->proc
!= infoCommand
&& cmd
->proc
!= slaveofCommand
)
1007 "link with MASTER is down and slave-serve-stale-data is set to no");
1011 /* Loading DB? Return an error if the command is not INFO */
1012 if (server
.loading
&& cmd
->proc
!= infoCommand
) {
1013 addReply(c
, shared
.loadingerr
);
1017 /* Exec the command */
1018 if (c
->flags
& REDIS_MULTI
&&
1019 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
1020 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
1022 queueMultiCommand(c
,cmd
);
1023 addReply(c
,shared
.queued
);
1025 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
1026 blockClientOnSwappedKeys(c
,cmd
)) return REDIS_ERR
;
1032 /*================================== Shutdown =============================== */
1034 int prepareForShutdown() {
1035 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1036 /* Kill the saving child if there is a background saving in progress.
1037 We want to avoid race conditions, for instance our saving child may
1038 overwrite the synchronous saving did by SHUTDOWN. */
1039 if (server
.bgsavechildpid
!= -1) {
1040 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
1041 kill(server
.bgsavechildpid
,SIGKILL
);
1042 rdbRemoveTempFile(server
.bgsavechildpid
);
1044 if (server
.appendonly
) {
1045 /* Append only file: fsync() the AOF and exit */
1046 aof_fsync(server
.appendfd
);
1047 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
1048 } else if (server
.saveparamslen
> 0) {
1049 /* Snapshotting. Perform a SYNC SAVE and exit */
1050 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1051 /* Ooops.. error saving! The best we can do is to continue
1052 * operating. Note that if there was a background saving process,
1053 * in the next cron() Redis will be notified that the background
1054 * saving aborted, handling special stuff like slaves pending for
1055 * synchronization... */
1056 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1060 redisLog(REDIS_WARNING
,"Not saving DB.");
1062 if (server
.daemonize
) unlink(server
.pidfile
);
1063 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1067 /*================================== Commands =============================== */
1069 void authCommand(redisClient
*c
) {
1070 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1071 c
->authenticated
= 1;
1072 addReply(c
,shared
.ok
);
1074 c
->authenticated
= 0;
1075 addReplyError(c
,"invalid password");
1079 void pingCommand(redisClient
*c
) {
1080 addReply(c
,shared
.pong
);
1083 void echoCommand(redisClient
*c
) {
1084 addReplyBulk(c
,c
->argv
[1]);
1087 /* Convert an amount of bytes into a human readable string in the form
1088 * of 100B, 2G, 100M, 4K, and so forth. */
1089 void bytesToHuman(char *s
, unsigned long long n
) {
1094 sprintf(s
,"%lluB",n
);
1096 } else if (n
< (1024*1024)) {
1097 d
= (double)n
/(1024);
1098 sprintf(s
,"%.2fK",d
);
1099 } else if (n
< (1024LL*1024*1024)) {
1100 d
= (double)n
/(1024*1024);
1101 sprintf(s
,"%.2fM",d
);
1102 } else if (n
< (1024LL*1024*1024*1024)) {
1103 d
= (double)n
/(1024LL*1024*1024);
1104 sprintf(s
,"%.2fG",d
);
1108 /* Create the string returned by the INFO command. This is decoupled
1109 * by the INFO command itself as we need to report the same information
1110 * on memory corruption problems. */
1111 sds
genRedisInfoString(void) {
1113 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1116 struct rusage self_ru
, c_ru
;
1118 getrusage(RUSAGE_SELF
, &self_ru
);
1119 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1121 bytesToHuman(hmem
,zmalloc_used_memory());
1122 info
= sdscatprintf(sdsempty(),
1123 "redis_version:%s\r\n"
1124 "redis_git_sha1:%s\r\n"
1125 "redis_git_dirty:%d\r\n"
1127 "multiplexing_api:%s\r\n"
1128 "process_id:%ld\r\n"
1129 "uptime_in_seconds:%ld\r\n"
1130 "uptime_in_days:%ld\r\n"
1132 "used_cpu_sys:%.2f\r\n"
1133 "used_cpu_user:%.2f\r\n"
1134 "used_cpu_sys_childrens:%.2f\r\n"
1135 "used_cpu_user_childrens:%.2f\r\n"
1136 "connected_clients:%d\r\n"
1137 "connected_slaves:%d\r\n"
1138 "blocked_clients:%d\r\n"
1139 "used_memory:%zu\r\n"
1140 "used_memory_human:%s\r\n"
1141 "used_memory_rss:%zu\r\n"
1142 "mem_fragmentation_ratio:%.2f\r\n"
1143 "use_tcmalloc:%d\r\n"
1145 "aof_enabled:%d\r\n"
1146 "changes_since_last_save:%lld\r\n"
1147 "bgsave_in_progress:%d\r\n"
1148 "last_save_time:%ld\r\n"
1149 "bgrewriteaof_in_progress:%d\r\n"
1150 "total_connections_received:%lld\r\n"
1151 "total_commands_processed:%lld\r\n"
1152 "expired_keys:%lld\r\n"
1153 "keyspace_hits:%lld\r\n"
1154 "keyspace_misses:%lld\r\n"
1155 "hash_max_zipmap_entries:%zu\r\n"
1156 "hash_max_zipmap_value:%zu\r\n"
1157 "pubsub_channels:%ld\r\n"
1158 "pubsub_patterns:%u\r\n"
1163 strtol(redisGitDirty(),NULL
,10) > 0,
1164 (sizeof(long) == 8) ? "64" : "32",
1169 (unsigned long) server
.lruclock
,
1170 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1171 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1172 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1173 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1174 listLength(server
.clients
)-listLength(server
.slaves
),
1175 listLength(server
.slaves
),
1176 server
.blpop_blocked_clients
,
1177 zmalloc_used_memory(),
1180 zmalloc_get_fragmentation_ratio(),
1189 server
.bgsavechildpid
!= -1,
1191 server
.bgrewritechildpid
!= -1,
1192 server
.stat_numconnections
,
1193 server
.stat_numcommands
,
1194 server
.stat_expiredkeys
,
1195 server
.stat_keyspace_hits
,
1196 server
.stat_keyspace_misses
,
1197 server
.hash_max_zipmap_entries
,
1198 server
.hash_max_zipmap_value
,
1199 dictSize(server
.pubsub_channels
),
1200 listLength(server
.pubsub_patterns
),
1201 server
.vm_enabled
!= 0,
1202 server
.masterhost
== NULL
? "master" : "slave"
1204 if (server
.masterhost
) {
1205 info
= sdscatprintf(info
,
1206 "master_host:%s\r\n"
1207 "master_port:%d\r\n"
1208 "master_link_status:%s\r\n"
1209 "master_last_io_seconds_ago:%d\r\n"
1210 "master_sync_in_progress:%d\r\n"
1213 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1215 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1216 server
.replstate
== REDIS_REPL_TRANSFER
1219 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1220 info
= sdscatprintf(info
,
1221 "master_sync_left_bytes:%ld\r\n"
1222 "master_sync_last_io_seconds_ago:%d\r\n"
1223 ,(long)server
.repl_transfer_left
,
1224 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1228 if (server
.vm_enabled
) {
1230 info
= sdscatprintf(info
,
1231 "vm_conf_max_memory:%llu\r\n"
1232 "vm_conf_page_size:%llu\r\n"
1233 "vm_conf_pages:%llu\r\n"
1234 "vm_stats_used_pages:%llu\r\n"
1235 "vm_stats_swapped_objects:%llu\r\n"
1236 "vm_stats_swappin_count:%llu\r\n"
1237 "vm_stats_swappout_count:%llu\r\n"
1238 "vm_stats_io_newjobs_len:%lu\r\n"
1239 "vm_stats_io_processing_len:%lu\r\n"
1240 "vm_stats_io_processed_len:%lu\r\n"
1241 "vm_stats_io_active_threads:%lu\r\n"
1242 "vm_stats_blocked_clients:%lu\r\n"
1243 ,(unsigned long long) server
.vm_max_memory
,
1244 (unsigned long long) server
.vm_page_size
,
1245 (unsigned long long) server
.vm_pages
,
1246 (unsigned long long) server
.vm_stats_used_pages
,
1247 (unsigned long long) server
.vm_stats_swapped_objects
,
1248 (unsigned long long) server
.vm_stats_swapins
,
1249 (unsigned long long) server
.vm_stats_swapouts
,
1250 (unsigned long) listLength(server
.io_newjobs
),
1251 (unsigned long) listLength(server
.io_processing
),
1252 (unsigned long) listLength(server
.io_processed
),
1253 (unsigned long) server
.io_active_threads
,
1254 (unsigned long) server
.vm_blocked_clients
1258 if (server
.loading
) {
1260 time_t eta
, elapsed
;
1261 off_t remaining_bytes
= server
.loading_total_bytes
-
1262 server
.loading_loaded_bytes
;
1264 perc
= ((double)server
.loading_loaded_bytes
/
1265 server
.loading_total_bytes
) * 100;
1267 elapsed
= time(NULL
)-server
.loading_start_time
;
1269 eta
= 1; /* A fake 1 second figure if we don't have enough info */
1271 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1274 info
= sdscatprintf(info
,
1275 "loading_start_time:%ld\r\n"
1276 "loading_total_bytes:%llu\r\n"
1277 "loading_loaded_bytes:%llu\r\n"
1278 "loading_loaded_perc:%.2f\r\n"
1279 "loading_eta_seconds:%ld\r\n"
1280 ,(unsigned long) server
.loading_start_time
,
1281 (unsigned long long) server
.loading_total_bytes
,
1282 (unsigned long long) server
.loading_loaded_bytes
,
1287 for (j
= 0; j
< server
.dbnum
; j
++) {
1288 long long keys
, vkeys
;
1290 keys
= dictSize(server
.db
[j
].dict
);
1291 vkeys
= dictSize(server
.db
[j
].expires
);
1292 if (keys
|| vkeys
) {
1293 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1300 void infoCommand(redisClient
*c
) {
1301 sds info
= genRedisInfoString();
1302 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1303 (unsigned long)sdslen(info
)));
1304 addReplySds(c
,info
);
1305 addReply(c
,shared
.crlf
);
1308 void monitorCommand(redisClient
*c
) {
1309 /* ignore MONITOR if aleady slave or in monitor mode */
1310 if (c
->flags
& REDIS_SLAVE
) return;
1312 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1314 listAddNodeTail(server
.monitors
,c
);
1315 addReply(c
,shared
.ok
);
1318 /* ============================ Maxmemory directive ======================== */
1320 /* This function gets called when 'maxmemory' is set on the config file to limit
1321 * the max memory used by the server, and we are out of memory.
1322 * This function will try to, in order:
1324 * - Free objects from the free list
1325 * - Try to remove keys with an EXPIRE set
1327 * It is not possible to free enough memory to reach used-memory < maxmemory
1328 * the server will start refusing commands that will enlarge even more the
1331 void freeMemoryIfNeeded(void) {
1332 /* Remove keys accordingly to the active policy as long as we are
1333 * over the memory limit. */
1334 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1336 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1337 int j
, k
, freed
= 0;
1339 for (j
= 0; j
< server
.dbnum
; j
++) {
1340 long bestval
= 0; /* just to prevent warning */
1342 struct dictEntry
*de
;
1343 redisDb
*db
= server
.db
+j
;
1346 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1347 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1349 dict
= server
.db
[j
].dict
;
1351 dict
= server
.db
[j
].expires
;
1353 if (dictSize(dict
) == 0) continue;
1355 /* volatile-random and allkeys-random policy */
1356 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1357 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1359 de
= dictGetRandomKey(dict
);
1360 bestkey
= dictGetEntryKey(de
);
1363 /* volatile-lru and allkeys-lru policy */
1364 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1365 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1367 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1372 de
= dictGetRandomKey(dict
);
1373 thiskey
= dictGetEntryKey(de
);
1374 /* When policy is volatile-lru we need an additonal lookup
1375 * to locate the real key, as dict is set to db->expires. */
1376 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1377 de
= dictFind(db
->dict
, thiskey
);
1378 o
= dictGetEntryVal(de
);
1379 thisval
= estimateObjectIdleTime(o
);
1381 /* Higher idle time is better candidate for deletion */
1382 if (bestkey
== NULL
|| thisval
> bestval
) {
1390 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1391 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1395 de
= dictGetRandomKey(dict
);
1396 thiskey
= dictGetEntryKey(de
);
1397 thisval
= (long) dictGetEntryVal(de
);
1399 /* Expire sooner (minor expire unix timestamp) is better
1400 * candidate for deletion */
1401 if (bestkey
== NULL
|| thisval
< bestval
) {
1408 /* Finally remove the selected key. */
1410 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1411 dbDelete(db
,keyobj
);
1412 server
.stat_expiredkeys
++;
1413 decrRefCount(keyobj
);
1417 if (!freed
) return; /* nothing to free... */
1421 int j
, k
, freed
= 0;
1422 for (j
= 0; j
< server
.dbnum
; j
++) {
1425 robj
*keyobj
= NULL
;
1426 struct dictEntry
*de
;
1428 if (dictSize(server
.db
[j
].expires
)) {
1430 /* From a sample of three keys drop the one nearest to
1431 * the natural expire */
1432 for (k
= 0; k
< 3; k
++) {
1435 de
= dictGetRandomKey(server
.db
[j
].expires
);
1436 t
= (time_t) dictGetEntryVal(de
);
1437 if (minttl
== -1 || t
< minttl
) {
1438 minkey
= dictGetEntryKey(de
);
1442 keyobj
= createStringObject(minkey
,sdslen(minkey
));
1443 dbDelete(server
.db
+j
,keyobj
);
1444 server
.stat_expiredkeys
++;
1445 decrRefCount(keyobj
);
1448 if (!freed
) return; /* nothing to free... */
1452 /* =================================== Main! ================================ */
1455 int linuxOvercommitMemoryValue(void) {
1456 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1460 if (fgets(buf
,64,fp
) == NULL
) {
1469 void linuxOvercommitMemoryWarning(void) {
1470 if (linuxOvercommitMemoryValue() == 0) {
1471 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.");
1474 #endif /* __linux__ */
1476 void createPidFile(void) {
1477 /* Try to write the pid file in a best-effort way. */
1478 FILE *fp
= fopen(server
.pidfile
,"w");
1480 fprintf(fp
,"%d\n",getpid());
1485 void daemonize(void) {
1488 if (fork() != 0) exit(0); /* parent exits */
1489 setsid(); /* create a new session */
1491 /* Every output goes to /dev/null. If Redis is daemonized but
1492 * the 'logfile' is set to 'stdout' in the configuration file
1493 * it will not log at all. */
1494 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1495 dup2(fd
, STDIN_FILENO
);
1496 dup2(fd
, STDOUT_FILENO
);
1497 dup2(fd
, STDERR_FILENO
);
1498 if (fd
> STDERR_FILENO
) close(fd
);
1503 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1504 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1509 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1510 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1514 int main(int argc
, char **argv
) {
1519 if (strcmp(argv
[1], "-v") == 0 ||
1520 strcmp(argv
[1], "--version") == 0) version();
1521 if (strcmp(argv
[1], "--help") == 0) usage();
1522 resetServerSaveParams();
1523 loadServerConfig(argv
[1]);
1524 } else if ((argc
> 2)) {
1527 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'");
1529 if (server
.daemonize
) daemonize();
1531 if (server
.daemonize
) createPidFile();
1532 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1534 linuxOvercommitMemoryWarning();
1537 if (server
.appendonly
) {
1538 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1539 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
1541 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1542 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
1544 if (server
.ipfd
> 0)
1545 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1546 if (server
.sofd
> 0)
1547 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1548 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1550 aeDeleteEventLoop(server
.el
);
1554 /* ============================= Backtrace support ========================= */
1556 #ifdef HAVE_BACKTRACE
1557 void *getMcontextEip(ucontext_t
*uc
) {
1558 #if defined(__FreeBSD__)
1559 return (void*) uc
->uc_mcontext
.mc_eip
;
1560 #elif defined(__dietlibc__)
1561 return (void*) uc
->uc_mcontext
.eip
;
1562 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1564 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1566 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1568 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1569 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1570 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1572 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1574 #elif defined(__i386__)
1575 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1576 #elif defined(__X86_64__) || defined(__x86_64__)
1577 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1578 #elif defined(__ia64__) /* Linux IA64 */
1579 return (void*) uc
->uc_mcontext
.sc_ip
;
1585 void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1587 char **messages
= NULL
;
1588 int i
, trace_size
= 0;
1589 ucontext_t
*uc
= (ucontext_t
*) secret
;
1591 struct sigaction act
;
1592 REDIS_NOTUSED(info
);
1594 redisLog(REDIS_WARNING
,
1595 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1596 infostring
= genRedisInfoString();
1597 redisLog(REDIS_WARNING
, "%s",infostring
);
1598 /* It's not safe to sdsfree() the returned string under memory
1599 * corruption conditions. Let it leak as we are going to abort */
1601 trace_size
= backtrace(trace
, 100);
1602 /* overwrite sigaction with caller's address */
1603 if (getMcontextEip(uc
) != NULL
) {
1604 trace
[1] = getMcontextEip(uc
);
1606 messages
= backtrace_symbols(trace
, trace_size
);
1608 for (i
=1; i
<trace_size
; ++i
)
1609 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1611 /* free(messages); Don't call free() with possibly corrupted memory. */
1612 if (server
.daemonize
) unlink(server
.pidfile
);
1614 /* Make sure we exit with the right signal at the end. So for instance
1615 * the core will be dumped if enabled. */
1616 sigemptyset (&act
.sa_mask
);
1617 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1618 * is used. Otherwise, sa_handler is used */
1619 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1620 act
.sa_handler
= SIG_DFL
;
1621 sigaction (sig
, &act
, NULL
);
1625 void sigtermHandler(int sig
) {
1628 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
1629 server
.shutdown_asap
= 1;
1632 void setupSigSegvAction(void) {
1633 struct sigaction act
;
1635 sigemptyset (&act
.sa_mask
);
1636 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1637 * is used. Otherwise, sa_handler is used */
1638 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1639 act
.sa_sigaction
= segvHandler
;
1640 sigaction (SIGSEGV
, &act
, NULL
);
1641 sigaction (SIGBUS
, &act
, NULL
);
1642 sigaction (SIGFPE
, &act
, NULL
);
1643 sigaction (SIGILL
, &act
, NULL
);
1644 sigaction (SIGBUS
, &act
, NULL
);
1646 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1647 act
.sa_handler
= sigtermHandler
;
1648 sigaction (SIGTERM
, &act
, NULL
);
1652 #else /* HAVE_BACKTRACE */
1653 void setupSigSegvAction(void) {
1655 #endif /* HAVE_BACKTRACE */