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 {"incr",incrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
82 {"decr",decrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
83 {"mget",mgetCommand
,-2,0,NULL
,1,-1,1},
84 {"rpush",rpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
85 {"lpush",lpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
86 {"rpushx",rpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
87 {"lpushx",lpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
88 {"linsert",linsertCommand
,5,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
89 {"rpop",rpopCommand
,2,0,NULL
,1,1,1},
90 {"lpop",lpopCommand
,2,0,NULL
,1,1,1},
91 {"brpop",brpopCommand
,-3,0,NULL
,1,1,1},
92 {"brpoplpush",brpoplpushCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,2,1},
93 {"blpop",blpopCommand
,-3,0,NULL
,1,1,1},
94 {"llen",llenCommand
,2,0,NULL
,1,1,1},
95 {"lindex",lindexCommand
,3,0,NULL
,1,1,1},
96 {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
97 {"lrange",lrangeCommand
,4,0,NULL
,1,1,1},
98 {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1},
99 {"lrem",lremCommand
,4,0,NULL
,1,1,1},
100 {"rpoplpush",rpoplpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1},
101 {"sadd",saddCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
102 {"srem",sremCommand
,3,0,NULL
,1,1,1},
103 {"smove",smoveCommand
,4,0,NULL
,1,2,1},
104 {"sismember",sismemberCommand
,3,0,NULL
,1,1,1},
105 {"scard",scardCommand
,2,0,NULL
,1,1,1},
106 {"spop",spopCommand
,2,0,NULL
,1,1,1},
107 {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1},
108 {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
109 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
110 {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
111 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
112 {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
113 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
114 {"smembers",sinterCommand
,2,0,NULL
,1,1,1},
115 {"zadd",zaddCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
116 {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
117 {"zrem",zremCommand
,3,0,NULL
,1,1,1},
118 {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1},
119 {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1},
120 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
121 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
122 {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1},
123 {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1},
124 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1},
125 {"zcount",zcountCommand
,4,0,NULL
,1,1,1},
126 {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1},
127 {"zcard",zcardCommand
,2,0,NULL
,1,1,1},
128 {"zscore",zscoreCommand
,3,0,NULL
,1,1,1},
129 {"zrank",zrankCommand
,3,0,NULL
,1,1,1},
130 {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1},
131 {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
132 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
133 {"hget",hgetCommand
,3,0,NULL
,1,1,1},
134 {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
135 {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1},
136 {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
137 {"hdel",hdelCommand
,3,0,NULL
,1,1,1},
138 {"hlen",hlenCommand
,2,0,NULL
,1,1,1},
139 {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1},
140 {"hvals",hvalsCommand
,2,0,NULL
,1,1,1},
141 {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1},
142 {"hexists",hexistsCommand
,3,0,NULL
,1,1,1},
143 {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
144 {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
145 {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
146 {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
147 {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
148 {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0},
149 {"select",selectCommand
,2,0,NULL
,0,0,0},
150 {"move",moveCommand
,3,0,NULL
,1,1,1},
151 {"rename",renameCommand
,3,0,NULL
,1,1,1},
152 {"renamenx",renamenxCommand
,3,0,NULL
,1,1,1},
153 {"expire",expireCommand
,3,0,NULL
,0,0,0},
154 {"expireat",expireatCommand
,3,0,NULL
,0,0,0},
155 {"keys",keysCommand
,2,0,NULL
,0,0,0},
156 {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0},
157 {"auth",authCommand
,2,0,NULL
,0,0,0},
158 {"ping",pingCommand
,1,0,NULL
,0,0,0},
159 {"echo",echoCommand
,2,0,NULL
,0,0,0},
160 {"save",saveCommand
,1,0,NULL
,0,0,0},
161 {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0},
162 {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0},
163 {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0},
164 {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0},
165 {"type",typeCommand
,2,0,NULL
,1,1,1},
166 {"multi",multiCommand
,1,0,NULL
,0,0,0},
167 {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
168 {"discard",discardCommand
,1,0,NULL
,0,0,0},
169 {"sync",syncCommand
,1,0,NULL
,0,0,0},
170 {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0},
171 {"flushall",flushallCommand
,1,0,NULL
,0,0,0},
172 {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
173 {"info",infoCommand
,1,0,NULL
,0,0,0},
174 {"monitor",monitorCommand
,1,0,NULL
,0,0,0},
175 {"ttl",ttlCommand
,2,0,NULL
,1,1,1},
176 {"persist",persistCommand
,2,0,NULL
,1,1,1},
177 {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0},
178 {"debug",debugCommand
,-2,0,NULL
,0,0,0},
179 {"config",configCommand
,-2,0,NULL
,0,0,0},
180 {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0},
181 {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0},
182 {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0},
183 {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0},
184 {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
185 {"watch",watchCommand
,-2,0,NULL
,0,0,0},
186 {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0}
189 /*============================ Utility functions ============================ */
191 void redisLog(int level
, const char *fmt
, ...) {
198 if (level
< server
.verbosity
) return;
200 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
205 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
206 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
207 vfprintf(fp
, fmt
, ap
);
212 if (server
.logfile
) fclose(fp
);
215 /* Redis generally does not try to recover from out of memory conditions
216 * when allocating objects or strings, it is not clear if it will be possible
217 * to report this condition to the client since the networking layer itself
218 * is based on heap allocation for send buffers, so we simply abort.
219 * At least the code will be simpler to read... */
220 void oom(const char *msg
) {
221 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
226 /*====================== Hash table type implementation ==================== */
228 /* This is an hash table type that uses the SDS dynamic strings libary as
229 * keys and radis objects as values (objects can hold SDS strings,
232 void dictVanillaFree(void *privdata
, void *val
)
234 DICT_NOTUSED(privdata
);
238 void dictListDestructor(void *privdata
, void *val
)
240 DICT_NOTUSED(privdata
);
241 listRelease((list
*)val
);
244 int dictSdsKeyCompare(void *privdata
, const void *key1
,
248 DICT_NOTUSED(privdata
);
250 l1
= sdslen((sds
)key1
);
251 l2
= sdslen((sds
)key2
);
252 if (l1
!= l2
) return 0;
253 return memcmp(key1
, key2
, l1
) == 0;
256 /* A case insensitive version used for the command lookup table. */
257 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
,
260 DICT_NOTUSED(privdata
);
262 return strcasecmp(key1
, key2
) == 0;
265 void dictRedisObjectDestructor(void *privdata
, void *val
)
267 DICT_NOTUSED(privdata
);
269 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
273 void dictSdsDestructor(void *privdata
, void *val
)
275 DICT_NOTUSED(privdata
);
280 int dictObjKeyCompare(void *privdata
, const void *key1
,
283 const robj
*o1
= key1
, *o2
= key2
;
284 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
287 unsigned int dictObjHash(const void *key
) {
289 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
292 unsigned int dictSdsHash(const void *key
) {
293 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
296 unsigned int dictSdsCaseHash(const void *key
) {
297 return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
));
300 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
303 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
306 if (o1
->encoding
== REDIS_ENCODING_INT
&&
307 o2
->encoding
== REDIS_ENCODING_INT
)
308 return o1
->ptr
== o2
->ptr
;
310 o1
= getDecodedObject(o1
);
311 o2
= getDecodedObject(o2
);
312 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
318 unsigned int dictEncObjHash(const void *key
) {
319 robj
*o
= (robj
*) key
;
321 if (o
->encoding
== REDIS_ENCODING_RAW
) {
322 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
324 if (o
->encoding
== REDIS_ENCODING_INT
) {
328 len
= ll2string(buf
,32,(long)o
->ptr
);
329 return dictGenHashFunction((unsigned char*)buf
, len
);
333 o
= getDecodedObject(o
);
334 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
342 dictType setDictType
= {
343 dictEncObjHash
, /* hash function */
346 dictEncObjKeyCompare
, /* key compare */
347 dictRedisObjectDestructor
, /* key destructor */
348 NULL
/* val destructor */
351 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
352 dictType zsetDictType
= {
353 dictEncObjHash
, /* hash function */
356 dictEncObjKeyCompare
, /* key compare */
357 dictRedisObjectDestructor
, /* key destructor */
358 NULL
/* val destructor */
361 /* Db->dict, keys are sds strings, vals are Redis objects. */
362 dictType dbDictType
= {
363 dictSdsHash
, /* hash function */
366 dictSdsKeyCompare
, /* key compare */
367 dictSdsDestructor
, /* key destructor */
368 dictRedisObjectDestructor
/* val destructor */
372 dictType keyptrDictType
= {
373 dictSdsHash
, /* hash function */
376 dictSdsKeyCompare
, /* key compare */
377 NULL
, /* key destructor */
378 NULL
/* val destructor */
381 /* Command table. sds string -> command struct pointer. */
382 dictType commandTableDictType
= {
383 dictSdsCaseHash
, /* hash function */
386 dictSdsKeyCaseCompare
, /* key compare */
387 dictSdsDestructor
, /* key destructor */
388 NULL
/* val destructor */
391 /* Hash type hash table (note that small hashes are represented with zimpaps) */
392 dictType hashDictType
= {
393 dictEncObjHash
, /* hash function */
396 dictEncObjKeyCompare
, /* key compare */
397 dictRedisObjectDestructor
, /* key destructor */
398 dictRedisObjectDestructor
/* val destructor */
401 /* Keylist hash table type has unencoded redis objects as keys and
402 * lists as values. It's used for blocking operations (BLPOP) and to
403 * map swapped keys to a list of clients waiting for this keys to be loaded. */
404 dictType keylistDictType
= {
405 dictObjHash
, /* hash function */
408 dictObjKeyCompare
, /* key compare */
409 dictRedisObjectDestructor
, /* key destructor */
410 dictListDestructor
/* val destructor */
413 int htNeedsResize(dict
*dict
) {
414 long long size
, used
;
416 size
= dictSlots(dict
);
417 used
= dictSize(dict
);
418 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
419 (used
*100/size
< REDIS_HT_MINFILL
));
422 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
423 * we resize the hash table to save memory */
424 void tryResizeHashTables(void) {
427 for (j
= 0; j
< server
.dbnum
; j
++) {
428 if (htNeedsResize(server
.db
[j
].dict
))
429 dictResize(server
.db
[j
].dict
);
430 if (htNeedsResize(server
.db
[j
].expires
))
431 dictResize(server
.db
[j
].expires
);
435 /* Our hash table implementation performs rehashing incrementally while
436 * we write/read from the hash table. Still if the server is idle, the hash
437 * table will use two tables for a long time. So we try to use 1 millisecond
438 * of CPU time at every serverCron() loop in order to rehash some key. */
439 void incrementallyRehash(void) {
442 for (j
= 0; j
< server
.dbnum
; j
++) {
443 if (dictIsRehashing(server
.db
[j
].dict
)) {
444 dictRehashMilliseconds(server
.db
[j
].dict
,1);
445 break; /* already used our millisecond for this loop... */
450 /* This function is called once a background process of some kind terminates,
451 * as we want to avoid resizing the hash tables when there is a child in order
452 * to play well with copy-on-write (otherwise when a resize happens lots of
453 * memory pages are copied). The goal of this function is to update the ability
454 * for dict.c to resize the hash tables accordingly to the fact we have o not
456 void updateDictResizePolicy(void) {
457 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
463 /* ======================= Cron: called every 100 ms ======================== */
465 /* Try to expire a few timed out keys. The algorithm used is adaptive and
466 * will use few CPU cycles if there are few expiring keys, otherwise
467 * it will get more aggressive to avoid that too much memory is used by
468 * keys that can be removed from the keyspace. */
469 void activeExpireCycle(void) {
472 for (j
= 0; j
< server
.dbnum
; j
++) {
474 redisDb
*db
= server
.db
+j
;
476 /* Continue to expire if at the end of the cycle more than 25%
477 * of the keys were expired. */
479 long num
= dictSize(db
->expires
);
480 time_t now
= time(NULL
);
483 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
484 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
489 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
490 t
= (time_t) dictGetEntryVal(de
);
492 sds key
= dictGetEntryKey(de
);
493 robj
*keyobj
= createStringObject(key
,sdslen(key
));
495 propagateExpire(db
,keyobj
);
497 decrRefCount(keyobj
);
499 server
.stat_expiredkeys
++;
502 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
506 void updateLRUClock(void) {
507 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
511 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
512 int j
, loops
= server
.cronloops
++;
513 REDIS_NOTUSED(eventLoop
);
515 REDIS_NOTUSED(clientData
);
517 /* We take a cached value of the unix time in the global state because
518 * with virtual memory and aging there is to store the current time
519 * in objects at every object access, and accuracy is not needed.
520 * To access a global var is faster than calling time(NULL) */
521 server
.unixtime
= time(NULL
);
522 /* We have just 22 bits per object for LRU information.
523 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
524 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
526 * Note that even if this will wrap after 1.5 years it's not a problem,
527 * everything will still work but just some object will appear younger
528 * to Redis. But for this to happen a given object should never be touched
531 * Note that you can change the resolution altering the
532 * REDIS_LRU_CLOCK_RESOLUTION define.
536 /* We received a SIGTERM, shutting down here in a safe way, as it is
537 * not ok doing so inside the signal handler. */
538 if (server
.shutdown_asap
) {
539 if (prepareForShutdown() == REDIS_OK
) exit(0);
540 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
543 /* Show some info about non-empty databases */
544 for (j
= 0; j
< server
.dbnum
; j
++) {
545 long long size
, used
, vkeys
;
547 size
= dictSlots(server
.db
[j
].dict
);
548 used
= dictSize(server
.db
[j
].dict
);
549 vkeys
= dictSize(server
.db
[j
].expires
);
550 if (!(loops
% 50) && (used
|| vkeys
)) {
551 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
552 /* dictPrintStats(server.dict); */
556 /* We don't want to resize the hash tables while a bacground saving
557 * is in progress: the saving child is created using fork() that is
558 * implemented with a copy-on-write semantic in most modern systems, so
559 * if we resize the HT while there is the saving child at work actually
560 * a lot of memory movements in the parent will cause a lot of pages
562 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
563 if (!(loops
% 10)) tryResizeHashTables();
564 if (server
.activerehashing
) incrementallyRehash();
567 /* Show information about connected clients */
569 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
570 listLength(server
.clients
)-listLength(server
.slaves
),
571 listLength(server
.slaves
),
572 zmalloc_used_memory());
575 /* Close connections of timedout clients */
576 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
577 closeTimedoutClients();
579 /* Check if a background saving or AOF rewrite in progress terminated */
580 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
584 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
585 if (pid
== server
.bgsavechildpid
) {
586 backgroundSaveDoneHandler(statloc
);
588 backgroundRewriteDoneHandler(statloc
);
590 updateDictResizePolicy();
593 /* If there is not a background saving in progress check if
594 * we have to save now */
595 time_t now
= time(NULL
);
596 for (j
= 0; j
< server
.saveparamslen
; j
++) {
597 struct saveparam
*sp
= server
.saveparams
+j
;
599 if (server
.dirty
>= sp
->changes
&&
600 now
-server
.lastsave
> sp
->seconds
) {
601 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
602 sp
->changes
, sp
->seconds
);
603 rdbSaveBackground(server
.dbfilename
);
609 /* Expire a few keys per cycle, only if this is a master.
610 * On slaves we wait for DEL operations synthesized by the master
611 * in order to guarantee a strict consistency. */
612 if (server
.masterhost
== NULL
) activeExpireCycle();
614 /* Swap a few keys on disk if we are over the memory limit and VM
615 * is enbled. Try to free objects from the free list first. */
616 if (vmCanSwapOut()) {
617 while (server
.vm_enabled
&& zmalloc_used_memory() >
618 server
.vm_max_memory
)
620 int retval
= (server
.vm_max_threads
== 0) ?
621 vmSwapOneObjectBlocking() :
622 vmSwapOneObjectThreaded();
623 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
624 zmalloc_used_memory() >
625 (server
.vm_max_memory
+server
.vm_max_memory
/10))
627 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
629 /* Note that when using threade I/O we free just one object,
630 * because anyway when the I/O thread in charge to swap this
631 * object out will finish, the handler of completed jobs
632 * will try to swap more objects if we are still out of memory. */
633 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
637 /* Replication cron function -- used to reconnect to master and
638 * to detect transfer failures. */
639 if (!(loops
% 10)) replicationCron();
644 /* This function gets called every time Redis is entering the
645 * main loop of the event driven library, that is, before to sleep
646 * for ready file descriptors. */
647 void beforeSleep(struct aeEventLoop
*eventLoop
) {
648 REDIS_NOTUSED(eventLoop
);
650 /* Awake clients that got all the swapped keys they requested */
651 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
655 listRewind(server
.io_ready_clients
,&li
);
656 while((ln
= listNext(&li
))) {
657 redisClient
*c
= ln
->value
;
658 struct redisCommand
*cmd
;
660 /* Resume the client. */
661 listDelNode(server
.io_ready_clients
,ln
);
662 c
->flags
&= (~REDIS_IO_WAIT
);
663 server
.vm_blocked_clients
--;
664 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
665 readQueryFromClient
, c
);
666 cmd
= lookupCommand(c
->argv
[0]->ptr
);
667 redisAssert(cmd
!= NULL
);
670 /* There may be more data to process in the input buffer. */
671 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
672 processInputBuffer(c
);
675 /* Write the AOF buffer on disk */
676 flushAppendOnlyFile();
679 /* =========================== Server initialization ======================== */
681 void createSharedObjects(void) {
684 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
685 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
686 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
687 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
688 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
689 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
690 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
691 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
692 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
693 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
694 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
695 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
696 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
697 "-ERR Operation against a key holding the wrong kind of value\r\n"));
698 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
699 "-ERR no such key\r\n"));
700 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
701 "-ERR syntax error\r\n"));
702 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
703 "-ERR source and destination objects are the same\r\n"));
704 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
705 "-ERR index out of range\r\n"));
706 shared
.loadingerr
= createObject(REDIS_STRING
,sdsnew(
707 "-LOADING Redis is loading the dataset in memory\r\n"));
708 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
709 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
710 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
711 shared
.select0
= createStringObject("select 0\r\n",10);
712 shared
.select1
= createStringObject("select 1\r\n",10);
713 shared
.select2
= createStringObject("select 2\r\n",10);
714 shared
.select3
= createStringObject("select 3\r\n",10);
715 shared
.select4
= createStringObject("select 4\r\n",10);
716 shared
.select5
= createStringObject("select 5\r\n",10);
717 shared
.select6
= createStringObject("select 6\r\n",10);
718 shared
.select7
= createStringObject("select 7\r\n",10);
719 shared
.select8
= createStringObject("select 8\r\n",10);
720 shared
.select9
= createStringObject("select 9\r\n",10);
721 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
722 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
723 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
724 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
725 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
726 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
727 shared
.mbulk3
= createStringObject("*3\r\n",4);
728 shared
.mbulk4
= createStringObject("*4\r\n",4);
729 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
730 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
731 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
735 void initServerConfig() {
736 server
.port
= REDIS_SERVERPORT
;
737 server
.bindaddr
= NULL
;
738 server
.unixsocket
= NULL
;
741 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
742 server
.verbosity
= REDIS_VERBOSE
;
743 server
.maxidletime
= REDIS_MAXIDLETIME
;
744 server
.saveparams
= NULL
;
746 server
.logfile
= NULL
; /* NULL = log on standard output */
747 server
.glueoutputbuf
= 1;
748 server
.daemonize
= 0;
749 server
.appendonly
= 0;
750 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
751 server
.no_appendfsync_on_rewrite
= 0;
752 server
.lastfsync
= time(NULL
);
753 server
.appendfd
= -1;
754 server
.appendseldb
= -1; /* Make sure the first time will not match */
755 server
.pidfile
= zstrdup("/var/run/redis.pid");
756 server
.dbfilename
= zstrdup("dump.rdb");
757 server
.appendfilename
= zstrdup("appendonly.aof");
758 server
.requirepass
= NULL
;
759 server
.rdbcompression
= 1;
760 server
.activerehashing
= 1;
761 server
.maxclients
= 0;
762 server
.blpop_blocked_clients
= 0;
763 server
.maxmemory
= 0;
764 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
765 server
.maxmemory_samples
= 3;
766 server
.vm_enabled
= 0;
767 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
768 server
.vm_page_size
= 256; /* 256 bytes per page */
769 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
770 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
771 server
.vm_max_threads
= 4;
772 server
.vm_blocked_clients
= 0;
773 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
774 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
775 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
776 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
777 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
778 server
.shutdown_asap
= 0;
781 resetServerSaveParams();
783 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
784 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
785 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
786 /* Replication related */
788 server
.masterauth
= NULL
;
789 server
.masterhost
= NULL
;
790 server
.masterport
= 6379;
791 server
.master
= NULL
;
792 server
.replstate
= REDIS_REPL_NONE
;
793 server
.repl_serve_stale_data
= 1;
795 /* Double constants initialization */
797 R_PosInf
= 1.0/R_Zero
;
798 R_NegInf
= -1.0/R_Zero
;
799 R_Nan
= R_Zero
/R_Zero
;
801 /* Command table -- we intiialize it here as it is part of the
802 * initial configuration, since command names may be changed via
803 * redis.conf using the rename-command directive. */
804 server
.commands
= dictCreate(&commandTableDictType
,NULL
);
805 populateCommandTable();
806 server
.delCommand
= lookupCommandByCString("del");
807 server
.multiCommand
= lookupCommandByCString("multi");
813 signal(SIGHUP
, SIG_IGN
);
814 signal(SIGPIPE
, SIG_IGN
);
815 setupSigSegvAction();
817 server
.mainthread
= pthread_self();
818 server
.clients
= listCreate();
819 server
.slaves
= listCreate();
820 server
.monitors
= listCreate();
821 createSharedObjects();
822 server
.el
= aeCreateEventLoop();
823 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
824 server
.ipfd
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
);
825 if (server
.ipfd
== ANET_ERR
) {
826 redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
);
829 if (server
.unixsocket
!= NULL
) {
830 unlink(server
.unixsocket
); /* don't care if this fails */
831 server
.sofd
= anetUnixServer(server
.neterr
,server
.unixsocket
);
832 if (server
.sofd
== ANET_ERR
) {
833 redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
);
837 if (server
.ipfd
< 0 && server
.sofd
< 0) {
838 redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting.");
841 for (j
= 0; j
< server
.dbnum
; j
++) {
842 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
843 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
844 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
845 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
846 if (server
.vm_enabled
)
847 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
850 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
851 server
.pubsub_patterns
= listCreate();
852 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
853 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
854 server
.cronloops
= 0;
855 server
.bgsavechildpid
= -1;
856 server
.bgrewritechildpid
= -1;
857 server
.bgrewritebuf
= sdsempty();
858 server
.aofbuf
= sdsempty();
859 server
.lastsave
= time(NULL
);
861 server
.stat_numcommands
= 0;
862 server
.stat_numconnections
= 0;
863 server
.stat_expiredkeys
= 0;
864 server
.stat_starttime
= time(NULL
);
865 server
.stat_keyspace_misses
= 0;
866 server
.stat_keyspace_hits
= 0;
867 server
.unixtime
= time(NULL
);
868 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
869 if (server
.ipfd
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
,
870 acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event");
871 if (server
.sofd
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
,
872 acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event");
874 if (server
.appendonly
) {
875 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
876 if (server
.appendfd
== -1) {
877 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
883 if (server
.vm_enabled
) vmInit();
886 /* Populates the Redis Command Table starting from the hard coded list
887 * we have on top of redis.c file. */
888 void populateCommandTable(void) {
890 int numcommands
= sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
);
892 for (j
= 0; j
< numcommands
; j
++) {
893 struct redisCommand
*c
= readonlyCommandTable
+j
;
896 retval
= dictAdd(server
.commands
, sdsnew(c
->name
), c
);
897 assert(retval
== DICT_OK
);
901 /* ====================== Commands lookup and execution ===================== */
903 struct redisCommand
*lookupCommand(sds name
) {
904 return dictFetchValue(server
.commands
, name
);
907 struct redisCommand
*lookupCommandByCString(char *s
) {
908 struct redisCommand
*cmd
;
909 sds name
= sdsnew(s
);
911 cmd
= dictFetchValue(server
.commands
, name
);
916 /* Call() is the core of Redis execution of a command */
917 void call(redisClient
*c
, struct redisCommand
*cmd
) {
920 dirty
= server
.dirty
;
922 dirty
= server
.dirty
-dirty
;
924 if (server
.appendonly
&& dirty
)
925 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
926 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
927 listLength(server
.slaves
))
928 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
929 if (listLength(server
.monitors
))
930 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
931 server
.stat_numcommands
++;
934 /* If this function gets called we already read a whole
935 * command, argments are in the client argv/argc fields.
936 * processCommand() execute the command or prepare the
937 * server for a bulk read from the client.
939 * If 1 is returned the client is still alive and valid and
940 * and other operations can be performed by the caller. Otherwise
941 * if 0 is returned the client was destroied (i.e. after QUIT). */
942 int processCommand(redisClient
*c
) {
943 struct redisCommand
*cmd
;
945 /* The QUIT command is handled separately. Normal command procs will
946 * go through checking for replication and QUIT will cause trouble
947 * when FORCE_REPLICATION is enabled and would be implemented in
948 * a regular command proc. */
949 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
950 addReply(c
,shared
.ok
);
951 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
955 /* Now lookup the command and check ASAP about trivial error conditions
956 * such wrong arity, bad command name and so forth. */
957 cmd
= lookupCommand(c
->argv
[0]->ptr
);
959 addReplyErrorFormat(c
,"unknown command '%s'",
960 (char*)c
->argv
[0]->ptr
);
962 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
963 (c
->argc
< -cmd
->arity
)) {
964 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
969 /* Check if the user is authenticated */
970 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
971 addReplyError(c
,"operation not permitted");
975 /* Handle the maxmemory directive.
977 * First we try to free some memory if possible (if there are volatile
978 * keys in the dataset). If there are not the only thing we can do
979 * is returning an error. */
980 if (server
.maxmemory
) freeMemoryIfNeeded();
981 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
982 zmalloc_used_memory() > server
.maxmemory
)
984 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
988 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
989 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
991 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
992 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
993 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
997 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
998 * we are a slave with a broken link with master. */
999 if (server
.masterhost
&& server
.replstate
!= REDIS_REPL_CONNECTED
&&
1000 server
.repl_serve_stale_data
== 0 &&
1001 cmd
->proc
!= infoCommand
&& cmd
->proc
!= slaveofCommand
)
1004 "link with MASTER is down and slave-serve-stale-data is set to no");
1008 /* Loading DB? Return an error if the command is not INFO */
1009 if (server
.loading
&& cmd
->proc
!= infoCommand
) {
1010 addReply(c
, shared
.loadingerr
);
1014 /* Exec the command */
1015 if (c
->flags
& REDIS_MULTI
&&
1016 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
1017 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
1019 queueMultiCommand(c
,cmd
);
1020 addReply(c
,shared
.queued
);
1022 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
1023 blockClientOnSwappedKeys(c
,cmd
)) return REDIS_ERR
;
1029 /*================================== Shutdown =============================== */
1031 int prepareForShutdown() {
1032 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
1033 /* Kill the saving child if there is a background saving in progress.
1034 We want to avoid race conditions, for instance our saving child may
1035 overwrite the synchronous saving did by SHUTDOWN. */
1036 if (server
.bgsavechildpid
!= -1) {
1037 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
1038 kill(server
.bgsavechildpid
,SIGKILL
);
1039 rdbRemoveTempFile(server
.bgsavechildpid
);
1041 if (server
.appendonly
) {
1042 /* Append only file: fsync() the AOF and exit */
1043 aof_fsync(server
.appendfd
);
1044 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
1045 } else if (server
.saveparamslen
> 0) {
1046 /* Snapshotting. Perform a SYNC SAVE and exit */
1047 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
1048 /* Ooops.. error saving! The best we can do is to continue
1049 * operating. Note that if there was a background saving process,
1050 * in the next cron() Redis will be notified that the background
1051 * saving aborted, handling special stuff like slaves pending for
1052 * synchronization... */
1053 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1057 redisLog(REDIS_WARNING
,"Not saving DB.");
1059 if (server
.daemonize
) unlink(server
.pidfile
);
1060 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1064 /*================================== Commands =============================== */
1066 void authCommand(redisClient
*c
) {
1067 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1068 c
->authenticated
= 1;
1069 addReply(c
,shared
.ok
);
1071 c
->authenticated
= 0;
1072 addReplyError(c
,"invalid password");
1076 void pingCommand(redisClient
*c
) {
1077 addReply(c
,shared
.pong
);
1080 void echoCommand(redisClient
*c
) {
1081 addReplyBulk(c
,c
->argv
[1]);
1084 /* Convert an amount of bytes into a human readable string in the form
1085 * of 100B, 2G, 100M, 4K, and so forth. */
1086 void bytesToHuman(char *s
, unsigned long long n
) {
1091 sprintf(s
,"%lluB",n
);
1093 } else if (n
< (1024*1024)) {
1094 d
= (double)n
/(1024);
1095 sprintf(s
,"%.2fK",d
);
1096 } else if (n
< (1024LL*1024*1024)) {
1097 d
= (double)n
/(1024*1024);
1098 sprintf(s
,"%.2fM",d
);
1099 } else if (n
< (1024LL*1024*1024*1024)) {
1100 d
= (double)n
/(1024LL*1024*1024);
1101 sprintf(s
,"%.2fG",d
);
1105 /* Create the string returned by the INFO command. This is decoupled
1106 * by the INFO command itself as we need to report the same information
1107 * on memory corruption problems. */
1108 sds
genRedisInfoString(void) {
1110 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1113 struct rusage self_ru
, c_ru
;
1115 getrusage(RUSAGE_SELF
, &self_ru
);
1116 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1118 bytesToHuman(hmem
,zmalloc_used_memory());
1119 info
= sdscatprintf(sdsempty(),
1120 "redis_version:%s\r\n"
1121 "redis_git_sha1:%s\r\n"
1122 "redis_git_dirty:%d\r\n"
1124 "multiplexing_api:%s\r\n"
1125 "process_id:%ld\r\n"
1126 "uptime_in_seconds:%ld\r\n"
1127 "uptime_in_days:%ld\r\n"
1129 "used_cpu_sys:%.2f\r\n"
1130 "used_cpu_user:%.2f\r\n"
1131 "used_cpu_sys_childrens:%.2f\r\n"
1132 "used_cpu_user_childrens:%.2f\r\n"
1133 "connected_clients:%d\r\n"
1134 "connected_slaves:%d\r\n"
1135 "blocked_clients:%d\r\n"
1136 "used_memory:%zu\r\n"
1137 "used_memory_human:%s\r\n"
1138 "used_memory_rss:%zu\r\n"
1139 "mem_fragmentation_ratio:%.2f\r\n"
1140 "use_tcmalloc:%d\r\n"
1142 "aof_enabled:%d\r\n"
1143 "changes_since_last_save:%lld\r\n"
1144 "bgsave_in_progress:%d\r\n"
1145 "last_save_time:%ld\r\n"
1146 "bgrewriteaof_in_progress:%d\r\n"
1147 "total_connections_received:%lld\r\n"
1148 "total_commands_processed:%lld\r\n"
1149 "expired_keys:%lld\r\n"
1150 "keyspace_hits:%lld\r\n"
1151 "keyspace_misses:%lld\r\n"
1152 "hash_max_zipmap_entries:%zu\r\n"
1153 "hash_max_zipmap_value:%zu\r\n"
1154 "pubsub_channels:%ld\r\n"
1155 "pubsub_patterns:%u\r\n"
1160 strtol(redisGitDirty(),NULL
,10) > 0,
1161 (sizeof(long) == 8) ? "64" : "32",
1166 (unsigned long) server
.lruclock
,
1167 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1168 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1169 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1170 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1171 listLength(server
.clients
)-listLength(server
.slaves
),
1172 listLength(server
.slaves
),
1173 server
.blpop_blocked_clients
,
1174 zmalloc_used_memory(),
1177 zmalloc_get_fragmentation_ratio(),
1186 server
.bgsavechildpid
!= -1,
1188 server
.bgrewritechildpid
!= -1,
1189 server
.stat_numconnections
,
1190 server
.stat_numcommands
,
1191 server
.stat_expiredkeys
,
1192 server
.stat_keyspace_hits
,
1193 server
.stat_keyspace_misses
,
1194 server
.hash_max_zipmap_entries
,
1195 server
.hash_max_zipmap_value
,
1196 dictSize(server
.pubsub_channels
),
1197 listLength(server
.pubsub_patterns
),
1198 server
.vm_enabled
!= 0,
1199 server
.masterhost
== NULL
? "master" : "slave"
1201 if (server
.masterhost
) {
1202 info
= sdscatprintf(info
,
1203 "master_host:%s\r\n"
1204 "master_port:%d\r\n"
1205 "master_link_status:%s\r\n"
1206 "master_last_io_seconds_ago:%d\r\n"
1207 "master_sync_in_progress:%d\r\n"
1210 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1212 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1,
1213 server
.replstate
== REDIS_REPL_TRANSFER
1216 if (server
.replstate
== REDIS_REPL_TRANSFER
) {
1217 info
= sdscatprintf(info
,
1218 "master_sync_left_bytes:%ld\r\n"
1219 "master_sync_last_io_seconds_ago:%d\r\n"
1220 ,(long)server
.repl_transfer_left
,
1221 (int)(time(NULL
)-server
.repl_transfer_lastio
)
1225 if (server
.vm_enabled
) {
1227 info
= sdscatprintf(info
,
1228 "vm_conf_max_memory:%llu\r\n"
1229 "vm_conf_page_size:%llu\r\n"
1230 "vm_conf_pages:%llu\r\n"
1231 "vm_stats_used_pages:%llu\r\n"
1232 "vm_stats_swapped_objects:%llu\r\n"
1233 "vm_stats_swappin_count:%llu\r\n"
1234 "vm_stats_swappout_count:%llu\r\n"
1235 "vm_stats_io_newjobs_len:%lu\r\n"
1236 "vm_stats_io_processing_len:%lu\r\n"
1237 "vm_stats_io_processed_len:%lu\r\n"
1238 "vm_stats_io_active_threads:%lu\r\n"
1239 "vm_stats_blocked_clients:%lu\r\n"
1240 ,(unsigned long long) server
.vm_max_memory
,
1241 (unsigned long long) server
.vm_page_size
,
1242 (unsigned long long) server
.vm_pages
,
1243 (unsigned long long) server
.vm_stats_used_pages
,
1244 (unsigned long long) server
.vm_stats_swapped_objects
,
1245 (unsigned long long) server
.vm_stats_swapins
,
1246 (unsigned long long) server
.vm_stats_swapouts
,
1247 (unsigned long) listLength(server
.io_newjobs
),
1248 (unsigned long) listLength(server
.io_processing
),
1249 (unsigned long) listLength(server
.io_processed
),
1250 (unsigned long) server
.io_active_threads
,
1251 (unsigned long) server
.vm_blocked_clients
1255 if (server
.loading
) {
1257 time_t eta
, elapsed
;
1258 off_t remaining_bytes
= server
.loading_total_bytes
-
1259 server
.loading_loaded_bytes
;
1261 perc
= ((double)server
.loading_loaded_bytes
/
1262 server
.loading_total_bytes
) * 100;
1264 elapsed
= time(NULL
)-server
.loading_start_time
;
1266 eta
= 1; /* A fake 1 second figure if we don't have enough info */
1268 eta
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
;
1271 info
= sdscatprintf(info
,
1272 "loading_start_time:%ld\r\n"
1273 "loading_total_bytes:%llu\r\n"
1274 "loading_loaded_bytes:%llu\r\n"
1275 "loading_loaded_perc:%.2f\r\n"
1276 "loading_eta_seconds:%ld\r\n"
1277 ,(unsigned long) server
.loading_start_time
,
1278 (unsigned long long) server
.loading_total_bytes
,
1279 (unsigned long long) server
.loading_loaded_bytes
,
1284 for (j
= 0; j
< server
.dbnum
; j
++) {
1285 long long keys
, vkeys
;
1287 keys
= dictSize(server
.db
[j
].dict
);
1288 vkeys
= dictSize(server
.db
[j
].expires
);
1289 if (keys
|| vkeys
) {
1290 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1297 void infoCommand(redisClient
*c
) {
1298 sds info
= genRedisInfoString();
1299 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1300 (unsigned long)sdslen(info
)));
1301 addReplySds(c
,info
);
1302 addReply(c
,shared
.crlf
);
1305 void monitorCommand(redisClient
*c
) {
1306 /* ignore MONITOR if aleady slave or in monitor mode */
1307 if (c
->flags
& REDIS_SLAVE
) return;
1309 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1311 listAddNodeTail(server
.monitors
,c
);
1312 addReply(c
,shared
.ok
);
1315 /* ============================ Maxmemory directive ======================== */
1317 /* This function gets called when 'maxmemory' is set on the config file to limit
1318 * the max memory used by the server, and we are out of memory.
1319 * This function will try to, in order:
1321 * - Free objects from the free list
1322 * - Try to remove keys with an EXPIRE set
1324 * It is not possible to free enough memory to reach used-memory < maxmemory
1325 * the server will start refusing commands that will enlarge even more the
1328 void freeMemoryIfNeeded(void) {
1329 /* Remove keys accordingly to the active policy as long as we are
1330 * over the memory limit. */
1331 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_NO_EVICTION
) return;
1333 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1334 int j
, k
, freed
= 0;
1336 for (j
= 0; j
< server
.dbnum
; j
++) {
1337 long bestval
= 0; /* just to prevent warning */
1339 struct dictEntry
*de
;
1340 redisDb
*db
= server
.db
+j
;
1343 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1344 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1346 dict
= server
.db
[j
].dict
;
1348 dict
= server
.db
[j
].expires
;
1350 if (dictSize(dict
) == 0) continue;
1352 /* volatile-random and allkeys-random policy */
1353 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1354 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1356 de
= dictGetRandomKey(dict
);
1357 bestkey
= dictGetEntryKey(de
);
1360 /* volatile-lru and allkeys-lru policy */
1361 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1362 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1364 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1369 de
= dictGetRandomKey(dict
);
1370 thiskey
= dictGetEntryKey(de
);
1371 /* When policy is volatile-lru we need an additonal lookup
1372 * to locate the real key, as dict is set to db->expires. */
1373 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1374 de
= dictFind(db
->dict
, thiskey
);
1375 o
= dictGetEntryVal(de
);
1376 thisval
= estimateObjectIdleTime(o
);
1378 /* Higher idle time is better candidate for deletion */
1379 if (bestkey
== NULL
|| thisval
> bestval
) {
1387 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1388 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1392 de
= dictGetRandomKey(dict
);
1393 thiskey
= dictGetEntryKey(de
);
1394 thisval
= (long) dictGetEntryVal(de
);
1396 /* Expire sooner (minor expire unix timestamp) is better
1397 * candidate for deletion */
1398 if (bestkey
== NULL
|| thisval
< bestval
) {
1405 /* Finally remove the selected key. */
1407 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1408 dbDelete(db
,keyobj
);
1409 server
.stat_expiredkeys
++;
1410 decrRefCount(keyobj
);
1414 if (!freed
) return; /* nothing to free... */
1418 int j
, k
, freed
= 0;
1419 for (j
= 0; j
< server
.dbnum
; j
++) {
1422 robj
*keyobj
= NULL
;
1423 struct dictEntry
*de
;
1425 if (dictSize(server
.db
[j
].expires
)) {
1427 /* From a sample of three keys drop the one nearest to
1428 * the natural expire */
1429 for (k
= 0; k
< 3; k
++) {
1432 de
= dictGetRandomKey(server
.db
[j
].expires
);
1433 t
= (time_t) dictGetEntryVal(de
);
1434 if (minttl
== -1 || t
< minttl
) {
1435 minkey
= dictGetEntryKey(de
);
1439 keyobj
= createStringObject(minkey
,sdslen(minkey
));
1440 dbDelete(server
.db
+j
,keyobj
);
1441 server
.stat_expiredkeys
++;
1442 decrRefCount(keyobj
);
1445 if (!freed
) return; /* nothing to free... */
1449 /* =================================== Main! ================================ */
1452 int linuxOvercommitMemoryValue(void) {
1453 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1457 if (fgets(buf
,64,fp
) == NULL
) {
1466 void linuxOvercommitMemoryWarning(void) {
1467 if (linuxOvercommitMemoryValue() == 0) {
1468 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.");
1471 #endif /* __linux__ */
1473 void createPidFile(void) {
1474 /* Try to write the pid file in a best-effort way. */
1475 FILE *fp
= fopen(server
.pidfile
,"w");
1477 fprintf(fp
,"%d\n",getpid());
1482 void daemonize(void) {
1485 if (fork() != 0) exit(0); /* parent exits */
1486 setsid(); /* create a new session */
1488 /* Every output goes to /dev/null. If Redis is daemonized but
1489 * the 'logfile' is set to 'stdout' in the configuration file
1490 * it will not log at all. */
1491 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1492 dup2(fd
, STDIN_FILENO
);
1493 dup2(fd
, STDOUT_FILENO
);
1494 dup2(fd
, STDERR_FILENO
);
1495 if (fd
> STDERR_FILENO
) close(fd
);
1500 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1501 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1506 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1507 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1511 int main(int argc
, char **argv
) {
1516 if (strcmp(argv
[1], "-v") == 0 ||
1517 strcmp(argv
[1], "--version") == 0) version();
1518 if (strcmp(argv
[1], "--help") == 0) usage();
1519 resetServerSaveParams();
1520 loadServerConfig(argv
[1]);
1521 } else if ((argc
> 2)) {
1524 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'");
1526 if (server
.daemonize
) daemonize();
1528 if (server
.daemonize
) createPidFile();
1529 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1531 linuxOvercommitMemoryWarning();
1534 if (server
.appendonly
) {
1535 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1536 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
1538 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1539 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
1541 if (server
.ipfd
> 0)
1542 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1543 if (server
.sofd
> 0)
1544 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
);
1545 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1547 aeDeleteEventLoop(server
.el
);
1551 /* ============================= Backtrace support ========================= */
1553 #ifdef HAVE_BACKTRACE
1554 void *getMcontextEip(ucontext_t
*uc
) {
1555 #if defined(__FreeBSD__)
1556 return (void*) uc
->uc_mcontext
.mc_eip
;
1557 #elif defined(__dietlibc__)
1558 return (void*) uc
->uc_mcontext
.eip
;
1559 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1561 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1563 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1565 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1566 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1567 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1569 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1571 #elif defined(__i386__)
1572 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1573 #elif defined(__X86_64__) || defined(__x86_64__)
1574 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1575 #elif defined(__ia64__) /* Linux IA64 */
1576 return (void*) uc
->uc_mcontext
.sc_ip
;
1582 void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1584 char **messages
= NULL
;
1585 int i
, trace_size
= 0;
1586 ucontext_t
*uc
= (ucontext_t
*) secret
;
1588 struct sigaction act
;
1589 REDIS_NOTUSED(info
);
1591 redisLog(REDIS_WARNING
,
1592 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1593 infostring
= genRedisInfoString();
1594 redisLog(REDIS_WARNING
, "%s",infostring
);
1595 /* It's not safe to sdsfree() the returned string under memory
1596 * corruption conditions. Let it leak as we are going to abort */
1598 trace_size
= backtrace(trace
, 100);
1599 /* overwrite sigaction with caller's address */
1600 if (getMcontextEip(uc
) != NULL
) {
1601 trace
[1] = getMcontextEip(uc
);
1603 messages
= backtrace_symbols(trace
, trace_size
);
1605 for (i
=1; i
<trace_size
; ++i
)
1606 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1608 /* free(messages); Don't call free() with possibly corrupted memory. */
1609 if (server
.daemonize
) unlink(server
.pidfile
);
1611 /* Make sure we exit with the right signal at the end. So for instance
1612 * the core will be dumped if enabled. */
1613 sigemptyset (&act
.sa_mask
);
1614 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1615 * is used. Otherwise, sa_handler is used */
1616 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1617 act
.sa_handler
= SIG_DFL
;
1618 sigaction (sig
, &act
, NULL
);
1622 void sigtermHandler(int sig
) {
1625 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
1626 server
.shutdown_asap
= 1;
1629 void setupSigSegvAction(void) {
1630 struct sigaction act
;
1632 sigemptyset (&act
.sa_mask
);
1633 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1634 * is used. Otherwise, sa_handler is used */
1635 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1636 act
.sa_sigaction
= segvHandler
;
1637 sigaction (SIGSEGV
, &act
, NULL
);
1638 sigaction (SIGBUS
, &act
, NULL
);
1639 sigaction (SIGFPE
, &act
, NULL
);
1640 sigaction (SIGILL
, &act
, NULL
);
1641 sigaction (SIGBUS
, &act
, NULL
);
1643 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1644 act
.sa_handler
= sigtermHandler
;
1645 sigaction (SIGTERM
, &act
, NULL
);
1649 #else /* HAVE_BACKTRACE */
1650 void setupSigSegvAction(void) {
1652 #endif /* HAVE_BACKTRACE */