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. 
  36 #endif /* HAVE_BACKTRACE */ 
  45 #include <arpa/inet.h> 
  49 #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 redisCommandTable
[] = { 
  72     {"get",getCommand
,2,0,NULL
,1,1,1,0,0}, 
  73     {"set",setCommand
,3,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,1,1,1,0,0}, 
  74     {"setnx",setnxCommand
,3,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,1,1,1,0,0}, 
  75     {"setex",setexCommand
,4,REDIS_CMD_DENYOOM
,noPreloadGetKeys
,2,2,1,0,0}, 
  76     {"append",appendCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  77     {"strlen",strlenCommand
,2,0,NULL
,1,1,1,0,0}, 
  78     {"del",delCommand
,-2,0,noPreloadGetKeys
,1,-1,1,0,0}, 
  79     {"exists",existsCommand
,2,0,NULL
,1,1,1,0,0}, 
  80     {"setbit",setbitCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  81     {"getbit",getbitCommand
,3,0,NULL
,1,1,1,0,0}, 
  82     {"setrange",setrangeCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  83     {"getrange",getrangeCommand
,4,0,NULL
,1,1,1,0,0}, 
  84     {"substr",getrangeCommand
,4,0,NULL
,1,1,1,0,0}, 
  85     {"incr",incrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  86     {"decr",decrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  87     {"mget",mgetCommand
,-2,0,NULL
,1,-1,1,0,0}, 
  88     {"rpush",rpushCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  89     {"lpush",lpushCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  90     {"rpushx",rpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  91     {"lpushx",lpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  92     {"linsert",linsertCommand
,5,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
  93     {"rpop",rpopCommand
,2,0,NULL
,1,1,1,0,0}, 
  94     {"lpop",lpopCommand
,2,0,NULL
,1,1,1,0,0}, 
  95     {"brpop",brpopCommand
,-3,0,NULL
,1,1,1,0,0}, 
  96     {"brpoplpush",brpoplpushCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,2,1,0,0}, 
  97     {"blpop",blpopCommand
,-3,0,NULL
,1,-2,1,0,0}, 
  98     {"llen",llenCommand
,2,0,NULL
,1,1,1,0,0}, 
  99     {"lindex",lindexCommand
,3,0,NULL
,1,1,1,0,0}, 
 100     {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 101     {"lrange",lrangeCommand
,4,0,NULL
,1,1,1,0,0}, 
 102     {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1,0,0}, 
 103     {"lrem",lremCommand
,4,0,NULL
,1,1,1,0,0}, 
 104     {"rpoplpush",rpoplpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1,0,0}, 
 105     {"sadd",saddCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 106     {"srem",sremCommand
,-3,0,NULL
,1,1,1,0,0}, 
 107     {"smove",smoveCommand
,4,0,NULL
,1,2,1,0,0}, 
 108     {"sismember",sismemberCommand
,3,0,NULL
,1,1,1,0,0}, 
 109     {"scard",scardCommand
,2,0,NULL
,1,1,1,0,0}, 
 110     {"spop",spopCommand
,2,0,NULL
,1,1,1,0,0}, 
 111     {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1,0,0}, 
 112     {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0}, 
 113     {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0}, 
 114     {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0}, 
 115     {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0}, 
 116     {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1,0,0}, 
 117     {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1,0,0}, 
 118     {"smembers",sinterCommand
,2,0,NULL
,1,1,1,0,0}, 
 119     {"zadd",zaddCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 120     {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 121     {"zrem",zremCommand
,-3,0,NULL
,1,1,1,0,0}, 
 122     {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1,0,0}, 
 123     {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1,0,0}, 
 124     {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0}, 
 125     {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0}, 
 126     {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1,0,0}, 
 127     {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1,0,0}, 
 128     {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1,0,0}, 
 129     {"zcount",zcountCommand
,4,0,NULL
,1,1,1,0,0}, 
 130     {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1,0,0}, 
 131     {"zcard",zcardCommand
,2,0,NULL
,1,1,1,0,0}, 
 132     {"zscore",zscoreCommand
,3,0,NULL
,1,1,1,0,0}, 
 133     {"zrank",zrankCommand
,3,0,NULL
,1,1,1,0,0}, 
 134     {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1,0,0}, 
 135     {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 136     {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 137     {"hget",hgetCommand
,3,0,NULL
,1,1,1,0,0}, 
 138     {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 139     {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1,0,0}, 
 140     {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 141     {"hdel",hdelCommand
,-3,0,NULL
,1,1,1,0,0}, 
 142     {"hlen",hlenCommand
,2,0,NULL
,1,1,1,0,0}, 
 143     {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1,0,0}, 
 144     {"hvals",hvalsCommand
,2,0,NULL
,1,1,1,0,0}, 
 145     {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1,0,0}, 
 146     {"hexists",hexistsCommand
,3,0,NULL
,1,1,1,0,0}, 
 147     {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 148     {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 149     {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 150     {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2,0,0}, 
 151     {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2,0,0}, 
 152     {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0,0,0}, 
 153     {"select",selectCommand
,2,0,NULL
,0,0,0,0,0}, 
 154     {"move",moveCommand
,3,0,NULL
,1,1,1,0,0}, 
 155     {"rename",renameCommand
,3,0,renameGetKeys
,1,2,1,0,0}, 
 156     {"renamenx",renamenxCommand
,3,0,renameGetKeys
,1,2,1,0,0}, 
 157     {"expire",expireCommand
,3,0,NULL
,1,1,1,0,0}, 
 158     {"expireat",expireatCommand
,3,0,NULL
,1,1,1,0,0}, 
 159     {"keys",keysCommand
,2,0,NULL
,0,0,0,0,0}, 
 160     {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0,0,0}, 
 161     {"auth",authCommand
,2,0,NULL
,0,0,0,0,0}, 
 162     {"ping",pingCommand
,1,0,NULL
,0,0,0,0,0}, 
 163     {"echo",echoCommand
,2,0,NULL
,0,0,0,0,0}, 
 164     {"save",saveCommand
,1,0,NULL
,0,0,0,0,0}, 
 165     {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0,0,0}, 
 166     {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0,0,0}, 
 167     {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0,0,0}, 
 168     {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0,0,0}, 
 169     {"type",typeCommand
,2,0,NULL
,1,1,1,0,0}, 
 170     {"multi",multiCommand
,1,0,NULL
,0,0,0,0,0}, 
 171     {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,NULL
,0,0,0,0,0}, 
 172     {"discard",discardCommand
,1,0,NULL
,0,0,0,0,0}, 
 173     {"sync",syncCommand
,1,0,NULL
,0,0,0,0,0}, 
 174     {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0,0,0}, 
 175     {"flushall",flushallCommand
,1,0,NULL
,0,0,0,0,0}, 
 176     {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1,0,0}, 
 177     {"info",infoCommand
,-1,0,NULL
,0,0,0,0,0}, 
 178     {"monitor",monitorCommand
,1,0,NULL
,0,0,0,0,0}, 
 179     {"ttl",ttlCommand
,2,0,NULL
,1,1,1,0,0}, 
 180     {"persist",persistCommand
,2,0,NULL
,1,1,1,0,0}, 
 181     {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0,0,0}, 
 182     {"debug",debugCommand
,-2,0,NULL
,0,0,0,0,0}, 
 183     {"config",configCommand
,-2,0,NULL
,0,0,0,0,0}, 
 184     {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0,0,0}, 
 185     {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0,0,0}, 
 186     {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0,0,0}, 
 187     {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0,0,0}, 
 188     {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0,0,0}, 
 189     {"watch",watchCommand
,-2,0,noPreloadGetKeys
,1,-1,1,0,0}, 
 190     {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0,0,0}, 
 191     {"cluster",clusterCommand
,-2,0,NULL
,0,0,0,0,0}, 
 192     {"restore",restoreCommand
,4,0,NULL
,0,0,0,0,0}, 
 193     {"migrate",migrateCommand
,6,0,NULL
,0,0,0,0,0}, 
 194     {"dump",dumpCommand
,2,0,NULL
,0,0,0,0,0}, 
 195     {"object",objectCommand
,-2,0,NULL
,0,0,0,0,0}, 
 196     {"client",clientCommand
,-2,0,NULL
,0,0,0,0,0}, 
 197     {"eval",evalCommand
,-3,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0}, 
 198     {"evalsha",evalShaCommand
,-3,REDIS_CMD_DENYOOM
,zunionInterGetKeys
,0,0,0,0,0}, 
 199     {"slowlog",slowlogCommand
,-2,0,NULL
,0,0,0,0,0} 
 202 /*============================ Utility functions ============================ */ 
 204 /* Low level logging. To use only for very big messages, otherwise 
 205  * redisLog() is to prefer. */ 
 206 void redisLogRaw(int level
, const char *msg
) { 
 207     const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING 
}; 
 208     const char *c 
= ".-*#"; 
 209     time_t now 
= time(NULL
); 
 212     int rawmode 
= (level 
& REDIS_LOG_RAW
); 
 214     level 
&= 0xff; /* clear flags */ 
 215     if (level 
< server
.verbosity
) return; 
 217     fp 
= (server
.logfile 
== NULL
) ? stdout 
: fopen(server
.logfile
,"a"); 
 221         fprintf(fp
,"%s",msg
); 
 223         strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
)); 
 224         fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
); 
 228     if (server
.logfile
) fclose(fp
); 
 230     if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
); 
 233 /* Like redisLogRaw() but with printf-alike support. This is the funciton that 
 234  * is used across the code. The raw version is only used in order to dump 
 235  * the INFO output on crash. */ 
 236 void redisLog(int level
, const char *fmt
, ...) { 
 238     char msg
[REDIS_MAX_LOGMSG_LEN
]; 
 240     if ((level
&0xff) < server
.verbosity
) return; 
 243     vsnprintf(msg
, sizeof(msg
), fmt
, ap
); 
 246     redisLogRaw(level
,msg
); 
 249 /* Redis generally does not try to recover from out of memory conditions 
 250  * when allocating objects or strings, it is not clear if it will be possible 
 251  * to report this condition to the client since the networking layer itself 
 252  * is based on heap allocation for send buffers, so we simply abort. 
 253  * At least the code will be simpler to read... */ 
 254 void oom(const char *msg
) { 
 255     redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
); 
 260 /* Return the UNIX time in microseconds */ 
 261 long long ustime(void) { 
 265     gettimeofday(&tv
, NULL
); 
 266     ust 
= ((long long)tv
.tv_sec
)*1000000; 
 271 /*====================== Hash table type implementation  ==================== */ 
 273 /* This is an hash table type that uses the SDS dynamic strings libary as 
 274  * keys and radis objects as values (objects can hold SDS strings, 
 277 void dictVanillaFree(void *privdata
, void *val
) 
 279     DICT_NOTUSED(privdata
); 
 283 void dictListDestructor(void *privdata
, void *val
) 
 285     DICT_NOTUSED(privdata
); 
 286     listRelease((list
*)val
); 
 289 int dictSdsKeyCompare(void *privdata
, const void *key1
, 
 293     DICT_NOTUSED(privdata
); 
 295     l1 
= sdslen((sds
)key1
); 
 296     l2 
= sdslen((sds
)key2
); 
 297     if (l1 
!= l2
) return 0; 
 298     return memcmp(key1
, key2
, l1
) == 0; 
 301 /* A case insensitive version used for the command lookup table. */ 
 302 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
, 
 305     DICT_NOTUSED(privdata
); 
 307     return strcasecmp(key1
, key2
) == 0; 
 310 void dictRedisObjectDestructor(void *privdata
, void *val
) 
 312     DICT_NOTUSED(privdata
); 
 314     if (val 
== NULL
) return; /* Values of swapped out keys as set to NULL */ 
 318 void dictSdsDestructor(void *privdata
, void *val
) 
 320     DICT_NOTUSED(privdata
); 
 325 int dictObjKeyCompare(void *privdata
, const void *key1
, 
 328     const robj 
*o1 
= key1
, *o2 
= key2
; 
 329     return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 332 unsigned int dictObjHash(const void *key
) { 
 334     return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 337 unsigned int dictSdsHash(const void *key
) { 
 338     return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
)); 
 341 unsigned int dictSdsCaseHash(const void *key
) { 
 342     return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
)); 
 345 int dictEncObjKeyCompare(void *privdata
, const void *key1
, 
 348     robj 
*o1 
= (robj
*) key1
, *o2 
= (robj
*) key2
; 
 351     if (o1
->encoding 
== REDIS_ENCODING_INT 
&& 
 352         o2
->encoding 
== REDIS_ENCODING_INT
) 
 353             return o1
->ptr 
== o2
->ptr
; 
 355     o1 
= getDecodedObject(o1
); 
 356     o2 
= getDecodedObject(o2
); 
 357     cmp 
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 363 unsigned int dictEncObjHash(const void *key
) { 
 364     robj 
*o 
= (robj
*) key
; 
 366     if (o
->encoding 
== REDIS_ENCODING_RAW
) { 
 367         return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 369         if (o
->encoding 
== REDIS_ENCODING_INT
) { 
 373             len 
= ll2string(buf
,32,(long)o
->ptr
); 
 374             return dictGenHashFunction((unsigned char*)buf
, len
); 
 378             o 
= getDecodedObject(o
); 
 379             hash 
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 386 /* Sets type hash table */ 
 387 dictType setDictType 
= { 
 388     dictEncObjHash
,            /* hash function */ 
 391     dictEncObjKeyCompare
,      /* key compare */ 
 392     dictRedisObjectDestructor
, /* key destructor */ 
 393     NULL                       
/* val destructor */ 
 396 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ 
 397 dictType zsetDictType 
= { 
 398     dictEncObjHash
,            /* hash function */ 
 401     dictEncObjKeyCompare
,      /* key compare */ 
 402     dictRedisObjectDestructor
, /* key destructor */ 
 403     NULL                       
/* val destructor */ 
 406 /* Db->dict, keys are sds strings, vals are Redis objects. */ 
 407 dictType dbDictType 
= { 
 408     dictSdsHash
,                /* hash function */ 
 411     dictSdsKeyCompare
,          /* key compare */ 
 412     dictSdsDestructor
,          /* key destructor */ 
 413     dictRedisObjectDestructor   
/* val destructor */ 
 417 dictType keyptrDictType 
= { 
 418     dictSdsHash
,               /* hash function */ 
 421     dictSdsKeyCompare
,         /* key compare */ 
 422     NULL
,                      /* key destructor */ 
 423     NULL                       
/* val destructor */ 
 426 /* Command table. sds string -> command struct pointer. */ 
 427 dictType commandTableDictType 
= { 
 428     dictSdsCaseHash
,           /* hash function */ 
 431     dictSdsKeyCaseCompare
,     /* key compare */ 
 432     dictSdsDestructor
,         /* key destructor */ 
 433     NULL                       
/* val destructor */ 
 436 /* Hash type hash table (note that small hashes are represented with zimpaps) */ 
 437 dictType hashDictType 
= { 
 438     dictEncObjHash
,             /* hash function */ 
 441     dictEncObjKeyCompare
,       /* key compare */ 
 442     dictRedisObjectDestructor
,  /* key destructor */ 
 443     dictRedisObjectDestructor   
/* val destructor */ 
 446 /* Keylist hash table type has unencoded redis objects as keys and 
 447  * lists as values. It's used for blocking operations (BLPOP) and to 
 448  * map swapped keys to a list of clients waiting for this keys to be loaded. */ 
 449 dictType keylistDictType 
= { 
 450     dictObjHash
,                /* hash function */ 
 453     dictObjKeyCompare
,          /* key compare */ 
 454     dictRedisObjectDestructor
,  /* key destructor */ 
 455     dictListDestructor          
/* val destructor */ 
 458 /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to 
 459  * clusterNode structures. */ 
 460 dictType clusterNodesDictType 
= { 
 461     dictSdsHash
,                /* hash function */ 
 464     dictSdsKeyCompare
,          /* key compare */ 
 465     dictSdsDestructor
,          /* key destructor */ 
 466     NULL                        
/* val destructor */ 
 469 int htNeedsResize(dict 
*dict
) { 
 470     long long size
, used
; 
 472     size 
= dictSlots(dict
); 
 473     used 
= dictSize(dict
); 
 474     return (size 
&& used 
&& size 
> DICT_HT_INITIAL_SIZE 
&& 
 475             (used
*100/size 
< REDIS_HT_MINFILL
)); 
 478 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL 
 479  * we resize the hash table to save memory */ 
 480 void tryResizeHashTables(void) { 
 483     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 484         if (htNeedsResize(server
.db
[j
].dict
)) 
 485             dictResize(server
.db
[j
].dict
); 
 486         if (htNeedsResize(server
.db
[j
].expires
)) 
 487             dictResize(server
.db
[j
].expires
); 
 491 /* Our hash table implementation performs rehashing incrementally while 
 492  * we write/read from the hash table. Still if the server is idle, the hash 
 493  * table will use two tables for a long time. So we try to use 1 millisecond 
 494  * of CPU time at every serverCron() loop in order to rehash some key. */ 
 495 void incrementallyRehash(void) { 
 498     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 499         if (dictIsRehashing(server
.db
[j
].dict
)) { 
 500             dictRehashMilliseconds(server
.db
[j
].dict
,1); 
 501             break; /* already used our millisecond for this loop... */ 
 506 /* This function is called once a background process of some kind terminates, 
 507  * as we want to avoid resizing the hash tables when there is a child in order 
 508  * to play well with copy-on-write (otherwise when a resize happens lots of 
 509  * memory pages are copied). The goal of this function is to update the ability 
 510  * for dict.c to resize the hash tables accordingly to the fact we have o not 
 512 void updateDictResizePolicy(void) { 
 513     if (server
.bgsavechildpid 
== -1 && server
.bgrewritechildpid 
== -1) 
 519 /* ======================= Cron: called every 100 ms ======================== */ 
 521 /* Try to expire a few timed out keys. The algorithm used is adaptive and 
 522  * will use few CPU cycles if there are few expiring keys, otherwise 
 523  * it will get more aggressive to avoid that too much memory is used by 
 524  * keys that can be removed from the keyspace. */ 
 525 void activeExpireCycle(void) { 
 528     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 530         redisDb 
*db 
= server
.db
+j
; 
 532         /* Continue to expire if at the end of the cycle more than 25% 
 533          * of the keys were expired. */ 
 535             long num 
= dictSize(db
->expires
); 
 536             time_t now 
= time(NULL
); 
 539             if (num 
> REDIS_EXPIRELOOKUPS_PER_CRON
) 
 540                 num 
= REDIS_EXPIRELOOKUPS_PER_CRON
; 
 545                 if ((de 
= dictGetRandomKey(db
->expires
)) == NULL
) break; 
 546                 t 
= (time_t) dictGetEntryVal(de
); 
 548                     sds key 
= dictGetEntryKey(de
); 
 549                     robj 
*keyobj 
= createStringObject(key
,sdslen(key
)); 
 551                     propagateExpire(db
,keyobj
); 
 553                     decrRefCount(keyobj
); 
 555                     server
.stat_expiredkeys
++; 
 558         } while (expired 
> REDIS_EXPIRELOOKUPS_PER_CRON
/4); 
 562 void updateLRUClock(void) { 
 563     server
.lruclock 
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) & 
 567 int serverCron(struct aeEventLoop 
*eventLoop
, long long id
, void *clientData
) { 
 568     int j
, loops 
= server
.cronloops
; 
 569     REDIS_NOTUSED(eventLoop
); 
 571     REDIS_NOTUSED(clientData
); 
 573     /* We take a cached value of the unix time in the global state because 
 574      * with virtual memory and aging there is to store the current time 
 575      * in objects at every object access, and accuracy is not needed. 
 576      * To access a global var is faster than calling time(NULL) */ 
 577     server
.unixtime 
= time(NULL
); 
 578     /* We have just 22 bits per object for LRU information. 
 579      * So we use an (eventually wrapping) LRU clock with 10 seconds resolution. 
 580      * 2^22 bits with 10 seconds resoluton is more or less 1.5 years. 
 582      * Note that even if this will wrap after 1.5 years it's not a problem, 
 583      * everything will still work but just some object will appear younger 
 584      * to Redis. But for this to happen a given object should never be touched 
 587      * Note that you can change the resolution altering the 
 588      * REDIS_LRU_CLOCK_RESOLUTION define. 
 592     /* Record the max memory used since the server was started. */ 
 593     if (zmalloc_used_memory() > server
.stat_peak_memory
) 
 594         server
.stat_peak_memory 
= zmalloc_used_memory(); 
 596     /* We received a SIGTERM, shutting down here in a safe way, as it is 
 597      * not ok doing so inside the signal handler. */ 
 598     if (server
.shutdown_asap
) { 
 599         if (prepareForShutdown() == REDIS_OK
) exit(0); 
 600         redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); 
 603     /* Show some info about non-empty databases */ 
 604     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 605         long long size
, used
, vkeys
; 
 607         size 
= dictSlots(server
.db
[j
].dict
); 
 608         used 
= dictSize(server
.db
[j
].dict
); 
 609         vkeys 
= dictSize(server
.db
[j
].expires
); 
 610         if (!(loops 
% 50) && (used 
|| vkeys
)) { 
 611             redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
); 
 612             /* dictPrintStats(server.dict); */ 
 616     /* We don't want to resize the hash tables while a bacground saving 
 617      * is in progress: the saving child is created using fork() that is 
 618      * implemented with a copy-on-write semantic in most modern systems, so 
 619      * if we resize the HT while there is the saving child at work actually 
 620      * a lot of memory movements in the parent will cause a lot of pages 
 622     if (server
.bgsavechildpid 
== -1 && server
.bgrewritechildpid 
== -1) { 
 623         if (!(loops 
% 10)) tryResizeHashTables(); 
 624         if (server
.activerehashing
) incrementallyRehash(); 
 627     /* Show information about connected clients */ 
 629         redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use", 
 630             listLength(server
.clients
)-listLength(server
.slaves
), 
 631             listLength(server
.slaves
), 
 632             zmalloc_used_memory()); 
 635     /* Close connections of timedout clients */ 
 636     if ((server
.maxidletime 
&& !(loops 
% 100)) || server
.bpop_blocked_clients
) 
 637         closeTimedoutClients(); 
 639     /* Start a scheduled AOF rewrite if this was requested by the user while 
 640      * a BGSAVE was in progress. */ 
 641     if (server
.bgsavechildpid 
== -1 && server
.bgrewritechildpid 
== -1 && 
 642         server
.aofrewrite_scheduled
) 
 644         rewriteAppendOnlyFileBackground(); 
 647     /* Check if a background saving or AOF rewrite in progress terminated. */ 
 648     if (server
.bgsavechildpid 
!= -1 || server
.bgrewritechildpid 
!= -1) { 
 652         if ((pid 
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) { 
 653             int exitcode 
= WEXITSTATUS(statloc
); 
 656             if (WIFSIGNALED(statloc
)) bysignal 
= WTERMSIG(statloc
); 
 658             if (pid 
== server
.bgsavechildpid
) { 
 659                 backgroundSaveDoneHandler(exitcode
,bysignal
); 
 661                 backgroundRewriteDoneHandler(exitcode
,bysignal
); 
 663             updateDictResizePolicy(); 
 666          time_t now 
= time(NULL
); 
 668         /* If there is not a background saving/rewrite in progress check if 
 669          * we have to save/rewrite now */ 
 670          for (j 
= 0; j 
< server
.saveparamslen
; j
++) { 
 671             struct saveparam 
*sp 
= server
.saveparams
+j
; 
 673             if (server
.dirty 
>= sp
->changes 
&& 
 674                 now
-server
.lastsave 
> sp
->seconds
) { 
 675                 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...", 
 676                     sp
->changes
, sp
->seconds
); 
 677                 rdbSaveBackground(server
.dbfilename
); 
 682          /* Trigger an AOF rewrite if needed */ 
 683          if (server
.bgsavechildpid 
== -1 && 
 684              server
.bgrewritechildpid 
== -1 && 
 685              server
.auto_aofrewrite_perc 
&& 
 686              server
.appendonly_current_size 
> server
.auto_aofrewrite_min_size
) 
 688             int base 
= server
.auto_aofrewrite_base_size 
? 
 689                             server
.auto_aofrewrite_base_size 
: 1; 
 690             long long growth 
= (server
.appendonly_current_size
*100/base
) - 100; 
 691             if (growth 
>= server
.auto_aofrewrite_perc
) { 
 692                 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
); 
 693                 rewriteAppendOnlyFileBackground(); 
 698     /* Expire a few keys per cycle, only if this is a master. 
 699      * On slaves we wait for DEL operations synthesized by the master 
 700      * in order to guarantee a strict consistency. */ 
 701     if (server
.masterhost 
== NULL
) activeExpireCycle(); 
 703     /* Replication cron function -- used to reconnect to master and 
 704      * to detect transfer failures. */ 
 705     if (!(loops 
% 10)) replicationCron(); 
 707     /* Run other sub-systems specific cron jobs */ 
 708     if (server
.cluster_enabled 
&& !(loops 
% 10)) clusterCron(); 
 714 /* This function gets called every time Redis is entering the 
 715  * main loop of the event driven library, that is, before to sleep 
 716  * for ready file descriptors. */ 
 717 void beforeSleep(struct aeEventLoop 
*eventLoop
) { 
 718     REDIS_NOTUSED(eventLoop
); 
 722     /* Try to process pending commands for clients that were just unblocked. */ 
 723     while (listLength(server
.unblocked_clients
)) { 
 724         ln 
= listFirst(server
.unblocked_clients
); 
 725         redisAssert(ln 
!= NULL
); 
 727         listDelNode(server
.unblocked_clients
,ln
); 
 728         c
->flags 
&= ~REDIS_UNBLOCKED
; 
 730         /* Process remaining data in the input buffer. */ 
 731         if (c
->querybuf 
&& sdslen(c
->querybuf
) > 0) 
 732             processInputBuffer(c
); 
 735     /* Write the AOF buffer on disk */ 
 736     flushAppendOnlyFile(); 
 739 /* =========================== Server initialization ======================== */ 
 741 void createSharedObjects(void) { 
 744     shared
.crlf 
= createObject(REDIS_STRING
,sdsnew("\r\n")); 
 745     shared
.ok 
= createObject(REDIS_STRING
,sdsnew("+OK\r\n")); 
 746     shared
.err 
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n")); 
 747     shared
.emptybulk 
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n")); 
 748     shared
.czero 
= createObject(REDIS_STRING
,sdsnew(":0\r\n")); 
 749     shared
.cone 
= createObject(REDIS_STRING
,sdsnew(":1\r\n")); 
 750     shared
.cnegone 
= createObject(REDIS_STRING
,sdsnew(":-1\r\n")); 
 751     shared
.nullbulk 
= createObject(REDIS_STRING
,sdsnew("$-1\r\n")); 
 752     shared
.nullmultibulk 
= createObject(REDIS_STRING
,sdsnew("*-1\r\n")); 
 753     shared
.emptymultibulk 
= createObject(REDIS_STRING
,sdsnew("*0\r\n")); 
 754     shared
.pong 
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n")); 
 755     shared
.queued 
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n")); 
 756     shared
.wrongtypeerr 
= createObject(REDIS_STRING
,sdsnew( 
 757         "-ERR Operation against a key holding the wrong kind of value\r\n")); 
 758     shared
.nokeyerr 
= createObject(REDIS_STRING
,sdsnew( 
 759         "-ERR no such key\r\n")); 
 760     shared
.syntaxerr 
= createObject(REDIS_STRING
,sdsnew( 
 761         "-ERR syntax error\r\n")); 
 762     shared
.sameobjecterr 
= createObject(REDIS_STRING
,sdsnew( 
 763         "-ERR source and destination objects are the same\r\n")); 
 764     shared
.outofrangeerr 
= createObject(REDIS_STRING
,sdsnew( 
 765         "-ERR index out of range\r\n")); 
 766     shared
.noscripterr 
= createObject(REDIS_STRING
,sdsnew( 
 767         "-NOSCRIPT No matching script. Please use EVAL.\r\n")); 
 768     shared
.loadingerr 
= createObject(REDIS_STRING
,sdsnew( 
 769         "-LOADING Redis is loading the dataset in memory\r\n")); 
 770     shared
.space 
= createObject(REDIS_STRING
,sdsnew(" ")); 
 771     shared
.colon 
= createObject(REDIS_STRING
,sdsnew(":")); 
 772     shared
.plus 
= createObject(REDIS_STRING
,sdsnew("+")); 
 773     shared
.select0 
= createStringObject("select 0\r\n",10); 
 774     shared
.select1 
= createStringObject("select 1\r\n",10); 
 775     shared
.select2 
= createStringObject("select 2\r\n",10); 
 776     shared
.select3 
= createStringObject("select 3\r\n",10); 
 777     shared
.select4 
= createStringObject("select 4\r\n",10); 
 778     shared
.select5 
= createStringObject("select 5\r\n",10); 
 779     shared
.select6 
= createStringObject("select 6\r\n",10); 
 780     shared
.select7 
= createStringObject("select 7\r\n",10); 
 781     shared
.select8 
= createStringObject("select 8\r\n",10); 
 782     shared
.select9 
= createStringObject("select 9\r\n",10); 
 783     shared
.messagebulk 
= createStringObject("$7\r\nmessage\r\n",13); 
 784     shared
.pmessagebulk 
= createStringObject("$8\r\npmessage\r\n",14); 
 785     shared
.subscribebulk 
= createStringObject("$9\r\nsubscribe\r\n",15); 
 786     shared
.unsubscribebulk 
= createStringObject("$11\r\nunsubscribe\r\n",18); 
 787     shared
.psubscribebulk 
= createStringObject("$10\r\npsubscribe\r\n",17); 
 788     shared
.punsubscribebulk 
= createStringObject("$12\r\npunsubscribe\r\n",19); 
 789     shared
.mbulk3 
= createStringObject("*3\r\n",4); 
 790     shared
.mbulk4 
= createStringObject("*4\r\n",4); 
 791     for (j 
= 0; j 
< REDIS_SHARED_INTEGERS
; j
++) { 
 792         shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
); 
 793         shared
.integers
[j
]->encoding 
= REDIS_ENCODING_INT
; 
 797 void initServerConfig() { 
 798     server
.port 
= REDIS_SERVERPORT
; 
 799     server
.bindaddr 
= NULL
; 
 800     server
.unixsocket 
= NULL
; 
 803     server
.dbnum 
= REDIS_DEFAULT_DBNUM
; 
 804     server
.verbosity 
= REDIS_VERBOSE
; 
 805     server
.maxidletime 
= REDIS_MAXIDLETIME
; 
 806     server
.saveparams 
= NULL
; 
 808     server
.logfile 
= NULL
; /* NULL = log on standard output */ 
 809     server
.syslog_enabled 
= 0; 
 810     server
.syslog_ident 
= zstrdup("redis"); 
 811     server
.syslog_facility 
= LOG_LOCAL0
; 
 812     server
.daemonize 
= 0; 
 813     server
.appendonly 
= 0; 
 814     server
.appendfsync 
= APPENDFSYNC_EVERYSEC
; 
 815     server
.no_appendfsync_on_rewrite 
= 0; 
 816     server
.auto_aofrewrite_perc 
= REDIS_AUTO_AOFREWRITE_PERC
; 
 817     server
.auto_aofrewrite_min_size 
= REDIS_AUTO_AOFREWRITE_MIN_SIZE
; 
 818     server
.auto_aofrewrite_base_size 
= 0; 
 819     server
.aofrewrite_scheduled 
= 0; 
 820     server
.lastfsync 
= time(NULL
); 
 821     server
.appendfd 
= -1; 
 822     server
.appendseldb 
= -1; /* Make sure the first time will not match */ 
 823     server
.pidfile 
= zstrdup("/var/run/redis.pid"); 
 824     server
.dbfilename 
= zstrdup("dump.rdb"); 
 825     server
.appendfilename 
= zstrdup("appendonly.aof"); 
 826     server
.requirepass 
= NULL
; 
 827     server
.rdbcompression 
= 1; 
 828     server
.activerehashing 
= 1; 
 829     server
.maxclients 
= 0; 
 830     server
.bpop_blocked_clients 
= 0; 
 831     server
.maxmemory 
= 0; 
 832     server
.maxmemory_policy 
= REDIS_MAXMEMORY_VOLATILE_LRU
; 
 833     server
.maxmemory_samples 
= 3; 
 834     server
.hash_max_zipmap_entries 
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
; 
 835     server
.hash_max_zipmap_value 
= REDIS_HASH_MAX_ZIPMAP_VALUE
; 
 836     server
.list_max_ziplist_entries 
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
; 
 837     server
.list_max_ziplist_value 
= REDIS_LIST_MAX_ZIPLIST_VALUE
; 
 838     server
.set_max_intset_entries 
= REDIS_SET_MAX_INTSET_ENTRIES
; 
 839     server
.zset_max_ziplist_entries 
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
; 
 840     server
.zset_max_ziplist_value 
= REDIS_ZSET_MAX_ZIPLIST_VALUE
; 
 841     server
.shutdown_asap 
= 0; 
 842     server
.cluster_enabled 
= 0; 
 843     server
.cluster
.configfile 
= zstrdup("nodes.conf"); 
 844     server
.lua_time_limit 
= REDIS_LUA_TIME_LIMIT
; 
 847     resetServerSaveParams(); 
 849     appendServerSaveParams(60*60,1);  /* save after 1 hour and 1 change */ 
 850     appendServerSaveParams(300,100);  /* save after 5 minutes and 100 changes */ 
 851     appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ 
 852     /* Replication related */ 
 854     server
.masterauth 
= NULL
; 
 855     server
.masterhost 
= NULL
; 
 856     server
.masterport 
= 6379; 
 857     server
.master 
= NULL
; 
 858     server
.replstate 
= REDIS_REPL_NONE
; 
 859     server
.repl_syncio_timeout 
= REDIS_REPL_SYNCIO_TIMEOUT
; 
 860     server
.repl_serve_stale_data 
= 1; 
 861     server
.repl_down_since 
= -1; 
 863     /* Double constants initialization */ 
 865     R_PosInf 
= 1.0/R_Zero
; 
 866     R_NegInf 
= -1.0/R_Zero
; 
 867     R_Nan 
= R_Zero
/R_Zero
; 
 869     /* Command table -- we intiialize it here as it is part of the 
 870      * initial configuration, since command names may be changed via 
 871      * redis.conf using the rename-command directive. */ 
 872     server
.commands 
= dictCreate(&commandTableDictType
,NULL
); 
 873     populateCommandTable(); 
 874     server
.delCommand 
= lookupCommandByCString("del"); 
 875     server
.multiCommand 
= lookupCommandByCString("multi"); 
 878     server
.slowlog_log_slower_than 
= REDIS_SLOWLOG_LOG_SLOWER_THAN
; 
 879     server
.slowlog_max_len 
= REDIS_SLOWLOG_MAX_LEN
; 
 885     signal(SIGHUP
, SIG_IGN
); 
 886     signal(SIGPIPE
, SIG_IGN
); 
 887     setupSignalHandlers(); 
 889     if (server
.syslog_enabled
) { 
 890         openlog(server
.syslog_ident
, LOG_PID 
| LOG_NDELAY 
| LOG_NOWAIT
, 
 891             server
.syslog_facility
); 
 894     server
.clients 
= listCreate(); 
 895     server
.slaves 
= listCreate(); 
 896     server
.monitors 
= listCreate(); 
 897     server
.unblocked_clients 
= listCreate(); 
 899     createSharedObjects(); 
 900     server
.el 
= aeCreateEventLoop(); 
 901     server
.db 
= zmalloc(sizeof(redisDb
)*server
.dbnum
); 
 903     if (server
.port 
!= 0) { 
 904         server
.ipfd 
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
); 
 905         if (server
.ipfd 
== ANET_ERR
) { 
 906             redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
); 
 910     if (server
.unixsocket 
!= NULL
) { 
 911         unlink(server
.unixsocket
); /* don't care if this fails */ 
 912         server
.sofd 
= anetUnixServer(server
.neterr
,server
.unixsocket
); 
 913         if (server
.sofd 
== ANET_ERR
) { 
 914             redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
); 
 918     if (server
.ipfd 
< 0 && server
.sofd 
< 0) { 
 919         redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting."); 
 922     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 923         server
.db
[j
].dict 
= dictCreate(&dbDictType
,NULL
); 
 924         server
.db
[j
].expires 
= dictCreate(&keyptrDictType
,NULL
); 
 925         server
.db
[j
].blocking_keys 
= dictCreate(&keylistDictType
,NULL
); 
 926         server
.db
[j
].watched_keys 
= dictCreate(&keylistDictType
,NULL
); 
 929     server
.pubsub_channels 
= dictCreate(&keylistDictType
,NULL
); 
 930     server
.pubsub_patterns 
= listCreate(); 
 931     listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
); 
 932     listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
); 
 933     server
.cronloops 
= 0; 
 934     server
.bgsavechildpid 
= -1; 
 935     server
.bgrewritechildpid 
= -1; 
 936     server
.bgrewritebuf 
= sdsempty(); 
 937     server
.aofbuf 
= sdsempty(); 
 938     server
.lastsave 
= time(NULL
); 
 940     server
.stat_numcommands 
= 0; 
 941     server
.stat_numconnections 
= 0; 
 942     server
.stat_expiredkeys 
= 0; 
 943     server
.stat_evictedkeys 
= 0; 
 944     server
.stat_starttime 
= time(NULL
); 
 945     server
.stat_keyspace_misses 
= 0; 
 946     server
.stat_keyspace_hits 
= 0; 
 947     server
.stat_peak_memory 
= 0; 
 948     server
.stat_fork_time 
= 0; 
 949     server
.unixtime 
= time(NULL
); 
 950     aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
); 
 951     if (server
.ipfd 
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
, 
 952         acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event"); 
 953     if (server
.sofd 
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
, 
 954         acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event"); 
 956     if (server
.appendonly
) { 
 957         server
.appendfd 
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644); 
 958         if (server
.appendfd 
== -1) { 
 959             redisLog(REDIS_WARNING
, "Can't open the append-only file: %s", 
 965     if (server
.cluster_enabled
) clusterInit(); 
 968     srand(time(NULL
)^getpid()); 
 971 /* Populates the Redis Command Table starting from the hard coded list 
 972  * we have on top of redis.c file. */ 
 973 void populateCommandTable(void) { 
 975     int numcommands 
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
); 
 977     for (j 
= 0; j 
< numcommands
; j
++) { 
 978         struct redisCommand 
*c 
= redisCommandTable
+j
; 
 981         retval 
= dictAdd(server
.commands
, sdsnew(c
->name
), c
); 
 982         assert(retval 
== DICT_OK
); 
 986 void resetCommandTableStats(void) { 
 987     int numcommands 
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
); 
 990     for (j 
= 0; j 
< numcommands
; j
++) { 
 991         struct redisCommand 
*c 
= redisCommandTable
+j
; 
 998 /* ====================== Commands lookup and execution ===================== */ 
1000 struct redisCommand 
*lookupCommand(sds name
) { 
1001     return dictFetchValue(server
.commands
, name
); 
1004 struct redisCommand 
*lookupCommandByCString(char *s
) { 
1005     struct redisCommand 
*cmd
; 
1006     sds name 
= sdsnew(s
); 
1008     cmd 
= dictFetchValue(server
.commands
, name
); 
1013 /* Call() is the core of Redis execution of a command */ 
1014 void call(redisClient 
*c
) { 
1015     long long dirty
, start 
= ustime(), duration
; 
1017     dirty 
= server
.dirty
; 
1019     dirty 
= server
.dirty
-dirty
; 
1020     duration 
= ustime()-start
; 
1021     c
->cmd
->microseconds 
+= duration
; 
1022     slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
); 
1025     if (server
.appendonly 
&& dirty
) 
1026         feedAppendOnlyFile(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
); 
1027     if ((dirty 
|| c
->cmd
->flags 
& REDIS_CMD_FORCE_REPLICATION
) && 
1028         listLength(server
.slaves
)) 
1029         replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
); 
1030     if (listLength(server
.monitors
)) 
1031         replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
); 
1032     server
.stat_numcommands
++; 
1035 /* If this function gets called we already read a whole 
1036  * command, argments are in the client argv/argc fields. 
1037  * processCommand() execute the command or prepare the 
1038  * server for a bulk read from the client. 
1040  * If 1 is returned the client is still alive and valid and 
1041  * and other operations can be performed by the caller. Otherwise 
1042  * if 0 is returned the client was destroied (i.e. after QUIT). */ 
1043 int processCommand(redisClient 
*c
) { 
1044     /* The QUIT command is handled separately. Normal command procs will 
1045      * go through checking for replication and QUIT will cause trouble 
1046      * when FORCE_REPLICATION is enabled and would be implemented in 
1047      * a regular command proc. */ 
1048     if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) { 
1049         addReply(c
,shared
.ok
); 
1050         c
->flags 
|= REDIS_CLOSE_AFTER_REPLY
; 
1054     /* Now lookup the command and check ASAP about trivial error conditions 
1055      * such as wrong arity, bad command name and so forth. */ 
1056     c
->cmd 
= lookupCommand(c
->argv
[0]->ptr
); 
1058         addReplyErrorFormat(c
,"unknown command '%s'", 
1059             (char*)c
->argv
[0]->ptr
); 
1061     } else if ((c
->cmd
->arity 
> 0 && c
->cmd
->arity 
!= c
->argc
) || 
1062                (c
->argc 
< -c
->cmd
->arity
)) { 
1063         addReplyErrorFormat(c
,"wrong number of arguments for '%s' command", 
1068     /* Check if the user is authenticated */ 
1069     if (server
.requirepass 
&& !c
->authenticated 
&& c
->cmd
->proc 
!= authCommand
) 
1071         addReplyError(c
,"operation not permitted"); 
1075     /* If cluster is enabled, redirect here */ 
1076     if (server
.cluster_enabled 
&& 
1077                 !(c
->cmd
->getkeys_proc 
== NULL 
&& c
->cmd
->firstkey 
== 0)) { 
1080         if (server
.cluster
.state 
!= REDIS_CLUSTER_OK
) { 
1081             addReplyError(c
,"The cluster is down. Check with CLUSTER INFO for more information"); 
1085             clusterNode 
*n 
= getNodeByQuery(c
,c
->cmd
,c
->argv
,c
->argc
,&hashslot
,&ask
); 
1087                 addReplyError(c
,"Multi keys request invalid in cluster"); 
1089             } else if (n 
!= server
.cluster
.myself
) { 
1090                 addReplySds(c
,sdscatprintf(sdsempty(), 
1091                     "-%s %d %s:%d\r\n", ask 
? "ASK" : "MOVED", 
1092                     hashslot
,n
->ip
,n
->port
)); 
1098     /* Handle the maxmemory directive. 
1100      * First we try to free some memory if possible (if there are volatile 
1101      * keys in the dataset). If there are not the only thing we can do 
1102      * is returning an error. */ 
1103     if (server
.maxmemory
) freeMemoryIfNeeded(); 
1104     if (server
.maxmemory 
&& (c
->cmd
->flags 
& REDIS_CMD_DENYOOM
) && 
1105         zmalloc_used_memory() > server
.maxmemory
) 
1107         addReplyError(c
,"command not allowed when used memory > 'maxmemory'"); 
1111     /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ 
1112     if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0) 
1114         c
->cmd
->proc 
!= subscribeCommand 
&& 
1115         c
->cmd
->proc 
!= unsubscribeCommand 
&& 
1116         c
->cmd
->proc 
!= psubscribeCommand 
&& 
1117         c
->cmd
->proc 
!= punsubscribeCommand
) { 
1118         addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context"); 
1122     /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and 
1123      * we are a slave with a broken link with master. */ 
1124     if (server
.masterhost 
&& server
.replstate 
!= REDIS_REPL_CONNECTED 
&& 
1125         server
.repl_serve_stale_data 
== 0 && 
1126         c
->cmd
->proc 
!= infoCommand 
&& c
->cmd
->proc 
!= slaveofCommand
) 
1129             "link with MASTER is down and slave-serve-stale-data is set to no"); 
1133     /* Loading DB? Return an error if the command is not INFO */ 
1134     if (server
.loading 
&& c
->cmd
->proc 
!= infoCommand
) { 
1135         addReply(c
, shared
.loadingerr
); 
1139     /* Exec the command */ 
1140     if (c
->flags 
& REDIS_MULTI 
&& 
1141         c
->cmd
->proc 
!= execCommand 
&& c
->cmd
->proc 
!= discardCommand 
&& 
1142         c
->cmd
->proc 
!= multiCommand 
&& c
->cmd
->proc 
!= watchCommand
) 
1144         queueMultiCommand(c
); 
1145         addReply(c
,shared
.queued
); 
1152 /*================================== Shutdown =============================== */ 
1154 int prepareForShutdown() { 
1155     redisLog(REDIS_WARNING
,"User requested shutdown..."); 
1156     /* Kill the saving child if there is a background saving in progress. 
1157        We want to avoid race conditions, for instance our saving child may 
1158        overwrite the synchronous saving did by SHUTDOWN. */ 
1159     if (server
.bgsavechildpid 
!= -1) { 
1160         redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!"); 
1161         kill(server
.bgsavechildpid
,SIGKILL
); 
1162         rdbRemoveTempFile(server
.bgsavechildpid
); 
1164     if (server
.appendonly
) { 
1165         /* Kill the AOF saving child as the AOF we already have may be longer 
1166          * but contains the full dataset anyway. */ 
1167         if (server
.bgrewritechildpid 
!= -1) { 
1168             redisLog(REDIS_WARNING
, 
1169                 "There is a child rewriting the AOF. Killing it!"); 
1170             kill(server
.bgrewritechildpid
,SIGKILL
); 
1172         /* Append only file: fsync() the AOF and exit */ 
1173         redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file."); 
1174         aof_fsync(server
.appendfd
); 
1176     if (server
.saveparamslen 
> 0) { 
1177         redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting."); 
1178         /* Snapshotting. Perform a SYNC SAVE and exit */ 
1179         if (rdbSave(server
.dbfilename
) != REDIS_OK
) { 
1180             /* Ooops.. error saving! The best we can do is to continue 
1181              * operating. Note that if there was a background saving process, 
1182              * in the next cron() Redis will be notified that the background 
1183              * saving aborted, handling special stuff like slaves pending for 
1184              * synchronization... */ 
1185             redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit."); 
1189     if (server
.daemonize
) { 
1190         redisLog(REDIS_NOTICE
,"Removing the pid file."); 
1191         unlink(server
.pidfile
); 
1193     redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye..."); 
1197 /*================================== Commands =============================== */ 
1199 void authCommand(redisClient 
*c
) { 
1200     if (!server
.requirepass 
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) { 
1201       c
->authenticated 
= 1; 
1202       addReply(c
,shared
.ok
); 
1204       c
->authenticated 
= 0; 
1205       addReplyError(c
,"invalid password"); 
1209 void pingCommand(redisClient 
*c
) { 
1210     addReply(c
,shared
.pong
); 
1213 void echoCommand(redisClient 
*c
) { 
1214     addReplyBulk(c
,c
->argv
[1]); 
1217 /* Convert an amount of bytes into a human readable string in the form 
1218  * of 100B, 2G, 100M, 4K, and so forth. */ 
1219 void bytesToHuman(char *s
, unsigned long long n
) { 
1224         sprintf(s
,"%lluB",n
); 
1226     } else if (n 
< (1024*1024)) { 
1227         d 
= (double)n
/(1024); 
1228         sprintf(s
,"%.2fK",d
); 
1229     } else if (n 
< (1024LL*1024*1024)) { 
1230         d 
= (double)n
/(1024*1024); 
1231         sprintf(s
,"%.2fM",d
); 
1232     } else if (n 
< (1024LL*1024*1024*1024)) { 
1233         d 
= (double)n
/(1024LL*1024*1024); 
1234         sprintf(s
,"%.2fG",d
); 
1238 /* Create the string returned by the INFO command. This is decoupled 
1239  * by the INFO command itself as we need to report the same information 
1240  * on memory corruption problems. */ 
1241 sds 
genRedisInfoString(char *section
) { 
1242     sds info 
= sdsempty(); 
1243     time_t uptime 
= time(NULL
)-server
.stat_starttime
; 
1245     struct rusage self_ru
, c_ru
; 
1246     unsigned long lol
, bib
; 
1247     int allsections 
= 0, defsections 
= 0; 
1251         allsections 
= strcasecmp(section
,"all") == 0; 
1252         defsections 
= strcasecmp(section
,"default") == 0; 
1255     getrusage(RUSAGE_SELF
, &self_ru
); 
1256     getrusage(RUSAGE_CHILDREN
, &c_ru
); 
1257     getClientsMaxBuffers(&lol
,&bib
); 
1260     if (allsections 
|| defsections 
|| !strcasecmp(section
,"server")) { 
1261         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1262         info 
= sdscatprintf(info
, 
1264             "redis_version:%s\r\n" 
1265             "redis_git_sha1:%s\r\n" 
1266             "redis_git_dirty:%d\r\n" 
1268             "multiplexing_api:%s\r\n" 
1269             "process_id:%ld\r\n" 
1271             "uptime_in_seconds:%ld\r\n" 
1272             "uptime_in_days:%ld\r\n" 
1273             "lru_clock:%ld\r\n", 
1276             strtol(redisGitDirty(),NULL
,10) > 0, 
1277             (sizeof(long) == 8) ? "64" : "32", 
1283             (unsigned long) server
.lruclock
); 
1287     if (allsections 
|| defsections 
|| !strcasecmp(section
,"clients")) { 
1288         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1289         info 
= sdscatprintf(info
, 
1291             "connected_clients:%d\r\n" 
1292             "client_longest_output_list:%lu\r\n" 
1293             "client_biggest_input_buf:%lu\r\n" 
1294             "blocked_clients:%d\r\n", 
1295             listLength(server
.clients
)-listLength(server
.slaves
), 
1297             server
.bpop_blocked_clients
); 
1301     if (allsections 
|| defsections 
|| !strcasecmp(section
,"memory")) { 
1305         bytesToHuman(hmem
,zmalloc_used_memory()); 
1306         bytesToHuman(peak_hmem
,server
.stat_peak_memory
); 
1307         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1308         info 
= sdscatprintf(info
, 
1310             "used_memory:%zu\r\n" 
1311             "used_memory_human:%s\r\n" 
1312             "used_memory_rss:%zu\r\n" 
1313             "used_memory_peak:%zu\r\n" 
1314             "used_memory_peak_human:%s\r\n" 
1315             "used_memory_lua:%lld\r\n" 
1316             "mem_fragmentation_ratio:%.2f\r\n" 
1317             "mem_allocator:%s\r\n", 
1318             zmalloc_used_memory(), 
1321             server
.stat_peak_memory
, 
1323             ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL, 
1324             zmalloc_get_fragmentation_ratio(), 
1330     if (allsections 
|| defsections 
|| !strcasecmp(section
,"persistence")) { 
1331         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1332         info 
= sdscatprintf(info
, 
1335             "aof_enabled:%d\r\n" 
1336             "changes_since_last_save:%lld\r\n" 
1337             "bgsave_in_progress:%d\r\n" 
1338             "last_save_time:%ld\r\n" 
1339             "bgrewriteaof_in_progress:%d\r\n", 
1343             server
.bgsavechildpid 
!= -1, 
1345             server
.bgrewritechildpid 
!= -1); 
1347         if (server
.appendonly
) { 
1348             info 
= sdscatprintf(info
, 
1349                 "aof_current_size:%lld\r\n" 
1350                 "aof_base_size:%lld\r\n" 
1351                 "aof_pending_rewrite:%d\r\n", 
1352                 (long long) server
.appendonly_current_size
, 
1353                 (long long) server
.auto_aofrewrite_base_size
, 
1354                 server
.aofrewrite_scheduled
); 
1357         if (server
.loading
) { 
1359             time_t eta
, elapsed
; 
1360             off_t remaining_bytes 
= server
.loading_total_bytes
- 
1361                                     server
.loading_loaded_bytes
; 
1363             perc 
= ((double)server
.loading_loaded_bytes 
/ 
1364                    server
.loading_total_bytes
) * 100; 
1366             elapsed 
= time(NULL
)-server
.loading_start_time
; 
1368                 eta 
= 1; /* A fake 1 second figure if we don't have 
1371                 eta 
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
; 
1374             info 
= sdscatprintf(info
, 
1375                 "loading_start_time:%ld\r\n" 
1376                 "loading_total_bytes:%llu\r\n" 
1377                 "loading_loaded_bytes:%llu\r\n" 
1378                 "loading_loaded_perc:%.2f\r\n" 
1379                 "loading_eta_seconds:%ld\r\n" 
1380                 ,(unsigned long) server
.loading_start_time
, 
1381                 (unsigned long long) server
.loading_total_bytes
, 
1382                 (unsigned long long) server
.loading_loaded_bytes
, 
1390     if (allsections 
|| defsections 
|| !strcasecmp(section
,"stats")) { 
1391         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1392         info 
= sdscatprintf(info
, 
1394             "total_connections_received:%lld\r\n" 
1395             "total_commands_processed:%lld\r\n" 
1396             "expired_keys:%lld\r\n" 
1397             "evicted_keys:%lld\r\n" 
1398             "keyspace_hits:%lld\r\n" 
1399             "keyspace_misses:%lld\r\n" 
1400             "pubsub_channels:%ld\r\n" 
1401             "pubsub_patterns:%u\r\n" 
1402             "latest_fork_usec:%lld\r\n", 
1403             server
.stat_numconnections
, 
1404             server
.stat_numcommands
, 
1405             server
.stat_expiredkeys
, 
1406             server
.stat_evictedkeys
, 
1407             server
.stat_keyspace_hits
, 
1408             server
.stat_keyspace_misses
, 
1409             dictSize(server
.pubsub_channels
), 
1410             listLength(server
.pubsub_patterns
), 
1411             server
.stat_fork_time
); 
1415     if (allsections 
|| defsections 
|| !strcasecmp(section
,"replication")) { 
1416         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1417         info 
= sdscatprintf(info
, 
1420             server
.masterhost 
== NULL 
? "master" : "slave"); 
1421         if (server
.masterhost
) { 
1422             info 
= sdscatprintf(info
, 
1423                 "master_host:%s\r\n" 
1424                 "master_port:%d\r\n" 
1425                 "master_link_status:%s\r\n" 
1426                 "master_last_io_seconds_ago:%d\r\n" 
1427                 "master_sync_in_progress:%d\r\n" 
1430                 (server
.replstate 
== REDIS_REPL_CONNECTED
) ? 
1433                 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1, 
1434                 server
.replstate 
== REDIS_REPL_TRANSFER
 
1437             if (server
.replstate 
== REDIS_REPL_TRANSFER
) { 
1438                 info 
= sdscatprintf(info
, 
1439                     "master_sync_left_bytes:%ld\r\n" 
1440                     "master_sync_last_io_seconds_ago:%d\r\n" 
1441                     ,(long)server
.repl_transfer_left
, 
1442                     (int)(time(NULL
)-server
.repl_transfer_lastio
) 
1446             if (server
.replstate 
!= REDIS_REPL_CONNECTED
) { 
1447                 info 
= sdscatprintf(info
, 
1448                     "master_link_down_since_seconds:%ld\r\n", 
1449                     (long)time(NULL
)-server
.repl_down_since
); 
1452         info 
= sdscatprintf(info
, 
1453             "connected_slaves:%d\r\n", 
1454             listLength(server
.slaves
)); 
1458     if (allsections 
|| defsections 
|| !strcasecmp(section
,"cpu")) { 
1459         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1460         info 
= sdscatprintf(info
, 
1462         "used_cpu_sys:%.2f\r\n" 
1463         "used_cpu_user:%.2f\r\n" 
1464         "used_cpu_sys_children:%.2f\r\n" 
1465         "used_cpu_user_children:%.2f\r\n", 
1466         (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000, 
1467         (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000, 
1468         (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000, 
1469         (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000); 
1473     if (allsections 
|| !strcasecmp(section
,"commandstats")) { 
1474         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1475         info 
= sdscatprintf(info
, "# Commandstats\r\n"); 
1476         numcommands 
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
); 
1477         for (j 
= 0; j 
< numcommands
; j
++) { 
1478             struct redisCommand 
*c 
= redisCommandTable
+j
; 
1480             if (!c
->calls
) continue; 
1481             info 
= sdscatprintf(info
, 
1482                 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n", 
1483                 c
->name
, c
->calls
, c
->microseconds
, 
1484                 (c
->calls 
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
)); 
1489     if (allsections 
|| defsections 
|| !strcasecmp(section
,"cluster")) { 
1490         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1491         info 
= sdscatprintf(info
, 
1493         "cluster_enabled:%d\r\n", 
1494         server
.cluster_enabled
); 
1498     if (allsections 
|| defsections 
|| !strcasecmp(section
,"keyspace")) { 
1499         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1500         info 
= sdscatprintf(info
, "# Keyspace\r\n"); 
1501         for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1502             long long keys
, vkeys
; 
1504             keys 
= dictSize(server
.db
[j
].dict
); 
1505             vkeys 
= dictSize(server
.db
[j
].expires
); 
1506             if (keys 
|| vkeys
) { 
1507                 info 
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n", 
1515 void infoCommand(redisClient 
*c
) { 
1516     char *section 
= c
->argc 
== 2 ? c
->argv
[1]->ptr 
: "default"; 
1519         addReply(c
,shared
.syntaxerr
); 
1522     sds info 
= genRedisInfoString(section
); 
1523     addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n", 
1524         (unsigned long)sdslen(info
))); 
1525     addReplySds(c
,info
); 
1526     addReply(c
,shared
.crlf
); 
1529 void monitorCommand(redisClient 
*c
) { 
1530     /* ignore MONITOR if aleady slave or in monitor mode */ 
1531     if (c
->flags 
& REDIS_SLAVE
) return; 
1533     c
->flags 
|= (REDIS_SLAVE
|REDIS_MONITOR
); 
1535     listAddNodeTail(server
.monitors
,c
); 
1536     addReply(c
,shared
.ok
); 
1539 /* ============================ Maxmemory directive  ======================== */ 
1541 /* This function gets called when 'maxmemory' is set on the config file to limit 
1542  * the max memory used by the server, and we are out of memory. 
1543  * This function will try to, in order: 
1545  * - Free objects from the free list 
1546  * - Try to remove keys with an EXPIRE set 
1548  * It is not possible to free enough memory to reach used-memory < maxmemory 
1549  * the server will start refusing commands that will enlarge even more the 
1552 void freeMemoryIfNeeded(void) { 
1553     /* Remove keys accordingly to the active policy as long as we are 
1554      * over the memory limit. */ 
1555     if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_NO_EVICTION
) return; 
1557     while (server
.maxmemory 
&& zmalloc_used_memory() > server
.maxmemory
) { 
1558         int j
, k
, freed 
= 0; 
1560         for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1561             long bestval 
= 0; /* just to prevent warning */ 
1563             struct dictEntry 
*de
; 
1564             redisDb 
*db 
= server
.db
+j
; 
1567             if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_LRU 
|| 
1568                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
) 
1570                 dict 
= server
.db
[j
].dict
; 
1572                 dict 
= server
.db
[j
].expires
; 
1574             if (dictSize(dict
) == 0) continue; 
1576             /* volatile-random and allkeys-random policy */ 
1577             if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_RANDOM 
|| 
1578                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_RANDOM
) 
1580                 de 
= dictGetRandomKey(dict
); 
1581                 bestkey 
= dictGetEntryKey(de
); 
1584             /* volatile-lru and allkeys-lru policy */ 
1585             else if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_LRU 
|| 
1586                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_LRU
) 
1588                 for (k 
= 0; k 
< server
.maxmemory_samples
; k
++) { 
1593                     de 
= dictGetRandomKey(dict
); 
1594                     thiskey 
= dictGetEntryKey(de
); 
1595                     /* When policy is volatile-lru we need an additonal lookup 
1596                      * to locate the real key, as dict is set to db->expires. */ 
1597                     if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_LRU
) 
1598                         de 
= dictFind(db
->dict
, thiskey
); 
1599                     o 
= dictGetEntryVal(de
); 
1600                     thisval 
= estimateObjectIdleTime(o
); 
1602                     /* Higher idle time is better candidate for deletion */ 
1603                     if (bestkey 
== NULL 
|| thisval 
> bestval
) { 
1611             else if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_TTL
) { 
1612                 for (k 
= 0; k 
< server
.maxmemory_samples
; k
++) { 
1616                     de 
= dictGetRandomKey(dict
); 
1617                     thiskey 
= dictGetEntryKey(de
); 
1618                     thisval 
= (long) dictGetEntryVal(de
); 
1620                     /* Expire sooner (minor expire unix timestamp) is better 
1621                      * candidate for deletion */ 
1622                     if (bestkey 
== NULL 
|| thisval 
< bestval
) { 
1629             /* Finally remove the selected key. */ 
1631                 robj 
*keyobj 
= createStringObject(bestkey
,sdslen(bestkey
)); 
1632                 propagateExpire(db
,keyobj
); 
1633                 dbDelete(db
,keyobj
); 
1634                 server
.stat_evictedkeys
++; 
1635                 decrRefCount(keyobj
); 
1639         if (!freed
) return; /* nothing to free... */ 
1643 /* =================================== Main! ================================ */ 
1646 int linuxOvercommitMemoryValue(void) { 
1647     FILE *fp 
= fopen("/proc/sys/vm/overcommit_memory","r"); 
1651     if (fgets(buf
,64,fp
) == NULL
) { 
1660 void linuxOvercommitMemoryWarning(void) { 
1661     if (linuxOvercommitMemoryValue() == 0) { 
1662         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."); 
1665 #endif /* __linux__ */ 
1667 void createPidFile(void) { 
1668     /* Try to write the pid file in a best-effort way. */ 
1669     FILE *fp 
= fopen(server
.pidfile
,"w"); 
1671         fprintf(fp
,"%d\n",(int)getpid()); 
1676 void daemonize(void) { 
1679     if (fork() != 0) exit(0); /* parent exits */ 
1680     setsid(); /* create a new session */ 
1682     /* Every output goes to /dev/null. If Redis is daemonized but 
1683      * the 'logfile' is set to 'stdout' in the configuration file 
1684      * it will not log at all. */ 
1685     if ((fd 
= open("/dev/null", O_RDWR
, 0)) != -1) { 
1686         dup2(fd
, STDIN_FILENO
); 
1687         dup2(fd
, STDOUT_FILENO
); 
1688         dup2(fd
, STDERR_FILENO
); 
1689         if (fd 
> STDERR_FILENO
) close(fd
); 
1694     printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
, 
1695         redisGitSHA1(), atoi(redisGitDirty()) > 0); 
1700     fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n"); 
1701     fprintf(stderr
,"       ./redis-server - (read config from stdin)\n"); 
1705 void redisAsciiArt(void) { 
1706 #include "asciilogo.h" 
1707     char *buf 
= zmalloc(1024*16); 
1709     snprintf(buf
,1024*16,ascii_logo
, 
1712         strtol(redisGitDirty(),NULL
,10) > 0, 
1713         (sizeof(long) == 8) ? "64" : "32", 
1714         server
.cluster_enabled 
? "cluster" : "stand alone", 
1718     redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
); 
1722 int main(int argc
, char **argv
) { 
1727         if (strcmp(argv
[1], "-v") == 0 || 
1728             strcmp(argv
[1], "--version") == 0) version(); 
1729         if (strcmp(argv
[1], "--help") == 0) usage(); 
1730         resetServerSaveParams(); 
1731         loadServerConfig(argv
[1]); 
1732     } else if ((argc 
> 2)) { 
1735         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'"); 
1737     if (server
.daemonize
) daemonize(); 
1739     if (server
.daemonize
) createPidFile(); 
1741     redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
); 
1743     linuxOvercommitMemoryWarning(); 
1746     if (server
.appendonly
) { 
1747         if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
) 
1748             redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000); 
1750         if (rdbLoad(server
.dbfilename
) == REDIS_OK
) 
1751             redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds",(float)(ustime()-start
)/1000000); 
1753     if (server
.ipfd 
> 0) 
1754         redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
); 
1755     if (server
.sofd 
> 0) 
1756         redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
); 
1757     aeSetBeforeSleepProc(server
.el
,beforeSleep
); 
1759     aeDeleteEventLoop(server
.el
); 
1763 #ifdef HAVE_BACKTRACE 
1764 static void *getMcontextEip(ucontext_t 
*uc
) { 
1765 #if defined(__FreeBSD__) 
1766     return (void*) uc
->uc_mcontext
.mc_eip
; 
1767 #elif defined(__dietlibc__) 
1768     return (void*) uc
->uc_mcontext
.eip
; 
1769 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6) 
1771     return (void*) uc
->uc_mcontext
->__ss
.__rip
; 
1773     return (void*) uc
->uc_mcontext
->__ss
.__eip
; 
1775 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) 
1776   #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) 
1777     return (void*) uc
->uc_mcontext
->__ss
.__rip
; 
1779     return (void*) uc
->uc_mcontext
->__ss
.__eip
; 
1781 #elif defined(__i386__) 
1782     return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */ 
1783 #elif defined(__X86_64__) || defined(__x86_64__) 
1784     return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */ 
1785 #elif defined(__ia64__) /* Linux IA64 */ 
1786     return (void*) uc
->uc_mcontext
.sc_ip
; 
1792 static void sigsegvHandler(int sig
, siginfo_t 
*info
, void *secret
) { 
1794     char **messages 
= NULL
; 
1795     int i
, trace_size 
= 0; 
1796     ucontext_t 
*uc 
= (ucontext_t
*) secret
; 
1798     struct sigaction act
; 
1799     REDIS_NOTUSED(info
); 
1801     redisLog(REDIS_WARNING
, 
1802         "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
); 
1803     infostring 
= genRedisInfoString("all"); 
1804     redisLogRaw(REDIS_WARNING
, infostring
); 
1805     /* It's not safe to sdsfree() the returned string under memory 
1806      * corruption conditions. Let it leak as we are going to abort */ 
1808     trace_size 
= backtrace(trace
, 100); 
1809     /* overwrite sigaction with caller's address */ 
1810     if (getMcontextEip(uc
) != NULL
) { 
1811         trace
[1] = getMcontextEip(uc
); 
1813     messages 
= backtrace_symbols(trace
, trace_size
); 
1815     for (i
=1; i
<trace_size
; ++i
) 
1816         redisLog(REDIS_WARNING
,"%s", messages
[i
]); 
1818     /* free(messages); Don't call free() with possibly corrupted memory. */ 
1819     if (server
.daemonize
) unlink(server
.pidfile
); 
1821     /* Make sure we exit with the right signal at the end. So for instance 
1822      * the core will be dumped if enabled. */ 
1823     sigemptyset (&act
.sa_mask
); 
1824     /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction 
1825      * is used. Otherwise, sa_handler is used */ 
1826     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND
; 
1827     act
.sa_handler 
= SIG_DFL
; 
1828     sigaction (sig
, &act
, NULL
); 
1831 #endif /* HAVE_BACKTRACE */ 
1833 static void sigtermHandler(int sig
) { 
1836     redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown..."); 
1837     server
.shutdown_asap 
= 1; 
1840 void setupSignalHandlers(void) { 
1841     struct sigaction act
; 
1843     /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. 
1844      * Otherwise, sa_handler is used. */ 
1845     sigemptyset(&act
.sa_mask
); 
1846     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND
; 
1847     act
.sa_handler 
= sigtermHandler
; 
1848     sigaction(SIGTERM
, &act
, NULL
); 
1850 #ifdef HAVE_BACKTRACE 
1851     sigemptyset(&act
.sa_mask
); 
1852     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND 
| SA_SIGINFO
; 
1853     act
.sa_sigaction 
= sigsegvHandler
; 
1854     sigaction(SIGSEGV
, &act
, NULL
); 
1855     sigaction(SIGBUS
, &act
, NULL
); 
1856     sigaction(SIGFPE
, &act
, NULL
); 
1857     sigaction(SIGILL
, &act
, NULL
);