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 {"blpop",blpopCommand
,-3,0,NULL
,1,1,1},
93 {"llen",llenCommand
,2,0,NULL
,1,1,1},
94 {"lindex",lindexCommand
,3,0,NULL
,1,1,1},
95 {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
96 {"lrange",lrangeCommand
,4,0,NULL
,1,1,1},
97 {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1},
98 {"lrem",lremCommand
,4,0,NULL
,1,1,1},
99 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1},
100 {"sadd",saddCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
101 {"srem",sremCommand
,3,0,NULL
,1,1,1},
102 {"smove",smoveCommand
,4,0,NULL
,1,2,1},
103 {"sismember",sismemberCommand
,3,0,NULL
,1,1,1},
104 {"scard",scardCommand
,2,0,NULL
,1,1,1},
105 {"spop",spopCommand
,2,0,NULL
,1,1,1},
106 {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1},
107 {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
108 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
109 {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
110 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
111 {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
112 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
113 {"smembers",sinterCommand
,2,0,NULL
,1,1,1},
114 {"zadd",zaddCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
115 {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
116 {"zrem",zremCommand
,3,0,NULL
,1,1,1},
117 {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1},
118 {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1},
119 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
120 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
121 {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1},
122 {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1},
123 {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1},
124 {"zcount",zcountCommand
,4,0,NULL
,1,1,1},
125 {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1},
126 {"zcard",zcardCommand
,2,0,NULL
,1,1,1},
127 {"zscore",zscoreCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
128 {"zrank",zrankCommand
,3,0,NULL
,1,1,1},
129 {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1},
130 {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
131 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
132 {"hget",hgetCommand
,3,0,NULL
,1,1,1},
133 {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
134 {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1},
135 {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
136 {"hdel",hdelCommand
,3,0,NULL
,1,1,1},
137 {"hlen",hlenCommand
,2,0,NULL
,1,1,1},
138 {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1},
139 {"hvals",hvalsCommand
,2,0,NULL
,1,1,1},
140 {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1},
141 {"hexists",hexistsCommand
,3,0,NULL
,1,1,1},
142 {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
143 {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
144 {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
145 {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
146 {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
147 {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0},
148 {"select",selectCommand
,2,0,NULL
,0,0,0},
149 {"move",moveCommand
,3,0,NULL
,1,1,1},
150 {"rename",renameCommand
,3,0,NULL
,1,1,1},
151 {"renamenx",renamenxCommand
,3,0,NULL
,1,1,1},
152 {"expire",expireCommand
,3,0,NULL
,0,0,0},
153 {"expireat",expireatCommand
,3,0,NULL
,0,0,0},
154 {"keys",keysCommand
,2,0,NULL
,0,0,0},
155 {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0},
156 {"auth",authCommand
,2,0,NULL
,0,0,0},
157 {"ping",pingCommand
,1,0,NULL
,0,0,0},
158 {"echo",echoCommand
,2,0,NULL
,0,0,0},
159 {"save",saveCommand
,1,0,NULL
,0,0,0},
160 {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0},
161 {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0},
162 {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0},
163 {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0},
164 {"type",typeCommand
,2,0,NULL
,1,1,1},
165 {"multi",multiCommand
,1,0,NULL
,0,0,0},
166 {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
167 {"discard",discardCommand
,1,0,NULL
,0,0,0},
168 {"sync",syncCommand
,1,0,NULL
,0,0,0},
169 {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0},
170 {"flushall",flushallCommand
,1,0,NULL
,0,0,0},
171 {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1},
172 {"info",infoCommand
,1,0,NULL
,0,0,0},
173 {"monitor",monitorCommand
,1,0,NULL
,0,0,0},
174 {"ttl",ttlCommand
,2,0,NULL
,1,1,1},
175 {"persist",persistCommand
,2,0,NULL
,1,1,1},
176 {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0},
177 {"debug",debugCommand
,-2,0,NULL
,0,0,0},
178 {"config",configCommand
,-2,0,NULL
,0,0,0},
179 {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0},
180 {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0},
181 {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0},
182 {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0},
183 {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
184 {"watch",watchCommand
,-2,0,NULL
,0,0,0},
185 {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0}
188 /*============================ Utility functions ============================ */
190 void redisLog(int level
, const char *fmt
, ...) {
197 if (level
< server
.verbosity
) return;
199 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
204 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
205 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
206 vfprintf(fp
, fmt
, ap
);
211 if (server
.logfile
) fclose(fp
);
214 /* Redis generally does not try to recover from out of memory conditions
215 * when allocating objects or strings, it is not clear if it will be possible
216 * to report this condition to the client since the networking layer itself
217 * is based on heap allocation for send buffers, so we simply abort.
218 * At least the code will be simpler to read... */
219 void oom(const char *msg
) {
220 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
225 /*====================== Hash table type implementation ==================== */
227 /* This is an hash table type that uses the SDS dynamic strings libary as
228 * keys and radis objects as values (objects can hold SDS strings,
231 void dictVanillaFree(void *privdata
, void *val
)
233 DICT_NOTUSED(privdata
);
237 void dictListDestructor(void *privdata
, void *val
)
239 DICT_NOTUSED(privdata
);
240 listRelease((list
*)val
);
243 int dictSdsKeyCompare(void *privdata
, const void *key1
,
247 DICT_NOTUSED(privdata
);
249 l1
= sdslen((sds
)key1
);
250 l2
= sdslen((sds
)key2
);
251 if (l1
!= l2
) return 0;
252 return memcmp(key1
, key2
, l1
) == 0;
255 void dictRedisObjectDestructor(void *privdata
, void *val
)
257 DICT_NOTUSED(privdata
);
259 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
263 void dictSdsDestructor(void *privdata
, void *val
)
265 DICT_NOTUSED(privdata
);
270 int dictObjKeyCompare(void *privdata
, const void *key1
,
273 const robj
*o1
= key1
, *o2
= key2
;
274 return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
277 unsigned int dictObjHash(const void *key
) {
279 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
282 unsigned int dictSdsHash(const void *key
) {
283 return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
));
286 int dictEncObjKeyCompare(void *privdata
, const void *key1
,
289 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
292 if (o1
->encoding
== REDIS_ENCODING_INT
&&
293 o2
->encoding
== REDIS_ENCODING_INT
)
294 return o1
->ptr
== o2
->ptr
;
296 o1
= getDecodedObject(o1
);
297 o2
= getDecodedObject(o2
);
298 cmp
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
304 unsigned int dictEncObjHash(const void *key
) {
305 robj
*o
= (robj
*) key
;
307 if (o
->encoding
== REDIS_ENCODING_RAW
) {
308 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
310 if (o
->encoding
== REDIS_ENCODING_INT
) {
314 len
= ll2string(buf
,32,(long)o
->ptr
);
315 return dictGenHashFunction((unsigned char*)buf
, len
);
319 o
= getDecodedObject(o
);
320 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
328 dictType setDictType
= {
329 dictEncObjHash
, /* hash function */
332 dictEncObjKeyCompare
, /* key compare */
333 dictRedisObjectDestructor
, /* key destructor */
334 NULL
/* val destructor */
337 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
338 dictType zsetDictType
= {
339 dictEncObjHash
, /* hash function */
342 dictEncObjKeyCompare
, /* key compare */
343 dictRedisObjectDestructor
, /* key destructor */
344 NULL
/* val destructor */
347 /* Db->dict, keys are sds strings, vals are Redis objects. */
348 dictType dbDictType
= {
349 dictSdsHash
, /* hash function */
352 dictSdsKeyCompare
, /* key compare */
353 dictSdsDestructor
, /* key destructor */
354 dictRedisObjectDestructor
/* val destructor */
358 dictType keyptrDictType
= {
359 dictSdsHash
, /* hash function */
362 dictSdsKeyCompare
, /* key compare */
363 NULL
, /* key destructor */
364 NULL
/* val destructor */
367 /* Hash type hash table (note that small hashes are represented with zimpaps) */
368 dictType hashDictType
= {
369 dictEncObjHash
, /* hash function */
372 dictEncObjKeyCompare
, /* key compare */
373 dictRedisObjectDestructor
, /* key destructor */
374 dictRedisObjectDestructor
/* val destructor */
377 /* Keylist hash table type has unencoded redis objects as keys and
378 * lists as values. It's used for blocking operations (BLPOP) and to
379 * map swapped keys to a list of clients waiting for this keys to be loaded. */
380 dictType keylistDictType
= {
381 dictObjHash
, /* hash function */
384 dictObjKeyCompare
, /* key compare */
385 dictRedisObjectDestructor
, /* key destructor */
386 dictListDestructor
/* val destructor */
389 int htNeedsResize(dict
*dict
) {
390 long long size
, used
;
392 size
= dictSlots(dict
);
393 used
= dictSize(dict
);
394 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
395 (used
*100/size
< REDIS_HT_MINFILL
));
398 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
399 * we resize the hash table to save memory */
400 void tryResizeHashTables(void) {
403 for (j
= 0; j
< server
.dbnum
; j
++) {
404 if (htNeedsResize(server
.db
[j
].dict
))
405 dictResize(server
.db
[j
].dict
);
406 if (htNeedsResize(server
.db
[j
].expires
))
407 dictResize(server
.db
[j
].expires
);
411 /* Our hash table implementation performs rehashing incrementally while
412 * we write/read from the hash table. Still if the server is idle, the hash
413 * table will use two tables for a long time. So we try to use 1 millisecond
414 * of CPU time at every serverCron() loop in order to rehash some key. */
415 void incrementallyRehash(void) {
418 for (j
= 0; j
< server
.dbnum
; j
++) {
419 if (dictIsRehashing(server
.db
[j
].dict
)) {
420 dictRehashMilliseconds(server
.db
[j
].dict
,1);
421 break; /* already used our millisecond for this loop... */
426 /* This function is called once a background process of some kind terminates,
427 * as we want to avoid resizing the hash tables when there is a child in order
428 * to play well with copy-on-write (otherwise when a resize happens lots of
429 * memory pages are copied). The goal of this function is to update the ability
430 * for dict.c to resize the hash tables accordingly to the fact we have o not
432 void updateDictResizePolicy(void) {
433 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
439 /* ======================= Cron: called every 100 ms ======================== */
441 /* Try to expire a few timed out keys. The algorithm used is adaptive and
442 * will use few CPU cycles if there are few expiring keys, otherwise
443 * it will get more aggressive to avoid that too much memory is used by
444 * keys that can be removed from the keyspace. */
445 void activeExpireCycle(void) {
448 for (j
= 0; j
< server
.dbnum
; j
++) {
450 redisDb
*db
= server
.db
+j
;
452 /* Continue to expire if at the end of the cycle more than 25%
453 * of the keys were expired. */
455 long num
= dictSize(db
->expires
);
456 time_t now
= time(NULL
);
459 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
460 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
465 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
466 t
= (time_t) dictGetEntryVal(de
);
468 sds key
= dictGetEntryKey(de
);
469 robj
*keyobj
= createStringObject(key
,sdslen(key
));
471 propagateExpire(db
,keyobj
);
473 decrRefCount(keyobj
);
475 server
.stat_expiredkeys
++;
478 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
482 void updateLRUClock(void) {
483 server
.lruclock
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) &
487 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
488 int j
, loops
= server
.cronloops
++;
489 REDIS_NOTUSED(eventLoop
);
491 REDIS_NOTUSED(clientData
);
493 /* We take a cached value of the unix time in the global state because
494 * with virtual memory and aging there is to store the current time
495 * in objects at every object access, and accuracy is not needed.
496 * To access a global var is faster than calling time(NULL) */
497 server
.unixtime
= time(NULL
);
498 /* We have just 22 bits per object for LRU information.
499 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
500 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
502 * Note that even if this will wrap after 1.5 years it's not a problem,
503 * everything will still work but just some object will appear younger
504 * to Redis. But for this to happen a given object should never be touched
507 * Note that you can change the resolution altering the
508 * REDIS_LRU_CLOCK_RESOLUTION define.
512 /* We received a SIGTERM, shutting down here in a safe way, as it is
513 * not ok doing so inside the signal handler. */
514 if (server
.shutdown_asap
) {
515 if (prepareForShutdown() == REDIS_OK
) exit(0);
516 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
519 /* Show some info about non-empty databases */
520 for (j
= 0; j
< server
.dbnum
; j
++) {
521 long long size
, used
, vkeys
;
523 size
= dictSlots(server
.db
[j
].dict
);
524 used
= dictSize(server
.db
[j
].dict
);
525 vkeys
= dictSize(server
.db
[j
].expires
);
526 if (!(loops
% 50) && (used
|| vkeys
)) {
527 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
528 /* dictPrintStats(server.dict); */
532 /* We don't want to resize the hash tables while a bacground saving
533 * is in progress: the saving child is created using fork() that is
534 * implemented with a copy-on-write semantic in most modern systems, so
535 * if we resize the HT while there is the saving child at work actually
536 * a lot of memory movements in the parent will cause a lot of pages
538 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
539 if (!(loops
% 10)) tryResizeHashTables();
540 if (server
.activerehashing
) incrementallyRehash();
543 /* Show information about connected clients */
545 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
546 listLength(server
.clients
)-listLength(server
.slaves
),
547 listLength(server
.slaves
),
548 zmalloc_used_memory());
551 /* Close connections of timedout clients */
552 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
553 closeTimedoutClients();
555 /* Check if a background saving or AOF rewrite in progress terminated */
556 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
560 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
561 if (pid
== server
.bgsavechildpid
) {
562 backgroundSaveDoneHandler(statloc
);
564 backgroundRewriteDoneHandler(statloc
);
566 updateDictResizePolicy();
569 /* If there is not a background saving in progress check if
570 * we have to save now */
571 time_t now
= time(NULL
);
572 for (j
= 0; j
< server
.saveparamslen
; j
++) {
573 struct saveparam
*sp
= server
.saveparams
+j
;
575 if (server
.dirty
>= sp
->changes
&&
576 now
-server
.lastsave
> sp
->seconds
) {
577 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
578 sp
->changes
, sp
->seconds
);
579 rdbSaveBackground(server
.dbfilename
);
585 /* Expire a few keys per cycle, only if this is a master.
586 * On slaves we wait for DEL operations synthesized by the master
587 * in order to guarantee a strict consistency. */
588 if (server
.masterhost
== NULL
) activeExpireCycle();
590 /* Swap a few keys on disk if we are over the memory limit and VM
591 * is enbled. Try to free objects from the free list first. */
592 if (vmCanSwapOut()) {
593 while (server
.vm_enabled
&& zmalloc_used_memory() >
594 server
.vm_max_memory
)
598 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
599 retval
= (server
.vm_max_threads
== 0) ?
600 vmSwapOneObjectBlocking() :
601 vmSwapOneObjectThreaded();
602 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
603 zmalloc_used_memory() >
604 (server
.vm_max_memory
+server
.vm_max_memory
/10))
606 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
608 /* Note that when using threade I/O we free just one object,
609 * because anyway when the I/O thread in charge to swap this
610 * object out will finish, the handler of completed jobs
611 * will try to swap more objects if we are still out of memory. */
612 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
616 /* Check if we should connect to a MASTER */
617 if (server
.replstate
== REDIS_REPL_CONNECT
&& !(loops
% 10)) {
618 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
619 if (syncWithMaster() == REDIS_OK
) {
620 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
621 if (server
.appendonly
) rewriteAppendOnlyFileBackground();
625 /* Update fragmentation info, used for fast RSS estimation */
626 if (!(loops
% 10)) server
.fragmentation
= zmalloc_get_fragmentation_ratio();
630 /* This function gets called every time Redis is entering the
631 * main loop of the event driven library, that is, before to sleep
632 * for ready file descriptors. */
633 void beforeSleep(struct aeEventLoop
*eventLoop
) {
634 REDIS_NOTUSED(eventLoop
);
636 /* Awake clients that got all the swapped keys they requested */
637 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
641 listRewind(server
.io_ready_clients
,&li
);
642 while((ln
= listNext(&li
))) {
643 redisClient
*c
= ln
->value
;
644 struct redisCommand
*cmd
;
646 /* Resume the client. */
647 listDelNode(server
.io_ready_clients
,ln
);
648 c
->flags
&= (~REDIS_IO_WAIT
);
649 server
.vm_blocked_clients
--;
650 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
651 readQueryFromClient
, c
);
652 cmd
= lookupCommand(c
->argv
[0]->ptr
);
653 redisAssert(cmd
!= NULL
);
656 /* There may be more data to process in the input buffer. */
657 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
658 processInputBuffer(c
);
661 /* Write the AOF buffer on disk */
662 flushAppendOnlyFile();
665 /* =========================== Server initialization ======================== */
667 void createSharedObjects(void) {
670 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
671 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
672 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
673 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
674 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
675 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
676 shared
.cnegone
= createObject(REDIS_STRING
,sdsnew(":-1\r\n"));
677 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
678 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
679 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
680 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
681 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
682 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
683 "-ERR Operation against a key holding the wrong kind of value\r\n"));
684 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
685 "-ERR no such key\r\n"));
686 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
687 "-ERR syntax error\r\n"));
688 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
689 "-ERR source and destination objects are the same\r\n"));
690 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
691 "-ERR index out of range\r\n"));
692 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
693 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
694 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
695 shared
.select0
= createStringObject("select 0\r\n",10);
696 shared
.select1
= createStringObject("select 1\r\n",10);
697 shared
.select2
= createStringObject("select 2\r\n",10);
698 shared
.select3
= createStringObject("select 3\r\n",10);
699 shared
.select4
= createStringObject("select 4\r\n",10);
700 shared
.select5
= createStringObject("select 5\r\n",10);
701 shared
.select6
= createStringObject("select 6\r\n",10);
702 shared
.select7
= createStringObject("select 7\r\n",10);
703 shared
.select8
= createStringObject("select 8\r\n",10);
704 shared
.select9
= createStringObject("select 9\r\n",10);
705 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
706 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
707 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
708 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
709 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
710 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
711 shared
.mbulk3
= createStringObject("*3\r\n",4);
712 shared
.mbulk4
= createStringObject("*4\r\n",4);
713 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
714 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
715 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
719 void initServerConfig() {
720 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
721 server
.port
= REDIS_SERVERPORT
;
722 server
.verbosity
= REDIS_VERBOSE
;
723 server
.maxidletime
= REDIS_MAXIDLETIME
;
724 server
.saveparams
= NULL
;
725 server
.logfile
= NULL
; /* NULL = log on standard output */
726 server
.bindaddr
= NULL
;
727 server
.glueoutputbuf
= 1;
728 server
.daemonize
= 0;
729 server
.appendonly
= 0;
730 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
731 server
.no_appendfsync_on_rewrite
= 0;
732 server
.lastfsync
= time(NULL
);
733 server
.appendfd
= -1;
734 server
.appendseldb
= -1; /* Make sure the first time will not match */
735 server
.pidfile
= zstrdup("/var/run/redis.pid");
736 server
.dbfilename
= zstrdup("dump.rdb");
737 server
.appendfilename
= zstrdup("appendonly.aof");
738 server
.requirepass
= NULL
;
739 server
.rdbcompression
= 1;
740 server
.activerehashing
= 1;
741 server
.fragmentation
= 1;
742 server
.maxclients
= 0;
743 server
.blpop_blocked_clients
= 0;
744 server
.maxmemory
= 0;
745 server
.maxmemory_policy
= REDIS_MAXMEMORY_VOLATILE_LRU
;
746 server
.maxmemory_samples
= 3;
747 server
.vm_enabled
= 0;
748 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
749 server
.vm_page_size
= 256; /* 256 bytes per page */
750 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
751 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
752 server
.vm_max_threads
= 4;
753 server
.vm_blocked_clients
= 0;
754 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
755 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
756 server
.list_max_ziplist_entries
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
757 server
.list_max_ziplist_value
= REDIS_LIST_MAX_ZIPLIST_VALUE
;
758 server
.set_max_intset_entries
= REDIS_SET_MAX_INTSET_ENTRIES
;
759 server
.shutdown_asap
= 0;
762 resetServerSaveParams();
764 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
765 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
766 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
767 /* Replication related */
769 server
.masterauth
= NULL
;
770 server
.masterhost
= NULL
;
771 server
.masterport
= 6379;
772 server
.master
= NULL
;
773 server
.replstate
= REDIS_REPL_NONE
;
775 /* Double constants initialization */
777 R_PosInf
= 1.0/R_Zero
;
778 R_NegInf
= -1.0/R_Zero
;
779 R_Nan
= R_Zero
/R_Zero
;
785 signal(SIGHUP
, SIG_IGN
);
786 signal(SIGPIPE
, SIG_IGN
);
787 setupSigSegvAction();
789 server
.mainthread
= pthread_self();
790 server
.devnull
= fopen("/dev/null","w");
791 if (server
.devnull
== NULL
) {
792 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
795 server
.clients
= listCreate();
796 server
.slaves
= listCreate();
797 server
.monitors
= listCreate();
798 server
.objfreelist
= listCreate();
799 createSharedObjects();
800 server
.el
= aeCreateEventLoop();
801 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
802 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
803 if (server
.fd
== -1) {
804 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
807 for (j
= 0; j
< server
.dbnum
; j
++) {
808 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
809 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
810 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
811 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
812 if (server
.vm_enabled
)
813 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
816 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
817 server
.pubsub_patterns
= listCreate();
818 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
819 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
820 server
.cronloops
= 0;
821 server
.bgsavechildpid
= -1;
822 server
.bgrewritechildpid
= -1;
823 server
.bgrewritebuf
= sdsempty();
824 server
.aofbuf
= sdsempty();
825 server
.lastsave
= time(NULL
);
827 server
.stat_numcommands
= 0;
828 server
.stat_numconnections
= 0;
829 server
.stat_expiredkeys
= 0;
830 server
.stat_starttime
= time(NULL
);
831 server
.stat_keyspace_misses
= 0;
832 server
.stat_keyspace_hits
= 0;
833 server
.unixtime
= time(NULL
);
834 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
835 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
836 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
838 if (server
.appendonly
) {
839 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
840 if (server
.appendfd
== -1) {
841 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
847 if (server
.vm_enabled
) vmInit();
850 int qsortRedisCommands(const void *r1
, const void *r2
) {
852 ((struct redisCommand
*)r1
)->name
,
853 ((struct redisCommand
*)r2
)->name
);
856 void sortCommandTable() {
857 /* Copy and sort the read-only version of the command table */
858 commandTable
= (struct redisCommand
*)zmalloc(sizeof(readonlyCommandTable
));
859 memcpy(commandTable
,readonlyCommandTable
,sizeof(readonlyCommandTable
));
861 sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
),
862 sizeof(struct redisCommand
),qsortRedisCommands
);
865 /* ====================== Commands lookup and execution ===================== */
867 struct redisCommand
*lookupCommand(char *name
) {
868 struct redisCommand tmp
= {name
,NULL
,0,0,NULL
,0,0,0};
872 sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
),
873 sizeof(struct redisCommand
),
877 /* Call() is the core of Redis execution of a command */
878 void call(redisClient
*c
, struct redisCommand
*cmd
) {
881 dirty
= server
.dirty
;
883 dirty
= server
.dirty
-dirty
;
885 if (server
.appendonly
&& dirty
)
886 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
887 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
888 listLength(server
.slaves
))
889 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
890 if (listLength(server
.monitors
))
891 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
892 server
.stat_numcommands
++;
895 /* If this function gets called we already read a whole
896 * command, argments are in the client argv/argc fields.
897 * processCommand() execute the command or prepare the
898 * server for a bulk read from the client.
900 * If 1 is returned the client is still alive and valid and
901 * and other operations can be performed by the caller. Otherwise
902 * if 0 is returned the client was destroied (i.e. after QUIT). */
903 int processCommand(redisClient
*c
) {
904 struct redisCommand
*cmd
;
906 /* The QUIT command is handled separately. Normal command procs will
907 * go through checking for replication and QUIT will cause trouble
908 * when FORCE_REPLICATION is enabled and would be implemented in
909 * a regular command proc. */
910 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
911 addReply(c
,shared
.ok
);
912 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
916 /* Now lookup the command and check ASAP about trivial error conditions
917 * such wrong arity, bad command name and so forth. */
918 cmd
= lookupCommand(c
->argv
[0]->ptr
);
920 addReplyErrorFormat(c
,"unknown command '%s'",
921 (char*)c
->argv
[0]->ptr
);
923 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
924 (c
->argc
< -cmd
->arity
)) {
925 addReplyErrorFormat(c
,"wrong number of arguments for '%s' command",
930 /* Check if the user is authenticated */
931 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
932 addReplyError(c
,"operation not permitted");
936 /* Handle the maxmemory directive.
938 * First we try to free some memory if possible (if there are volatile
939 * keys in the dataset). If there are not the only thing we can do
940 * is returning an error. */
941 if (server
.maxmemory
) freeMemoryIfNeeded();
942 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
943 zmalloc_used_memory() > server
.maxmemory
)
945 addReplyError(c
,"command not allowed when used memory > 'maxmemory'");
949 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
950 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
952 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
953 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
954 addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
958 /* Exec the command */
959 if (c
->flags
& REDIS_MULTI
&&
960 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
961 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
963 queueMultiCommand(c
,cmd
);
964 addReply(c
,shared
.queued
);
966 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
967 blockClientOnSwappedKeys(c
,cmd
)) return REDIS_ERR
;
973 /*================================== Shutdown =============================== */
975 int prepareForShutdown() {
976 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
977 /* Kill the saving child if there is a background saving in progress.
978 We want to avoid race conditions, for instance our saving child may
979 overwrite the synchronous saving did by SHUTDOWN. */
980 if (server
.bgsavechildpid
!= -1) {
981 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
982 kill(server
.bgsavechildpid
,SIGKILL
);
983 rdbRemoveTempFile(server
.bgsavechildpid
);
985 if (server
.appendonly
) {
986 /* Append only file: fsync() the AOF and exit */
987 aof_fsync(server
.appendfd
);
988 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
989 } else if (server
.saveparamslen
> 0) {
990 /* Snapshotting. Perform a SYNC SAVE and exit */
991 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
992 /* Ooops.. error saving! The best we can do is to continue
993 * operating. Note that if there was a background saving process,
994 * in the next cron() Redis will be notified that the background
995 * saving aborted, handling special stuff like slaves pending for
996 * synchronization... */
997 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
1001 redisLog(REDIS_WARNING
,"Not saving DB.");
1003 if (server
.daemonize
) unlink(server
.pidfile
);
1004 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
1008 /*================================== Commands =============================== */
1010 void authCommand(redisClient
*c
) {
1011 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1012 c
->authenticated
= 1;
1013 addReply(c
,shared
.ok
);
1015 c
->authenticated
= 0;
1016 addReplyError(c
,"invalid password");
1020 void pingCommand(redisClient
*c
) {
1021 addReply(c
,shared
.pong
);
1024 void echoCommand(redisClient
*c
) {
1025 addReplyBulk(c
,c
->argv
[1]);
1028 /* Convert an amount of bytes into a human readable string in the form
1029 * of 100B, 2G, 100M, 4K, and so forth. */
1030 void bytesToHuman(char *s
, unsigned long long n
) {
1035 sprintf(s
,"%lluB",n
);
1037 } else if (n
< (1024*1024)) {
1038 d
= (double)n
/(1024);
1039 sprintf(s
,"%.2fK",d
);
1040 } else if (n
< (1024LL*1024*1024)) {
1041 d
= (double)n
/(1024*1024);
1042 sprintf(s
,"%.2fM",d
);
1043 } else if (n
< (1024LL*1024*1024*1024)) {
1044 d
= (double)n
/(1024LL*1024*1024);
1045 sprintf(s
,"%.2fG",d
);
1049 /* Create the string returned by the INFO command. This is decoupled
1050 * by the INFO command itself as we need to report the same information
1051 * on memory corruption problems. */
1052 sds
genRedisInfoString(void) {
1054 time_t uptime
= time(NULL
)-server
.stat_starttime
;
1057 struct rusage self_ru
, c_ru
;
1059 getrusage(RUSAGE_SELF
, &self_ru
);
1060 getrusage(RUSAGE_CHILDREN
, &c_ru
);
1062 bytesToHuman(hmem
,zmalloc_used_memory());
1063 info
= sdscatprintf(sdsempty(),
1064 "redis_version:%s\r\n"
1065 "redis_git_sha1:%s\r\n"
1066 "redis_git_dirty:%d\r\n"
1068 "multiplexing_api:%s\r\n"
1069 "process_id:%ld\r\n"
1070 "uptime_in_seconds:%ld\r\n"
1071 "uptime_in_days:%ld\r\n"
1073 "used_cpu_sys:%.2f\r\n"
1074 "used_cpu_user:%.2f\r\n"
1075 "used_cpu_sys_childrens:%.2f\r\n"
1076 "used_cpu_user_childrens:%.2f\r\n"
1077 "connected_clients:%d\r\n"
1078 "connected_slaves:%d\r\n"
1079 "blocked_clients:%d\r\n"
1080 "used_memory:%zu\r\n"
1081 "used_memory_human:%s\r\n"
1082 "used_memory_rss:%zu\r\n"
1083 "used_memory_estimated_rss:%zu\r\n"
1084 "mem_fragmentation_ratio:%.2f\r\n"
1085 "use_tcmalloc:%d\r\n"
1086 "changes_since_last_save:%lld\r\n"
1087 "bgsave_in_progress:%d\r\n"
1088 "last_save_time:%ld\r\n"
1089 "bgrewriteaof_in_progress:%d\r\n"
1090 "total_connections_received:%lld\r\n"
1091 "total_commands_processed:%lld\r\n"
1092 "expired_keys:%lld\r\n"
1093 "keyspace_hits:%lld\r\n"
1094 "keyspace_misses:%lld\r\n"
1095 "hash_max_zipmap_entries:%zu\r\n"
1096 "hash_max_zipmap_value:%zu\r\n"
1097 "pubsub_channels:%ld\r\n"
1098 "pubsub_patterns:%u\r\n"
1103 strtol(redisGitDirty(),NULL
,10) > 0,
1104 (sizeof(long) == 8) ? "64" : "32",
1109 (unsigned long) server
.lruclock
,
1110 (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000,
1111 (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000,
1112 (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000,
1113 (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000,
1114 listLength(server
.clients
)-listLength(server
.slaves
),
1115 listLength(server
.slaves
),
1116 server
.blpop_blocked_clients
,
1117 zmalloc_used_memory(),
1121 zmalloc_get_fragmentation_ratio(),
1128 server
.bgsavechildpid
!= -1,
1130 server
.bgrewritechildpid
!= -1,
1131 server
.stat_numconnections
,
1132 server
.stat_numcommands
,
1133 server
.stat_expiredkeys
,
1134 server
.stat_keyspace_hits
,
1135 server
.stat_keyspace_misses
,
1136 server
.hash_max_zipmap_entries
,
1137 server
.hash_max_zipmap_value
,
1138 dictSize(server
.pubsub_channels
),
1139 listLength(server
.pubsub_patterns
),
1140 server
.vm_enabled
!= 0,
1141 server
.masterhost
== NULL
? "master" : "slave"
1143 if (server
.masterhost
) {
1144 info
= sdscatprintf(info
,
1145 "master_host:%s\r\n"
1146 "master_port:%d\r\n"
1147 "master_link_status:%s\r\n"
1148 "master_last_io_seconds_ago:%d\r\n"
1151 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
1153 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
1156 if (server
.vm_enabled
) {
1158 info
= sdscatprintf(info
,
1159 "vm_conf_max_memory:%llu\r\n"
1160 "vm_conf_page_size:%llu\r\n"
1161 "vm_conf_pages:%llu\r\n"
1162 "vm_stats_used_pages:%llu\r\n"
1163 "vm_stats_swapped_objects:%llu\r\n"
1164 "vm_stats_swappin_count:%llu\r\n"
1165 "vm_stats_swappout_count:%llu\r\n"
1166 "vm_stats_io_newjobs_len:%lu\r\n"
1167 "vm_stats_io_processing_len:%lu\r\n"
1168 "vm_stats_io_processed_len:%lu\r\n"
1169 "vm_stats_io_active_threads:%lu\r\n"
1170 "vm_stats_blocked_clients:%lu\r\n"
1171 ,(unsigned long long) server
.vm_max_memory
,
1172 (unsigned long long) server
.vm_page_size
,
1173 (unsigned long long) server
.vm_pages
,
1174 (unsigned long long) server
.vm_stats_used_pages
,
1175 (unsigned long long) server
.vm_stats_swapped_objects
,
1176 (unsigned long long) server
.vm_stats_swapins
,
1177 (unsigned long long) server
.vm_stats_swapouts
,
1178 (unsigned long) listLength(server
.io_newjobs
),
1179 (unsigned long) listLength(server
.io_processing
),
1180 (unsigned long) listLength(server
.io_processed
),
1181 (unsigned long) server
.io_active_threads
,
1182 (unsigned long) server
.vm_blocked_clients
1186 for (j
= 0; j
< server
.dbnum
; j
++) {
1187 long long keys
, vkeys
;
1189 keys
= dictSize(server
.db
[j
].dict
);
1190 vkeys
= dictSize(server
.db
[j
].expires
);
1191 if (keys
|| vkeys
) {
1192 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
1199 void infoCommand(redisClient
*c
) {
1200 sds info
= genRedisInfoString();
1201 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
1202 (unsigned long)sdslen(info
)));
1203 addReplySds(c
,info
);
1204 addReply(c
,shared
.crlf
);
1207 void monitorCommand(redisClient
*c
) {
1208 /* ignore MONITOR if aleady slave or in monitor mode */
1209 if (c
->flags
& REDIS_SLAVE
) return;
1211 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
1213 listAddNodeTail(server
.monitors
,c
);
1214 addReply(c
,shared
.ok
);
1217 /* ============================ Maxmemory directive ======================== */
1219 /* Try to free one object form the pre-allocated objects free list.
1220 * This is useful under low mem conditions as by default we take 1 million
1221 * free objects allocated. On success REDIS_OK is returned, otherwise
1223 int tryFreeOneObjectFromFreelist(void) {
1226 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
1227 if (listLength(server
.objfreelist
)) {
1228 listNode
*head
= listFirst(server
.objfreelist
);
1229 o
= listNodeValue(head
);
1230 listDelNode(server
.objfreelist
,head
);
1231 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
1235 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
1240 /* A fast RSS sampling function.
1242 * The function is reasonably accurate while fast, since it uses the trick of
1243 * using the server.fragmentation ratio that is computed every second and
1244 * is the ratio between the RSS and our zmalloc() count of allocated bytes.
1246 * So in order to compute the current RSS used we just need to multiply
1247 * the zmalloc() memory reporting, that is as fast as reading a counter,
1248 * for the latest estimation of fragmentation.
1250 * The behavior of this function is also very desirable because it is
1251 * very responsive to memory changes: while the real RSS is actually measured
1252 * in pages, the RSS estimation will actually change even if just a few bytes
1253 * are freed, and this is a good property when the function is used in order
1254 * to evict keys for Virtual Memory of for 'maxmemory' directive.
1256 * Note that when the memory reported by zmalloc is smaller than the RSS
1257 * (that is, fragmentation < 1) this means that something is odd (many pages
1258 * swapped since the Redis instance is idle) and we consider the fragmentation
1260 size_t redisEstimateRSS(void) {
1261 size_t used
= zmalloc_used_memory();
1264 if (server
.fragmentation
< 1) return used
;
1265 maxfrag
= (float)SIZE_MAX
/ used
;
1267 /* If multiplying memory usage reported by zmalloc per fragmentation
1268 * ratio will lead to an overflow we just return SIZE_MAX. */
1269 if (maxfrag
< server
.fragmentation
) return SIZE_MAX
;
1271 return (size_t)((used
* server
.fragmentation
));
1274 /* This function gets called when 'maxmemory' is set on the config file to limit
1275 * the max memory used by the server, and we are out of memory.
1276 * This function will try to, in order:
1278 * - Free objects from the free list
1279 * - Try to remove keys with an EXPIRE set
1281 * It is not possible to free enough memory to reach used-memory < maxmemory
1282 * the server will start refusing commands that will enlarge even more the
1285 void freeMemoryIfNeeded(void) {
1286 /* Remove keys accordingly to the active policy as long as we are
1287 * over the memory limit. */
1288 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
1289 int j
, k
, freed
= 0;
1291 /* Basic strategy -- remove objects from the free list. */
1292 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1294 for (j
= 0; j
< server
.dbnum
; j
++) {
1295 long bestval
= 0; /* just to prevent warning */
1297 struct dictEntry
*de
;
1298 redisDb
*db
= server
.db
+j
;
1301 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1302 server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
)
1304 dict
= server
.db
[j
].dict
;
1306 dict
= server
.db
[j
].expires
;
1308 if (dictSize(dict
) == 0) continue;
1310 /* volatile-random and allkeys-random policy */
1311 if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
||
1312 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_RANDOM
)
1314 de
= dictGetRandomKey(dict
);
1315 bestkey
= dictGetEntryKey(de
);
1318 /* volatile-lru and allkeys-lru policy */
1319 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_ALLKEYS_LRU
||
1320 server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_LRU
)
1322 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1327 de
= dictGetRandomKey(dict
);
1328 thiskey
= dictGetEntryKey(de
);
1329 o
= dictGetEntryVal(de
);
1330 thisval
= estimateObjectIdleTime(o
);
1332 /* Higher idle time is better candidate for deletion */
1333 if (bestkey
== NULL
|| thisval
> bestval
) {
1341 else if (server
.maxmemory_policy
== REDIS_MAXMEMORY_VOLATILE_TTL
) {
1342 for (k
= 0; k
< server
.maxmemory_samples
; k
++) {
1346 de
= dictGetRandomKey(dict
);
1347 thiskey
= dictGetEntryKey(de
);
1348 thisval
= (long) dictGetEntryVal(de
);
1350 /* Expire sooner (minor expire unix timestamp) is better
1351 * candidate for deletion */
1352 if (bestkey
== NULL
|| thisval
< bestval
) {
1359 /* Finally remove the selected key. */
1361 robj
*keyobj
= createStringObject(bestkey
,sdslen(bestkey
));
1362 dbDelete(db
,keyobj
);
1363 server
.stat_expiredkeys
++;
1364 decrRefCount(keyobj
);
1368 if (!freed
) return; /* nothing to free... */
1372 int j
, k
, freed
= 0;
1373 for (j
= 0; j
< server
.dbnum
; j
++) {
1376 robj
*keyobj
= NULL
;
1377 struct dictEntry
*de
;
1379 if (dictSize(server
.db
[j
].expires
)) {
1381 /* From a sample of three keys drop the one nearest to
1382 * the natural expire */
1383 for (k
= 0; k
< 3; k
++) {
1386 de
= dictGetRandomKey(server
.db
[j
].expires
);
1387 t
= (time_t) dictGetEntryVal(de
);
1388 if (minttl
== -1 || t
< minttl
) {
1389 minkey
= dictGetEntryKey(de
);
1393 keyobj
= createStringObject(minkey
,sdslen(minkey
));
1394 dbDelete(server
.db
+j
,keyobj
);
1395 server
.stat_expiredkeys
++;
1396 decrRefCount(keyobj
);
1399 if (!freed
) return; /* nothing to free... */
1403 /* =================================== Main! ================================ */
1406 int linuxOvercommitMemoryValue(void) {
1407 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
1411 if (fgets(buf
,64,fp
) == NULL
) {
1420 void linuxOvercommitMemoryWarning(void) {
1421 if (linuxOvercommitMemoryValue() == 0) {
1422 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.");
1425 #endif /* __linux__ */
1427 void createPidFile(void) {
1428 /* Try to write the pid file in a best-effort way. */
1429 FILE *fp
= fopen(server
.pidfile
,"w");
1431 fprintf(fp
,"%d\n",getpid());
1436 void daemonize(void) {
1439 if (fork() != 0) exit(0); /* parent exits */
1440 setsid(); /* create a new session */
1442 /* Every output goes to /dev/null. If Redis is daemonized but
1443 * the 'logfile' is set to 'stdout' in the configuration file
1444 * it will not log at all. */
1445 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
1446 dup2(fd
, STDIN_FILENO
);
1447 dup2(fd
, STDOUT_FILENO
);
1448 dup2(fd
, STDERR_FILENO
);
1449 if (fd
> STDERR_FILENO
) close(fd
);
1454 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
1455 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1460 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
1461 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
1465 int main(int argc
, char **argv
) {
1471 if (strcmp(argv
[1], "-v") == 0 ||
1472 strcmp(argv
[1], "--version") == 0) version();
1473 if (strcmp(argv
[1], "--help") == 0) usage();
1474 resetServerSaveParams();
1475 loadServerConfig(argv
[1]);
1476 } else if ((argc
> 2)) {
1479 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'");
1481 if (server
.daemonize
) daemonize();
1483 if (server
.daemonize
) createPidFile();
1484 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
1486 linuxOvercommitMemoryWarning();
1489 if (server
.appendonly
) {
1490 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
1491 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
1493 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
1494 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
1496 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
1497 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
1499 aeDeleteEventLoop(server
.el
);
1503 /* ============================= Backtrace support ========================= */
1505 #ifdef HAVE_BACKTRACE
1506 void *getMcontextEip(ucontext_t
*uc
) {
1507 #if defined(__FreeBSD__)
1508 return (void*) uc
->uc_mcontext
.mc_eip
;
1509 #elif defined(__dietlibc__)
1510 return (void*) uc
->uc_mcontext
.eip
;
1511 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1513 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1515 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1517 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1518 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1519 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
1521 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
1523 #elif defined(__i386__)
1524 return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */
1525 #elif defined(__X86_64__) || defined(__x86_64__)
1526 return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */
1527 #elif defined(__ia64__) /* Linux IA64 */
1528 return (void*) uc
->uc_mcontext
.sc_ip
;
1534 void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
1536 char **messages
= NULL
;
1537 int i
, trace_size
= 0;
1538 ucontext_t
*uc
= (ucontext_t
*) secret
;
1540 struct sigaction act
;
1541 REDIS_NOTUSED(info
);
1543 redisLog(REDIS_WARNING
,
1544 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
1545 infostring
= genRedisInfoString();
1546 redisLog(REDIS_WARNING
, "%s",infostring
);
1547 /* It's not safe to sdsfree() the returned string under memory
1548 * corruption conditions. Let it leak as we are going to abort */
1550 trace_size
= backtrace(trace
, 100);
1551 /* overwrite sigaction with caller's address */
1552 if (getMcontextEip(uc
) != NULL
) {
1553 trace
[1] = getMcontextEip(uc
);
1555 messages
= backtrace_symbols(trace
, trace_size
);
1557 for (i
=1; i
<trace_size
; ++i
)
1558 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
1560 /* free(messages); Don't call free() with possibly corrupted memory. */
1561 if (server
.daemonize
) unlink(server
.pidfile
);
1563 /* Make sure we exit with the right signal at the end. So for instance
1564 * the core will be dumped if enabled. */
1565 sigemptyset (&act
.sa_mask
);
1566 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1567 * is used. Otherwise, sa_handler is used */
1568 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1569 act
.sa_handler
= SIG_DFL
;
1570 sigaction (sig
, &act
, NULL
);
1574 void sigtermHandler(int sig
) {
1577 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
1578 server
.shutdown_asap
= 1;
1581 void setupSigSegvAction(void) {
1582 struct sigaction act
;
1584 sigemptyset (&act
.sa_mask
);
1585 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1586 * is used. Otherwise, sa_handler is used */
1587 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
1588 act
.sa_sigaction
= segvHandler
;
1589 sigaction (SIGSEGV
, &act
, NULL
);
1590 sigaction (SIGBUS
, &act
, NULL
);
1591 sigaction (SIGFPE
, &act
, NULL
);
1592 sigaction (SIGILL
, &act
, NULL
);
1593 sigaction (SIGBUS
, &act
, NULL
);
1595 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
1596 act
.sa_handler
= sigtermHandler
;
1597 sigaction (SIGTERM
, &act
, NULL
);
1601 #else /* HAVE_BACKTRACE */
1602 void setupSigSegvAction(void) {
1604 #endif /* HAVE_BACKTRACE */