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. 
  41 #include <arpa/inet.h> 
  45 #include <sys/resource.h> 
  50 #include <sys/resource.h> 
  52 /* Our shared "common" objects */ 
  54 struct sharedObjectsStruct shared
; 
  56 /* Global vars that are actually used as constants. The following double 
  57  * values are used for double on-disk serialization, and are initialized 
  58  * at runtime to avoid strange compiler optimizations. */ 
  60 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
; 
  62 /*================================= Globals ================================= */ 
  65 struct redisServer server
; /* server global state */ 
  66 struct redisCommand 
*commandTable
; 
  70  * Every entry is composed of the following fields: 
  72  * name: a string representing the command name. 
  73  * function: pointer to the C function implementing the command. 
  74  * arity: number of arguments, it is possible to use -N to say >= N 
  75  * sflags: command flags as string. See below for a table of flags. 
  76  * flags: flags as bitmask. Computed by Redis using the 'sflags' field. 
  77  * get_keys_proc: an optional function to get key arguments from a command. 
  78  *                This is only used when the following three fields are not 
  79  *                enough to specify what arguments are keys. 
  80  * first_key_index: first argument that is a key 
  81  * last_key_index: last argument that is a key 
  82  * key_step: step to get all the keys from first to last argument. For instance 
  83  *           in MSET the step is two since arguments are key,val,key,val,... 
  84  * microseconds: microseconds of total execution time for this command. 
  85  * calls: total number of calls of this command. 
  87  * The flags, microseconds and calls fields are computed by Redis and should 
  88  * always be set to zero. 
  90  * Command flags are expressed using strings where every character represents 
  91  * a flag. Later the populateCommandTable() function will take care of 
  92  * populating the real 'flags' field using this characters. 
  94  * This is the meaning of the flags: 
  96  * w: write command (may modify the key space). 
  97  * r: read command  (will never modify the key space). 
  98  * m: may increase memory usage once called. Don't allow if out of memory. 
  99  * a: admin command, like SAVE or SHUTDOWN. 
 100  * p: Pub/Sub related command. 
 101  * f: force replication of this command, regarless of server.dirty. 
 102  * s: command not allowed in scripts. 
 103  * R: random command. Command is not deterministic, that is, the same command 
 104  *    with the same arguments, with the same key space, may have different 
 105  *    results. For instance SPOP and RANDOMKEY are two random commands. 
 106  * S: Sort command output array if called from script, so that the output 
 109 struct redisCommand redisCommandTable
[] = { 
 110     {"get",getCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 111     {"set",setCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0}, 
 112     {"setnx",setnxCommand
,3,"wm",0,noPreloadGetKeys
,1,1,1,0,0}, 
 113     {"setex",setexCommand
,4,"wm",0,noPreloadGetKeys
,1,1,1,0,0}, 
 114     {"psetex",psetexCommand
,4,"wm",0,noPreloadGetKeys
,1,1,1,0,0}, 
 115     {"append",appendCommand
,3,"wm",0,NULL
,1,1,1,0,0}, 
 116     {"strlen",strlenCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 117     {"del",delCommand
,-2,"w",0,noPreloadGetKeys
,1,-1,1,0,0}, 
 118     {"exists",existsCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 119     {"setbit",setbitCommand
,4,"wm",0,NULL
,1,1,1,0,0}, 
 120     {"getbit",getbitCommand
,3,"r",0,NULL
,1,1,1,0,0}, 
 121     {"setrange",setrangeCommand
,4,"wm",0,NULL
,1,1,1,0,0}, 
 122     {"getrange",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0}, 
 123     {"substr",getrangeCommand
,4,"r",0,NULL
,1,1,1,0,0}, 
 124     {"incr",incrCommand
,2,"wm",0,NULL
,1,1,1,0,0}, 
 125     {"decr",decrCommand
,2,"wm",0,NULL
,1,1,1,0,0}, 
 126     {"mget",mgetCommand
,-2,"r",0,NULL
,1,-1,1,0,0}, 
 127     {"rpush",rpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0}, 
 128     {"lpush",lpushCommand
,-3,"wm",0,NULL
,1,1,1,0,0}, 
 129     {"rpushx",rpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0}, 
 130     {"lpushx",lpushxCommand
,3,"wm",0,NULL
,1,1,1,0,0}, 
 131     {"linsert",linsertCommand
,5,"wm",0,NULL
,1,1,1,0,0}, 
 132     {"rpop",rpopCommand
,2,"w",0,NULL
,1,1,1,0,0}, 
 133     {"lpop",lpopCommand
,2,"w",0,NULL
,1,1,1,0,0}, 
 134     {"brpop",brpopCommand
,-3,"ws",0,NULL
,1,1,1,0,0}, 
 135     {"brpoplpush",brpoplpushCommand
,4,"wms",0,NULL
,1,2,1,0,0}, 
 136     {"blpop",blpopCommand
,-3,"ws",0,NULL
,1,-2,1,0,0}, 
 137     {"llen",llenCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 138     {"lindex",lindexCommand
,3,"r",0,NULL
,1,1,1,0,0}, 
 139     {"lset",lsetCommand
,4,"wm",0,NULL
,1,1,1,0,0}, 
 140     {"lrange",lrangeCommand
,4,"r",0,NULL
,1,1,1,0,0}, 
 141     {"ltrim",ltrimCommand
,4,"w",0,NULL
,1,1,1,0,0}, 
 142     {"lrem",lremCommand
,4,"w",0,NULL
,1,1,1,0,0}, 
 143     {"rpoplpush",rpoplpushCommand
,3,"wm",0,NULL
,1,2,1,0,0}, 
 144     {"sadd",saddCommand
,-3,"wm",0,NULL
,1,1,1,0,0}, 
 145     {"srem",sremCommand
,-3,"w",0,NULL
,1,1,1,0,0}, 
 146     {"smove",smoveCommand
,4,"w",0,NULL
,1,2,1,0,0}, 
 147     {"sismember",sismemberCommand
,3,"r",0,NULL
,1,1,1,0,0}, 
 148     {"scard",scardCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 149     {"spop",spopCommand
,2,"wRs",0,NULL
,1,1,1,0,0}, 
 150     {"srandmember",srandmemberCommand
,2,"rR",0,NULL
,1,1,1,0,0}, 
 151     {"sinter",sinterCommand
,-2,"rS",0,NULL
,1,-1,1,0,0}, 
 152     {"sinterstore",sinterstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0}, 
 153     {"sunion",sunionCommand
,-2,"rS",0,NULL
,1,-1,1,0,0}, 
 154     {"sunionstore",sunionstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0}, 
 155     {"sdiff",sdiffCommand
,-2,"rS",0,NULL
,1,-1,1,0,0}, 
 156     {"sdiffstore",sdiffstoreCommand
,-3,"wm",0,NULL
,1,-1,1,0,0}, 
 157     {"smembers",sinterCommand
,2,"rS",0,NULL
,1,1,1,0,0}, 
 158     {"zadd",zaddCommand
,-4,"wm",0,NULL
,1,1,1,0,0}, 
 159     {"zincrby",zincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0}, 
 160     {"zrem",zremCommand
,-3,"w",0,NULL
,1,1,1,0,0}, 
 161     {"zremrangebyscore",zremrangebyscoreCommand
,4,"w",0,NULL
,1,1,1,0,0}, 
 162     {"zremrangebyrank",zremrangebyrankCommand
,4,"w",0,NULL
,1,1,1,0,0}, 
 163     {"zunionstore",zunionstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0}, 
 164     {"zinterstore",zinterstoreCommand
,-4,"wm",0,zunionInterGetKeys
,0,0,0,0,0}, 
 165     {"zrange",zrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0}, 
 166     {"zrangebyscore",zrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0}, 
 167     {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,"r",0,NULL
,1,1,1,0,0}, 
 168     {"zcount",zcountCommand
,4,"r",0,NULL
,1,1,1,0,0}, 
 169     {"zrevrange",zrevrangeCommand
,-4,"r",0,NULL
,1,1,1,0,0}, 
 170     {"zcard",zcardCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 171     {"zscore",zscoreCommand
,3,"r",0,NULL
,1,1,1,0,0}, 
 172     {"zrank",zrankCommand
,3,"r",0,NULL
,1,1,1,0,0}, 
 173     {"zrevrank",zrevrankCommand
,3,"r",0,NULL
,1,1,1,0,0}, 
 174     {"hset",hsetCommand
,4,"wm",0,NULL
,1,1,1,0,0}, 
 175     {"hsetnx",hsetnxCommand
,4,"wm",0,NULL
,1,1,1,0,0}, 
 176     {"hget",hgetCommand
,3,"r",0,NULL
,1,1,1,0,0}, 
 177     {"hmset",hmsetCommand
,-4,"wm",0,NULL
,1,1,1,0,0}, 
 178     {"hmget",hmgetCommand
,-3,"r",0,NULL
,1,1,1,0,0}, 
 179     {"hincrby",hincrbyCommand
,4,"wm",0,NULL
,1,1,1,0,0}, 
 180     {"hincrbyfloat",hincrbyfloatCommand
,4,"wm",0,NULL
,1,1,1,0,0}, 
 181     {"hdel",hdelCommand
,-3,"w",0,NULL
,1,1,1,0,0}, 
 182     {"hlen",hlenCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 183     {"hkeys",hkeysCommand
,2,"rS",0,NULL
,1,1,1,0,0}, 
 184     {"hvals",hvalsCommand
,2,"rS",0,NULL
,1,1,1,0,0}, 
 185     {"hgetall",hgetallCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 186     {"hexists",hexistsCommand
,3,"r",0,NULL
,1,1,1,0,0}, 
 187     {"incrby",incrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0}, 
 188     {"decrby",decrbyCommand
,3,"wm",0,NULL
,1,1,1,0,0}, 
 189     {"incrbyfloat",incrbyfloatCommand
,3,"wm",0,NULL
,1,1,1,0,0}, 
 190     {"getset",getsetCommand
,3,"wm",0,NULL
,1,1,1,0,0}, 
 191     {"mset",msetCommand
,-3,"wm",0,NULL
,1,-1,2,0,0}, 
 192     {"msetnx",msetnxCommand
,-3,"wm",0,NULL
,1,-1,2,0,0}, 
 193     {"randomkey",randomkeyCommand
,1,"rR",0,NULL
,0,0,0,0,0}, 
 194     {"select",selectCommand
,2,"r",0,NULL
,0,0,0,0,0}, 
 195     {"move",moveCommand
,3,"w",0,NULL
,1,1,1,0,0}, 
 196     {"rename",renameCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0}, 
 197     {"renamenx",renamenxCommand
,3,"w",0,renameGetKeys
,1,2,1,0,0}, 
 198     {"expire",expireCommand
,3,"w",0,NULL
,1,1,1,0,0}, 
 199     {"expireat",expireatCommand
,3,"w",0,NULL
,1,1,1,0,0}, 
 200     {"pexpire",pexpireCommand
,3,"w",0,NULL
,1,1,1,0,0}, 
 201     {"pexpireat",pexpireatCommand
,3,"w",0,NULL
,1,1,1,0,0}, 
 202     {"keys",keysCommand
,2,"rS",0,NULL
,0,0,0,0,0}, 
 203     {"dbsize",dbsizeCommand
,1,"r",0,NULL
,0,0,0,0,0}, 
 204     {"auth",authCommand
,2,"rs",0,NULL
,0,0,0,0,0}, 
 205     {"ping",pingCommand
,1,"r",0,NULL
,0,0,0,0,0}, 
 206     {"echo",echoCommand
,2,"r",0,NULL
,0,0,0,0,0}, 
 207     {"save",saveCommand
,1,"ars",0,NULL
,0,0,0,0,0}, 
 208     {"bgsave",bgsaveCommand
,1,"ar",0,NULL
,0,0,0,0,0}, 
 209     {"bgrewriteaof",bgrewriteaofCommand
,1,"ar",0,NULL
,0,0,0,0,0}, 
 210     {"shutdown",shutdownCommand
,-1,"ar",0,NULL
,0,0,0,0,0}, 
 211     {"lastsave",lastsaveCommand
,1,"r",0,NULL
,0,0,0,0,0}, 
 212     {"type",typeCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 213     {"multi",multiCommand
,1,"rs",0,NULL
,0,0,0,0,0}, 
 214     {"exec",execCommand
,1,"wms",0,NULL
,0,0,0,0,0}, 
 215     {"discard",discardCommand
,1,"rs",0,NULL
,0,0,0,0,0}, 
 216     {"sync",syncCommand
,1,"ars",0,NULL
,0,0,0,0,0}, 
 217     {"flushdb",flushdbCommand
,1,"w",0,NULL
,0,0,0,0,0}, 
 218     {"flushall",flushallCommand
,1,"w",0,NULL
,0,0,0,0,0}, 
 219     {"sort",sortCommand
,-2,"wmS",0,NULL
,1,1,1,0,0}, 
 220     {"info",infoCommand
,-1,"r",0,NULL
,0,0,0,0,0}, 
 221     {"monitor",monitorCommand
,1,"ars",0,NULL
,0,0,0,0,0}, 
 222     {"ttl",ttlCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 223     {"pttl",pttlCommand
,2,"r",0,NULL
,1,1,1,0,0}, 
 224     {"persist",persistCommand
,2,"w",0,NULL
,1,1,1,0,0}, 
 225     {"slaveof",slaveofCommand
,3,"aws",0,NULL
,0,0,0,0,0}, 
 226     {"debug",debugCommand
,-2,"aws",0,NULL
,0,0,0,0,0}, 
 227     {"config",configCommand
,-2,"ar",0,NULL
,0,0,0,0,0}, 
 228     {"subscribe",subscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0}, 
 229     {"unsubscribe",unsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0}, 
 230     {"psubscribe",psubscribeCommand
,-2,"rps",0,NULL
,0,0,0,0,0}, 
 231     {"punsubscribe",punsubscribeCommand
,-1,"rps",0,NULL
,0,0,0,0,0}, 
 232     {"publish",publishCommand
,3,"rpf",0,NULL
,0,0,0,0,0}, 
 233     {"watch",watchCommand
,-2,"rs",0,noPreloadGetKeys
,1,-1,1,0,0}, 
 234     {"unwatch",unwatchCommand
,1,"rs",0,NULL
,0,0,0,0,0}, 
 235     {"restore",restoreCommand
,4,"awm",0,NULL
,1,1,1,0,0}, 
 236     {"migrate",migrateCommand
,6,"aw",0,NULL
,0,0,0,0,0}, 
 237     {"dump",dumpCommand
,2,"ar",0,NULL
,1,1,1,0,0}, 
 238     {"object",objectCommand
,-2,"r",0,NULL
,2,2,2,0,0}, 
 239     {"client",clientCommand
,-2,"ar",0,NULL
,0,0,0,0,0}, 
 240     {"eval",evalCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0}, 
 241     {"evalsha",evalShaCommand
,-3,"wms",0,zunionInterGetKeys
,0,0,0,0,0}, 
 242     {"slowlog",slowlogCommand
,-2,"r",0,NULL
,0,0,0,0,0}, 
 243     {"script",scriptCommand
,-2,"ras",0,NULL
,0,0,0,0,0}, 
 244     {"time",timeCommand
,1,"rR",0,NULL
,0,0,0,0,0} 
 247 /*============================ Utility functions ============================ */ 
 249 /* Low level logging. To use only for very big messages, otherwise 
 250  * redisLog() is to prefer. */ 
 251 void redisLogRaw(int level
, const char *msg
) { 
 252     const int syslogLevelMap
[] = { LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING 
}; 
 253     const char *c 
= ".-*#"; 
 254     time_t now 
= time(NULL
); 
 257     int rawmode 
= (level 
& REDIS_LOG_RAW
); 
 259     level 
&= 0xff; /* clear flags */ 
 260     if (level 
< server
.verbosity
) return; 
 262     fp 
= (server
.logfile 
== NULL
) ? stdout 
: fopen(server
.logfile
,"a"); 
 266         fprintf(fp
,"%s",msg
); 
 268         strftime(buf
,sizeof(buf
),"%d %b %H:%M:%S",localtime(&now
)); 
 269         fprintf(fp
,"[%d] %s %c %s\n",(int)getpid(),buf
,c
[level
],msg
); 
 273     if (server
.logfile
) fclose(fp
); 
 275     if (server
.syslog_enabled
) syslog(syslogLevelMap
[level
], "%s", msg
); 
 278 /* Like redisLogRaw() but with printf-alike support. This is the funciton that 
 279  * is used across the code. The raw version is only used in order to dump 
 280  * the INFO output on crash. */ 
 281 void redisLog(int level
, const char *fmt
, ...) { 
 283     char msg
[REDIS_MAX_LOGMSG_LEN
]; 
 285     if ((level
&0xff) < server
.verbosity
) return; 
 288     vsnprintf(msg
, sizeof(msg
), fmt
, ap
); 
 291     redisLogRaw(level
,msg
); 
 294 /* Redis generally does not try to recover from out of memory conditions 
 295  * when allocating objects or strings, it is not clear if it will be possible 
 296  * to report this condition to the client since the networking layer itself 
 297  * is based on heap allocation for send buffers, so we simply abort. 
 298  * At least the code will be simpler to read... */ 
 299 void oom(const char *msg
) { 
 300     redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
); 
 305 /* Return the UNIX time in microseconds */ 
 306 long long ustime(void) { 
 310     gettimeofday(&tv
, NULL
); 
 311     ust 
= ((long long)tv
.tv_sec
)*1000000; 
 316 /* Return the UNIX time in milliseconds */ 
 317 long long mstime(void) { 
 318     return ustime()/1000; 
 321 /*====================== Hash table type implementation  ==================== */ 
 323 /* This is an hash table type that uses the SDS dynamic strings libary as 
 324  * keys and radis objects as values (objects can hold SDS strings, 
 327 void dictVanillaFree(void *privdata
, void *val
) 
 329     DICT_NOTUSED(privdata
); 
 333 void dictListDestructor(void *privdata
, void *val
) 
 335     DICT_NOTUSED(privdata
); 
 336     listRelease((list
*)val
); 
 339 int dictSdsKeyCompare(void *privdata
, const void *key1
, 
 343     DICT_NOTUSED(privdata
); 
 345     l1 
= sdslen((sds
)key1
); 
 346     l2 
= sdslen((sds
)key2
); 
 347     if (l1 
!= l2
) return 0; 
 348     return memcmp(key1
, key2
, l1
) == 0; 
 351 /* A case insensitive version used for the command lookup table. */ 
 352 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
, 
 355     DICT_NOTUSED(privdata
); 
 357     return strcasecmp(key1
, key2
) == 0; 
 360 void dictRedisObjectDestructor(void *privdata
, void *val
) 
 362     DICT_NOTUSED(privdata
); 
 364     if (val 
== NULL
) return; /* Values of swapped out keys as set to NULL */ 
 368 void dictSdsDestructor(void *privdata
, void *val
) 
 370     DICT_NOTUSED(privdata
); 
 375 int dictObjKeyCompare(void *privdata
, const void *key1
, 
 378     const robj 
*o1 
= key1
, *o2 
= key2
; 
 379     return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 382 unsigned int dictObjHash(const void *key
) { 
 384     return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 387 unsigned int dictSdsHash(const void *key
) { 
 388     return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
)); 
 391 unsigned int dictSdsCaseHash(const void *key
) { 
 392     return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
)); 
 395 int dictEncObjKeyCompare(void *privdata
, const void *key1
, 
 398     robj 
*o1 
= (robj
*) key1
, *o2 
= (robj
*) key2
; 
 401     if (o1
->encoding 
== REDIS_ENCODING_INT 
&& 
 402         o2
->encoding 
== REDIS_ENCODING_INT
) 
 403             return o1
->ptr 
== o2
->ptr
; 
 405     o1 
= getDecodedObject(o1
); 
 406     o2 
= getDecodedObject(o2
); 
 407     cmp 
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 413 unsigned int dictEncObjHash(const void *key
) { 
 414     robj 
*o 
= (robj
*) key
; 
 416     if (o
->encoding 
== REDIS_ENCODING_RAW
) { 
 417         return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 419         if (o
->encoding 
== REDIS_ENCODING_INT
) { 
 423             len 
= ll2string(buf
,32,(long)o
->ptr
); 
 424             return dictGenHashFunction((unsigned char*)buf
, len
); 
 428             o 
= getDecodedObject(o
); 
 429             hash 
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 436 /* Sets type hash table */ 
 437 dictType setDictType 
= { 
 438     dictEncObjHash
,            /* hash function */ 
 441     dictEncObjKeyCompare
,      /* key compare */ 
 442     dictRedisObjectDestructor
, /* key destructor */ 
 443     NULL                       
/* val destructor */ 
 446 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ 
 447 dictType zsetDictType 
= { 
 448     dictEncObjHash
,            /* hash function */ 
 451     dictEncObjKeyCompare
,      /* key compare */ 
 452     dictRedisObjectDestructor
, /* key destructor */ 
 453     NULL                       
/* val destructor */ 
 456 /* Db->dict, keys are sds strings, vals are Redis objects. */ 
 457 dictType dbDictType 
= { 
 458     dictSdsHash
,                /* hash function */ 
 461     dictSdsKeyCompare
,          /* key compare */ 
 462     dictSdsDestructor
,          /* key destructor */ 
 463     dictRedisObjectDestructor   
/* val destructor */ 
 467 dictType keyptrDictType 
= { 
 468     dictSdsHash
,               /* hash function */ 
 471     dictSdsKeyCompare
,         /* key compare */ 
 472     NULL
,                      /* key destructor */ 
 473     NULL                       
/* val destructor */ 
 476 /* Command table. sds string -> command struct pointer. */ 
 477 dictType commandTableDictType 
= { 
 478     dictSdsCaseHash
,           /* hash function */ 
 481     dictSdsKeyCaseCompare
,     /* key compare */ 
 482     dictSdsDestructor
,         /* key destructor */ 
 483     NULL                       
/* val destructor */ 
 486 /* Hash type hash table (note that small hashes are represented with zimpaps) */ 
 487 dictType hashDictType 
= { 
 488     dictEncObjHash
,             /* hash function */ 
 491     dictEncObjKeyCompare
,       /* key compare */ 
 492     dictRedisObjectDestructor
,  /* key destructor */ 
 493     dictRedisObjectDestructor   
/* val destructor */ 
 496 /* Keylist hash table type has unencoded redis objects as keys and 
 497  * lists as values. It's used for blocking operations (BLPOP) and to 
 498  * map swapped keys to a list of clients waiting for this keys to be loaded. */ 
 499 dictType keylistDictType 
= { 
 500     dictObjHash
,                /* hash function */ 
 503     dictObjKeyCompare
,          /* key compare */ 
 504     dictRedisObjectDestructor
,  /* key destructor */ 
 505     dictListDestructor          
/* val destructor */ 
 508 int htNeedsResize(dict 
*dict
) { 
 509     long long size
, used
; 
 511     size 
= dictSlots(dict
); 
 512     used 
= dictSize(dict
); 
 513     return (size 
&& used 
&& size 
> DICT_HT_INITIAL_SIZE 
&& 
 514             (used
*100/size 
< REDIS_HT_MINFILL
)); 
 517 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL 
 518  * we resize the hash table to save memory */ 
 519 void tryResizeHashTables(void) { 
 522     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 523         if (htNeedsResize(server
.db
[j
].dict
)) 
 524             dictResize(server
.db
[j
].dict
); 
 525         if (htNeedsResize(server
.db
[j
].expires
)) 
 526             dictResize(server
.db
[j
].expires
); 
 530 /* Our hash table implementation performs rehashing incrementally while 
 531  * we write/read from the hash table. Still if the server is idle, the hash 
 532  * table will use two tables for a long time. So we try to use 1 millisecond 
 533  * of CPU time at every serverCron() loop in order to rehash some key. */ 
 534 void incrementallyRehash(void) { 
 537     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 538         if (dictIsRehashing(server
.db
[j
].dict
)) { 
 539             dictRehashMilliseconds(server
.db
[j
].dict
,1); 
 540             break; /* already used our millisecond for this loop... */ 
 545 /* This function is called once a background process of some kind terminates, 
 546  * as we want to avoid resizing the hash tables when there is a child in order 
 547  * to play well with copy-on-write (otherwise when a resize happens lots of 
 548  * memory pages are copied). The goal of this function is to update the ability 
 549  * for dict.c to resize the hash tables accordingly to the fact we have o not 
 551 void updateDictResizePolicy(void) { 
 552     if (server
.rdb_child_pid 
== -1 && server
.aof_child_pid 
== -1) 
 558 /* ======================= Cron: called every 100 ms ======================== */ 
 560 /* Try to expire a few timed out keys. The algorithm used is adaptive and 
 561  * will use few CPU cycles if there are few expiring keys, otherwise 
 562  * it will get more aggressive to avoid that too much memory is used by 
 563  * keys that can be removed from the keyspace. */ 
 564 void activeExpireCycle(void) { 
 567     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 569         redisDb 
*db 
= server
.db
+j
; 
 571         /* Continue to expire if at the end of the cycle more than 25% 
 572          * of the keys were expired. */ 
 574             long num 
= dictSize(db
->expires
); 
 575             long long now 
= mstime(); 
 578             if (num 
> REDIS_EXPIRELOOKUPS_PER_CRON
) 
 579                 num 
= REDIS_EXPIRELOOKUPS_PER_CRON
; 
 584                 if ((de 
= dictGetRandomKey(db
->expires
)) == NULL
) break; 
 585                 t 
= dictGetSignedIntegerVal(de
); 
 587                     sds key 
= dictGetKey(de
); 
 588                     robj 
*keyobj 
= createStringObject(key
,sdslen(key
)); 
 590                     propagateExpire(db
,keyobj
); 
 592                     decrRefCount(keyobj
); 
 594                     server
.stat_expiredkeys
++; 
 597         } while (expired 
> REDIS_EXPIRELOOKUPS_PER_CRON
/4); 
 601 void updateLRUClock(void) { 
 602     server
.lruclock 
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) & 
 607 /* Add a sample to the operations per second array of samples. */ 
 608 void trackOperationsPerSecond(void) { 
 609     long long t 
= mstime() - server
.ops_sec_last_sample_time
; 
 610     long long ops 
= server
.stat_numcommands 
- server
.ops_sec_last_sample_ops
; 
 613     ops_sec 
= t 
> 0 ? (ops
*1000/t
) : 0; 
 615     server
.ops_sec_samples
[server
.ops_sec_idx
] = ops_sec
; 
 616     server
.ops_sec_idx 
= (server
.ops_sec_idx
+1) % REDIS_OPS_SEC_SAMPLES
; 
 617     server
.ops_sec_last_sample_time 
= mstime(); 
 618     server
.ops_sec_last_sample_ops 
= server
.stat_numcommands
; 
 621 /* Return the mean of all the samples. */ 
 622 long long getOperationsPerSecond(void) { 
 626     for (j 
= 0; j 
< REDIS_OPS_SEC_SAMPLES
; j
++) 
 627         sum 
+= server
.ops_sec_samples
[j
]; 
 628     return sum 
/ REDIS_OPS_SEC_SAMPLES
; 
 631 void clientsCronHandleTimeout(redisClient 
*c
) { 
 632     time_t now 
= server
.unixtime
; 
 634     if (server
.maxidletime 
&& 
 635         !(c
->flags 
& REDIS_SLAVE
) &&    /* no timeout for slaves */ 
 636         !(c
->flags 
& REDIS_MASTER
) &&   /* no timeout for masters */ 
 637         !(c
->flags 
& REDIS_BLOCKED
) &&  /* no timeout for BLPOP */ 
 638         dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */ 
 639         listLength(c
->pubsub_patterns
) == 0 && 
 640         (now 
- c
->lastinteraction 
> server
.maxidletime
)) 
 642         redisLog(REDIS_VERBOSE
,"Closing idle client"); 
 644     } else if (c
->flags 
& REDIS_BLOCKED
) { 
 645         if (c
->bpop
.timeout 
!= 0 && c
->bpop
.timeout 
< now
) { 
 646             addReply(c
,shared
.nullmultibulk
); 
 647             unblockClientWaitingData(c
); 
 652 /* The client query buffer is an sds.c string that can end with a lot of 
 653  * free space not used, this function reclaims space if needed. */ 
 654 void clientsCronResizeQueryBuffer(redisClient 
*c
) { 
 655     size_t querybuf_size 
= sdsAllocSize(c
->querybuf
); 
 656     time_t idletime 
= server
.unixtime 
- c
->lastinteraction
; 
 658     /* There are two conditions to resize the query buffer: 
 659      * 1) Query buffer is > BIG_ARG and too big for latest peak. 
 660      * 2) Client is inactive and the buffer is bigger than 1k. */ 
 661     if (((querybuf_size 
> REDIS_MBULK_BIG_ARG
) && 
 662          (querybuf_size
/(c
->querybuf_peak
+1)) > 2) || 
 663          (querybuf_size 
> 1024 && idletime 
> 2)) 
 665         /* Only resize the query buffer if it is actually wasting space. */ 
 666         if (sdsavail(c
->querybuf
) > 1024) { 
 667             c
->querybuf 
= sdsRemoveFreeSpace(c
->querybuf
); 
 670     /* Reset the peak again to capture the peak memory usage in the next 
 672     c
->querybuf_peak 
= 0; 
 675 void clientsCron(void) { 
 676     /* Make sure to process at least 1/100 of clients per call. 
 677      * Since this function is called 10 times per second we are sure that 
 678      * in the worst case we process all the clients in 10 seconds. 
 679      * In normal conditions (a reasonable number of clients) we process 
 680      * all the clients in a shorter time. */ 
 681     int numclients 
= listLength(server
.clients
); 
 682     int iterations 
= numclients
/100; 
 685         iterations 
= (numclients 
< 50) ? numclients 
: 50; 
 686     while(listLength(server
.clients
) && iterations
--) { 
 690         /* Rotate the list, take the current head, process. 
 691          * This way if the client must be removed from the list it's the 
 692          * first element and we don't incur into O(N) computation. */ 
 693         listRotate(server
.clients
); 
 694         head 
= listFirst(server
.clients
); 
 695         c 
= listNodeValue(head
); 
 696         clientsCronHandleTimeout(c
); 
 697         clientsCronResizeQueryBuffer(c
); 
 701 int serverCron(struct aeEventLoop 
*eventLoop
, long long id
, void *clientData
) { 
 702     int j
, loops 
= server
.cronloops
; 
 703     REDIS_NOTUSED(eventLoop
); 
 705     REDIS_NOTUSED(clientData
); 
 707     /* We take a cached value of the unix time in the global state because 
 708      * with virtual memory and aging there is to store the current time 
 709      * in objects at every object access, and accuracy is not needed. 
 710      * To access a global var is faster than calling time(NULL) */ 
 711     server
.unixtime 
= time(NULL
); 
 713     trackOperationsPerSecond(); 
 715     /* We have just 22 bits per object for LRU information. 
 716      * So we use an (eventually wrapping) LRU clock with 10 seconds resolution. 
 717      * 2^22 bits with 10 seconds resoluton is more or less 1.5 years. 
 719      * Note that even if this will wrap after 1.5 years it's not a problem, 
 720      * everything will still work but just some object will appear younger 
 721      * to Redis. But for this to happen a given object should never be touched 
 724      * Note that you can change the resolution altering the 
 725      * REDIS_LRU_CLOCK_RESOLUTION define. 
 729     /* Record the max memory used since the server was started. */ 
 730     if (zmalloc_used_memory() > server
.stat_peak_memory
) 
 731         server
.stat_peak_memory 
= zmalloc_used_memory(); 
 733     /* We received a SIGTERM, shutting down here in a safe way, as it is 
 734      * not ok doing so inside the signal handler. */ 
 735     if (server
.shutdown_asap
) { 
 736         if (prepareForShutdown(0) == REDIS_OK
) exit(0); 
 737         redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); 
 740     /* Show some info about non-empty databases */ 
 741     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 742         long long size
, used
, vkeys
; 
 744         size 
= dictSlots(server
.db
[j
].dict
); 
 745         used 
= dictSize(server
.db
[j
].dict
); 
 746         vkeys 
= dictSize(server
.db
[j
].expires
); 
 747         if (!(loops 
% 50) && (used 
|| vkeys
)) { 
 748             redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
); 
 749             /* dictPrintStats(server.dict); */ 
 753     /* We don't want to resize the hash tables while a bacground saving 
 754      * is in progress: the saving child is created using fork() that is 
 755      * implemented with a copy-on-write semantic in most modern systems, so 
 756      * if we resize the HT while there is the saving child at work actually 
 757      * a lot of memory movements in the parent will cause a lot of pages 
 759     if (server
.rdb_child_pid 
== -1 && server
.aof_child_pid 
== -1) { 
 760         if (!(loops 
% 10)) tryResizeHashTables(); 
 761         if (server
.activerehashing
) incrementallyRehash(); 
 764     /* Show information about connected clients */ 
 766         redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use", 
 767             listLength(server
.clients
)-listLength(server
.slaves
), 
 768             listLength(server
.slaves
), 
 769             zmalloc_used_memory()); 
 772     /* We need to do a few operations on clients asynchronously. */ 
 775     /* Start a scheduled AOF rewrite if this was requested by the user while 
 776      * a BGSAVE was in progress. */ 
 777     if (server
.rdb_child_pid 
== -1 && server
.aof_child_pid 
== -1 && 
 778         server
.aof_rewrite_scheduled
) 
 780         rewriteAppendOnlyFileBackground(); 
 783     /* Check if a background saving or AOF rewrite in progress terminated. */ 
 784     if (server
.rdb_child_pid 
!= -1 || server
.aof_child_pid 
!= -1) { 
 788         if ((pid 
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) { 
 789             int exitcode 
= WEXITSTATUS(statloc
); 
 792             if (WIFSIGNALED(statloc
)) bysignal 
= WTERMSIG(statloc
); 
 794             if (pid 
== server
.rdb_child_pid
) { 
 795                 backgroundSaveDoneHandler(exitcode
,bysignal
); 
 797                 backgroundRewriteDoneHandler(exitcode
,bysignal
); 
 799             updateDictResizePolicy(); 
 802          time_t now 
= time(NULL
); 
 804         /* If there is not a background saving/rewrite in progress check if 
 805          * we have to save/rewrite now */ 
 806          for (j 
= 0; j 
< server
.saveparamslen
; j
++) { 
 807             struct saveparam 
*sp 
= server
.saveparams
+j
; 
 809             if (server
.dirty 
>= sp
->changes 
&& 
 810                 now
-server
.lastsave 
> sp
->seconds
) { 
 811                 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...", 
 812                     sp
->changes
, sp
->seconds
); 
 813                 rdbSaveBackground(server
.rdb_filename
); 
 818          /* Trigger an AOF rewrite if needed */ 
 819          if (server
.rdb_child_pid 
== -1 && 
 820              server
.aof_child_pid 
== -1 && 
 821              server
.aof_rewrite_perc 
&& 
 822              server
.aof_current_size 
> server
.aof_rewrite_min_size
) 
 824             long long base 
= server
.aof_rewrite_base_size 
? 
 825                             server
.aof_rewrite_base_size 
: 1; 
 826             long long growth 
= (server
.aof_current_size
*100/base
) - 100; 
 827             if (growth 
>= server
.aof_rewrite_perc
) { 
 828                 redisLog(REDIS_NOTICE
,"Starting automatic rewriting of AOF on %lld%% growth",growth
); 
 829                 rewriteAppendOnlyFileBackground(); 
 835     /* If we postponed an AOF buffer flush, let's try to do it every time the 
 836      * cron function is called. */ 
 837     if (server
.aof_flush_postponed_start
) flushAppendOnlyFile(0); 
 839     /* Expire a few keys per cycle, only if this is a master. 
 840      * On slaves we wait for DEL operations synthesized by the master 
 841      * in order to guarantee a strict consistency. */ 
 842     if (server
.masterhost 
== NULL
) activeExpireCycle(); 
 844     /* Close clients that need to be closed asynchronous */ 
 845     freeClientsInAsyncFreeQueue(); 
 847     /* Replication cron function -- used to reconnect to master and 
 848      * to detect transfer failures. */ 
 849     if (!(loops 
% 10)) replicationCron(); 
 855 /* This function gets called every time Redis is entering the 
 856  * main loop of the event driven library, that is, before to sleep 
 857  * for ready file descriptors. */ 
 858 void beforeSleep(struct aeEventLoop 
*eventLoop
) { 
 859     REDIS_NOTUSED(eventLoop
); 
 863     /* Try to process pending commands for clients that were just unblocked. */ 
 864     while (listLength(server
.unblocked_clients
)) { 
 865         ln 
= listFirst(server
.unblocked_clients
); 
 866         redisAssert(ln 
!= NULL
); 
 868         listDelNode(server
.unblocked_clients
,ln
); 
 869         c
->flags 
&= ~REDIS_UNBLOCKED
; 
 871         /* Process remaining data in the input buffer. */ 
 872         if (c
->querybuf 
&& sdslen(c
->querybuf
) > 0) { 
 873             server
.current_client 
= c
; 
 874             processInputBuffer(c
); 
 875             server
.current_client 
= NULL
; 
 879     /* Write the AOF buffer on disk */ 
 880     flushAppendOnlyFile(0); 
 883 /* =========================== Server initialization ======================== */ 
 885 void createSharedObjects(void) { 
 888     shared
.crlf 
= createObject(REDIS_STRING
,sdsnew("\r\n")); 
 889     shared
.ok 
= createObject(REDIS_STRING
,sdsnew("+OK\r\n")); 
 890     shared
.err 
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n")); 
 891     shared
.emptybulk 
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n")); 
 892     shared
.czero 
= createObject(REDIS_STRING
,sdsnew(":0\r\n")); 
 893     shared
.cone 
= createObject(REDIS_STRING
,sdsnew(":1\r\n")); 
 894     shared
.cnegone 
= createObject(REDIS_STRING
,sdsnew(":-1\r\n")); 
 895     shared
.nullbulk 
= createObject(REDIS_STRING
,sdsnew("$-1\r\n")); 
 896     shared
.nullmultibulk 
= createObject(REDIS_STRING
,sdsnew("*-1\r\n")); 
 897     shared
.emptymultibulk 
= createObject(REDIS_STRING
,sdsnew("*0\r\n")); 
 898     shared
.pong 
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n")); 
 899     shared
.queued 
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n")); 
 900     shared
.wrongtypeerr 
= createObject(REDIS_STRING
,sdsnew( 
 901         "-ERR Operation against a key holding the wrong kind of value\r\n")); 
 902     shared
.nokeyerr 
= createObject(REDIS_STRING
,sdsnew( 
 903         "-ERR no such key\r\n")); 
 904     shared
.syntaxerr 
= createObject(REDIS_STRING
,sdsnew( 
 905         "-ERR syntax error\r\n")); 
 906     shared
.sameobjecterr 
= createObject(REDIS_STRING
,sdsnew( 
 907         "-ERR source and destination objects are the same\r\n")); 
 908     shared
.outofrangeerr 
= createObject(REDIS_STRING
,sdsnew( 
 909         "-ERR index out of range\r\n")); 
 910     shared
.noscripterr 
= createObject(REDIS_STRING
,sdsnew( 
 911         "-NOSCRIPT No matching script. Please use EVAL.\r\n")); 
 912     shared
.loadingerr 
= createObject(REDIS_STRING
,sdsnew( 
 913         "-LOADING Redis is loading the dataset in memory\r\n")); 
 914     shared
.slowscripterr 
= createObject(REDIS_STRING
,sdsnew( 
 915         "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n")); 
 916     shared
.bgsaveerr 
= createObject(REDIS_STRING
,sdsnew( 
 917         "-MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Write commands are disabled. Please check Redis logs for details about the error.\r\n")); 
 918     shared
.space 
= createObject(REDIS_STRING
,sdsnew(" ")); 
 919     shared
.colon 
= createObject(REDIS_STRING
,sdsnew(":")); 
 920     shared
.plus 
= createObject(REDIS_STRING
,sdsnew("+")); 
 921     shared
.select0 
= createStringObject("select 0\r\n",10); 
 922     shared
.select1 
= createStringObject("select 1\r\n",10); 
 923     shared
.select2 
= createStringObject("select 2\r\n",10); 
 924     shared
.select3 
= createStringObject("select 3\r\n",10); 
 925     shared
.select4 
= createStringObject("select 4\r\n",10); 
 926     shared
.select5 
= createStringObject("select 5\r\n",10); 
 927     shared
.select6 
= createStringObject("select 6\r\n",10); 
 928     shared
.select7 
= createStringObject("select 7\r\n",10); 
 929     shared
.select8 
= createStringObject("select 8\r\n",10); 
 930     shared
.select9 
= createStringObject("select 9\r\n",10); 
 931     shared
.messagebulk 
= createStringObject("$7\r\nmessage\r\n",13); 
 932     shared
.pmessagebulk 
= createStringObject("$8\r\npmessage\r\n",14); 
 933     shared
.subscribebulk 
= createStringObject("$9\r\nsubscribe\r\n",15); 
 934     shared
.unsubscribebulk 
= createStringObject("$11\r\nunsubscribe\r\n",18); 
 935     shared
.psubscribebulk 
= createStringObject("$10\r\npsubscribe\r\n",17); 
 936     shared
.punsubscribebulk 
= createStringObject("$12\r\npunsubscribe\r\n",19); 
 937     shared
.del 
= createStringObject("DEL",3); 
 938     shared
.rpop 
= createStringObject("RPOP",4); 
 939     shared
.lpop 
= createStringObject("LPOP",4); 
 940     for (j 
= 0; j 
< REDIS_SHARED_INTEGERS
; j
++) { 
 941         shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
); 
 942         shared
.integers
[j
]->encoding 
= REDIS_ENCODING_INT
; 
 944     for (j 
= 0; j 
< REDIS_SHARED_BULKHDR_LEN
; j
++) { 
 945         shared
.mbulkhdr
[j
] = createObject(REDIS_STRING
, 
 946             sdscatprintf(sdsempty(),"*%d\r\n",j
)); 
 947         shared
.bulkhdr
[j
] = createObject(REDIS_STRING
, 
 948             sdscatprintf(sdsempty(),"$%d\r\n",j
)); 
 952 void initServerConfig() { 
 953     getRandomHexChars(server
.runid
,REDIS_RUN_ID_SIZE
); 
 954     server
.runid
[REDIS_RUN_ID_SIZE
] = '\0'; 
 955     server
.arch_bits 
= (sizeof(long) == 8) ? 64 : 32; 
 956     server
.port 
= REDIS_SERVERPORT
; 
 957     server
.bindaddr 
= NULL
; 
 958     server
.unixsocket 
= NULL
; 
 959     server
.unixsocketperm 
= 0; 
 962     server
.dbnum 
= REDIS_DEFAULT_DBNUM
; 
 963     server
.verbosity 
= REDIS_NOTICE
; 
 964     server
.maxidletime 
= REDIS_MAXIDLETIME
; 
 965     server
.client_max_querybuf_len 
= REDIS_MAX_QUERYBUF_LEN
; 
 966     server
.saveparams 
= NULL
; 
 968     server
.logfile 
= NULL
; /* NULL = log on standard output */ 
 969     server
.syslog_enabled 
= 0; 
 970     server
.syslog_ident 
= zstrdup("redis"); 
 971     server
.syslog_facility 
= LOG_LOCAL0
; 
 972     server
.daemonize 
= 0; 
 973     server
.aof_state 
= REDIS_AOF_OFF
; 
 974     server
.aof_fsync 
= AOF_FSYNC_EVERYSEC
; 
 975     server
.aof_no_fsync_on_rewrite 
= 0; 
 976     server
.aof_rewrite_perc 
= REDIS_AOF_REWRITE_PERC
; 
 977     server
.aof_rewrite_min_size 
= REDIS_AOF_REWRITE_MIN_SIZE
; 
 978     server
.aof_rewrite_base_size 
= 0; 
 979     server
.aof_rewrite_scheduled 
= 0; 
 980     server
.aof_last_fsync 
= time(NULL
); 
 982     server
.aof_selected_db 
= -1; /* Make sure the first time will not match */ 
 983     server
.aof_flush_postponed_start 
= 0; 
 984     server
.pidfile 
= zstrdup("/var/run/redis.pid"); 
 985     server
.rdb_filename 
= zstrdup("dump.rdb"); 
 986     server
.aof_filename 
= zstrdup("appendonly.aof"); 
 987     server
.requirepass 
= NULL
; 
 988     server
.rdb_compression 
= 1; 
 989     server
.activerehashing 
= 1; 
 990     server
.maxclients 
= REDIS_MAX_CLIENTS
; 
 991     server
.bpop_blocked_clients 
= 0; 
 992     server
.maxmemory 
= 0; 
 993     server
.maxmemory_policy 
= REDIS_MAXMEMORY_VOLATILE_LRU
; 
 994     server
.maxmemory_samples 
= 3; 
 995     server
.hash_max_ziplist_entries 
= REDIS_HASH_MAX_ZIPLIST_ENTRIES
; 
 996     server
.hash_max_ziplist_value 
= REDIS_HASH_MAX_ZIPLIST_VALUE
; 
 997     server
.list_max_ziplist_entries 
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
; 
 998     server
.list_max_ziplist_value 
= REDIS_LIST_MAX_ZIPLIST_VALUE
; 
 999     server
.set_max_intset_entries 
= REDIS_SET_MAX_INTSET_ENTRIES
; 
1000     server
.zset_max_ziplist_entries 
= REDIS_ZSET_MAX_ZIPLIST_ENTRIES
; 
1001     server
.zset_max_ziplist_value 
= REDIS_ZSET_MAX_ZIPLIST_VALUE
; 
1002     server
.shutdown_asap 
= 0; 
1003     server
.repl_ping_slave_period 
= REDIS_REPL_PING_SLAVE_PERIOD
; 
1004     server
.repl_timeout 
= REDIS_REPL_TIMEOUT
; 
1005     server
.lua_caller 
= NULL
; 
1006     server
.lua_time_limit 
= REDIS_LUA_TIME_LIMIT
; 
1007     server
.lua_client 
= NULL
; 
1008     server
.lua_timedout 
= 0; 
1011     resetServerSaveParams(); 
1013     appendServerSaveParams(60*60,1);  /* save after 1 hour and 1 change */ 
1014     appendServerSaveParams(300,100);  /* save after 5 minutes and 100 changes */ 
1015     appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ 
1016     /* Replication related */ 
1017     server
.masterauth 
= NULL
; 
1018     server
.masterhost 
= NULL
; 
1019     server
.masterport 
= 6379; 
1020     server
.master 
= NULL
; 
1021     server
.repl_state 
= REDIS_REPL_NONE
; 
1022     server
.repl_syncio_timeout 
= REDIS_REPL_SYNCIO_TIMEOUT
; 
1023     server
.repl_serve_stale_data 
= 1; 
1024     server
.repl_down_since 
= -1; 
1026     /* Client output buffer limits */ 
1027     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_NORMAL
].hard_limit_bytes 
= 0; 
1028     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_NORMAL
].soft_limit_bytes 
= 0; 
1029     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_NORMAL
].soft_limit_seconds 
= 0; 
1030     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_SLAVE
].hard_limit_bytes 
= 1024*1024*256; 
1031     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_SLAVE
].soft_limit_bytes 
= 1024*1024*64; 
1032     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_SLAVE
].soft_limit_seconds 
= 60; 
1033     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_PUBSUB
].hard_limit_bytes 
= 1024*1024*32; 
1034     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_PUBSUB
].soft_limit_bytes 
= 1024*1024*8; 
1035     server
.client_obuf_limits
[REDIS_CLIENT_LIMIT_CLASS_PUBSUB
].soft_limit_seconds 
= 60; 
1037     /* Double constants initialization */ 
1039     R_PosInf 
= 1.0/R_Zero
; 
1040     R_NegInf 
= -1.0/R_Zero
; 
1041     R_Nan 
= R_Zero
/R_Zero
; 
1043     /* Command table -- we intiialize it here as it is part of the 
1044      * initial configuration, since command names may be changed via 
1045      * redis.conf using the rename-command directive. */ 
1046     server
.commands 
= dictCreate(&commandTableDictType
,NULL
); 
1047     populateCommandTable(); 
1048     server
.delCommand 
= lookupCommandByCString("del"); 
1049     server
.multiCommand 
= lookupCommandByCString("multi"); 
1050     server
.lpushCommand 
= lookupCommandByCString("lpush"); 
1053     server
.slowlog_log_slower_than 
= REDIS_SLOWLOG_LOG_SLOWER_THAN
; 
1054     server
.slowlog_max_len 
= REDIS_SLOWLOG_MAX_LEN
; 
1057     server
.assert_failed 
= "<no assertion failed>"; 
1058     server
.assert_file 
= "<no file>"; 
1059     server
.assert_line 
= 0; 
1060     server
.bug_report_start 
= 0; 
1063 /* This function will try to raise the max number of open files accordingly to 
1064  * the configured max number of clients. It will also account for 32 additional 
1065  * file descriptors as we need a few more for persistence, listening 
1066  * sockets, log files and so forth. 
1068  * If it will not be possible to set the limit accordingly to the configured 
1069  * max number of clients, the function will do the reverse setting 
1070  * server.maxclients to the value that we can actually handle. */ 
1071 void adjustOpenFilesLimit(void) { 
1072     rlim_t maxfiles 
= server
.maxclients
+32; 
1073     struct rlimit limit
; 
1075     if (maxfiles 
< 1024) maxfiles 
= 1024; 
1076     if (getrlimit(RLIMIT_NOFILE
,&limit
) == -1) { 
1077         redisLog(REDIS_WARNING
,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.", 
1079         server
.maxclients 
= 1024-32; 
1081         rlim_t oldlimit 
= limit
.rlim_cur
; 
1083         /* Set the max number of files if the current limit is not enough 
1085         if (oldlimit 
< maxfiles
) { 
1086             limit
.rlim_cur 
= maxfiles
; 
1087             limit
.rlim_max 
= maxfiles
; 
1088             if (setrlimit(RLIMIT_NOFILE
,&limit
) == -1) { 
1089                 server
.maxclients 
= oldlimit
-32; 
1090                 redisLog(REDIS_WARNING
,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.", 
1091                     (int) maxfiles
, strerror(errno
), (int) server
.maxclients
); 
1093                 redisLog(REDIS_NOTICE
,"Max number of open files set to %d", 
1103     signal(SIGHUP
, SIG_IGN
); 
1104     signal(SIGPIPE
, SIG_IGN
); 
1105     setupSignalHandlers(); 
1107     if (server
.syslog_enabled
) { 
1108         openlog(server
.syslog_ident
, LOG_PID 
| LOG_NDELAY 
| LOG_NOWAIT
, 
1109             server
.syslog_facility
); 
1112     server
.current_client 
= NULL
; 
1113     server
.clients 
= listCreate(); 
1114     server
.clients_to_close 
= listCreate(); 
1115     server
.slaves 
= listCreate(); 
1116     server
.monitors 
= listCreate(); 
1117     server
.unblocked_clients 
= listCreate(); 
1119     createSharedObjects(); 
1120     adjustOpenFilesLimit(); 
1121     server
.el 
= aeCreateEventLoop(server
.maxclients
+1024); 
1122     server
.db 
= zmalloc(sizeof(redisDb
)*server
.dbnum
); 
1124     if (server
.port 
!= 0) { 
1125         server
.ipfd 
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
); 
1126         if (server
.ipfd 
== ANET_ERR
) { 
1127             redisLog(REDIS_WARNING
, "Opening port %d: %s", 
1128                 server
.port
, server
.neterr
); 
1132     if (server
.unixsocket 
!= NULL
) { 
1133         unlink(server
.unixsocket
); /* don't care if this fails */ 
1134         server
.sofd 
= anetUnixServer(server
.neterr
,server
.unixsocket
,server
.unixsocketperm
); 
1135         if (server
.sofd 
== ANET_ERR
) { 
1136             redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
); 
1140     if (server
.ipfd 
< 0 && server
.sofd 
< 0) { 
1141         redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting."); 
1144     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1145         server
.db
[j
].dict 
= dictCreate(&dbDictType
,NULL
); 
1146         server
.db
[j
].expires 
= dictCreate(&keyptrDictType
,NULL
); 
1147         server
.db
[j
].blocking_keys 
= dictCreate(&keylistDictType
,NULL
); 
1148         server
.db
[j
].watched_keys 
= dictCreate(&keylistDictType
,NULL
); 
1149         server
.db
[j
].id 
= j
; 
1151     server
.pubsub_channels 
= dictCreate(&keylistDictType
,NULL
); 
1152     server
.pubsub_patterns 
= listCreate(); 
1153     listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
); 
1154     listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
); 
1155     server
.cronloops 
= 0; 
1156     server
.rdb_child_pid 
= -1; 
1157     server
.aof_child_pid 
= -1; 
1158     server
.aof_rewrite_buf 
= sdsempty(); 
1159     server
.aof_buf 
= sdsempty(); 
1160     server
.lastsave 
= time(NULL
); 
1162     server
.stat_numcommands 
= 0; 
1163     server
.stat_numconnections 
= 0; 
1164     server
.stat_expiredkeys 
= 0; 
1165     server
.stat_evictedkeys 
= 0; 
1166     server
.stat_starttime 
= time(NULL
); 
1167     server
.stat_keyspace_misses 
= 0; 
1168     server
.stat_keyspace_hits 
= 0; 
1169     server
.stat_peak_memory 
= 0; 
1170     server
.stat_fork_time 
= 0; 
1171     server
.stat_rejected_conn 
= 0; 
1172     memset(server
.ops_sec_samples
,0,sizeof(server
.ops_sec_samples
)); 
1173     server
.ops_sec_idx 
= 0; 
1174     server
.ops_sec_last_sample_time 
= mstime(); 
1175     server
.ops_sec_last_sample_ops 
= 0; 
1176     server
.unixtime 
= time(NULL
); 
1177     server
.lastbgsave_status 
= REDIS_OK
; 
1178     server
.stop_writes_on_bgsave_err 
= 1; 
1179     aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
); 
1180     if (server
.ipfd 
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
, 
1181         acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event"); 
1182     if (server
.sofd 
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
, 
1183         acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event"); 
1185     if (server
.aof_state 
== REDIS_AOF_ON
) { 
1186         server
.aof_fd 
= open(server
.aof_filename
, 
1187                                O_WRONLY
|O_APPEND
|O_CREAT
,0644); 
1188         if (server
.aof_fd 
== -1) { 
1189             redisLog(REDIS_WARNING
, "Can't open the append-only file: %s", 
1195     /* 32 bit instances are limited to 4GB of address space, so if there is 
1196      * no explicit limit in the user provided configuration we set a limit 
1197      * at 3.5GB using maxmemory with 'noeviction' policy'. This saves 
1198      * useless crashes of the Redis instance. */ 
1199     if (server
.arch_bits 
== 32 && server
.maxmemory 
== 0) { 
1200         redisLog(REDIS_WARNING
,"Warning: 32 bit instance detected but no memory limit set. Setting 3.5 GB maxmemory limit with 'noeviction' policy now."); 
1201         server
.maxmemory 
= 3584LL*(1024*1024); /* 3584 MB = 3.5 GB */ 
1202         server
.maxmemory_policy 
= REDIS_MAXMEMORY_NO_EVICTION
; 
1210 /* Populates the Redis Command Table starting from the hard coded list 
1211  * we have on top of redis.c file. */ 
1212 void populateCommandTable(void) { 
1214     int numcommands 
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
); 
1216     for (j 
= 0; j 
< numcommands
; j
++) { 
1217         struct redisCommand 
*c 
= redisCommandTable
+j
; 
1218         char *f 
= c
->sflags
; 
1223             case 'w': c
->flags 
|= REDIS_CMD_WRITE
; break; 
1224             case 'r': c
->flags 
|= REDIS_CMD_READONLY
; break; 
1225             case 'm': c
->flags 
|= REDIS_CMD_DENYOOM
; break; 
1226             case 'a': c
->flags 
|= REDIS_CMD_ADMIN
; break; 
1227             case 'p': c
->flags 
|= REDIS_CMD_PUBSUB
; break; 
1228             case 'f': c
->flags 
|= REDIS_CMD_FORCE_REPLICATION
; break; 
1229             case 's': c
->flags 
|= REDIS_CMD_NOSCRIPT
; break; 
1230             case 'R': c
->flags 
|= REDIS_CMD_RANDOM
; break; 
1231             case 'S': c
->flags 
|= REDIS_CMD_SORT_FOR_SCRIPT
; break; 
1232             default: redisPanic("Unsupported command flag"); break; 
1237         retval 
= dictAdd(server
.commands
, sdsnew(c
->name
), c
); 
1238         assert(retval 
== DICT_OK
); 
1242 void resetCommandTableStats(void) { 
1243     int numcommands 
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
); 
1246     for (j 
= 0; j 
< numcommands
; j
++) { 
1247         struct redisCommand 
*c 
= redisCommandTable
+j
; 
1249         c
->microseconds 
= 0; 
1254 /* ========================== Redis OP Array API ============================ */ 
1256 void redisOpArrayInit(redisOpArray 
*oa
) { 
1261 int redisOpArrayAppend(redisOpArray 
*oa
, struct redisCommand 
*cmd
, int dbid
, 
1262                        robj 
**argv
, int argc
, int target
) 
1266     oa
->ops 
= zrealloc(oa
->ops
,sizeof(redisOp
)*(oa
->numops
+1)); 
1267     op 
= oa
->ops
+oa
->numops
; 
1272     op
->target 
= target
; 
1277 void redisOpArrayFree(redisOpArray 
*oa
) { 
1283         op 
= oa
->ops
+oa
->numops
; 
1284         for (j 
= 0; j 
< op
->argc
; j
++) 
1285             decrRefCount(op
->argv
[j
]); 
1291 /* ====================== Commands lookup and execution ===================== */ 
1293 struct redisCommand 
*lookupCommand(sds name
) { 
1294     return dictFetchValue(server
.commands
, name
); 
1297 struct redisCommand 
*lookupCommandByCString(char *s
) { 
1298     struct redisCommand 
*cmd
; 
1299     sds name 
= sdsnew(s
); 
1301     cmd 
= dictFetchValue(server
.commands
, name
); 
1306 /* Propagate the specified command (in the context of the specified database id) 
1307  * to AOF, Slaves and Monitors. 
1309  * flags are an xor between: 
1310  * + REDIS_PROPAGATE_NONE (no propagation of command at all) 
1311  * + REDIS_PROPAGATE_AOF (propagate into the AOF file if is enabled) 
1312  * + REDIS_PROPAGATE_REPL (propagate into the replication link) 
1314 void propagate(struct redisCommand 
*cmd
, int dbid
, robj 
**argv
, int argc
, 
1317     if (server
.aof_state 
!= REDIS_AOF_OFF 
&& flags 
& REDIS_PROPAGATE_AOF
) 
1318         feedAppendOnlyFile(cmd
,dbid
,argv
,argc
); 
1319     if (flags 
& REDIS_PROPAGATE_REPL 
&& listLength(server
.slaves
)) 
1320         replicationFeedSlaves(server
.slaves
,dbid
,argv
,argc
); 
1323 /* Used inside commands to schedule the propagation of additional commands 
1324  * after the current command is propagated to AOF / Replication. */ 
1325 void alsoPropagate(struct redisCommand 
*cmd
, int dbid
, robj 
**argv
, int argc
, 
1328     redisOpArrayAppend(&server
.also_propagate
,cmd
,dbid
,argv
,argc
,target
); 
1331 /* Call() is the core of Redis execution of a command */ 
1332 void call(redisClient 
*c
, int flags
) { 
1333     long long dirty
, start 
= ustime(), duration
; 
1335     /* Sent the command to clients in MONITOR mode, only if the commands are 
1336      * not geneated from reading an AOF. */ 
1337     if (listLength(server
.monitors
) && !server
.loading
) 
1338         replicationFeedMonitors(c
,server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
); 
1340     /* Call the command. */ 
1341     redisOpArrayInit(&server
.also_propagate
); 
1342     dirty 
= server
.dirty
; 
1344     dirty 
= server
.dirty
-dirty
; 
1345     duration 
= ustime()-start
; 
1347     /* When EVAL is called loading the AOF we don't want commands called 
1348      * from Lua to go into the slowlog or to populate statistics. */ 
1349     if (server
.loading 
&& c
->flags 
& REDIS_LUA_CLIENT
) 
1350         flags 
&= ~(REDIS_CALL_SLOWLOG 
| REDIS_CALL_STATS
); 
1352     /* Log the command into the Slow log if needed, and populate the 
1353      * per-command statistics that we show in INFO commandstats. */ 
1354     if (flags 
& REDIS_CALL_SLOWLOG
) 
1355         slowlogPushEntryIfNeeded(c
->argv
,c
->argc
,duration
); 
1356     if (flags 
& REDIS_CALL_STATS
) { 
1357         c
->cmd
->microseconds 
+= duration
; 
1361     /* Propagate the command into the AOF and replication link */ 
1362     if (flags 
& REDIS_CALL_PROPAGATE
) { 
1363         int flags 
= REDIS_PROPAGATE_NONE
; 
1365         if (c
->cmd
->flags 
& REDIS_CMD_FORCE_REPLICATION
) 
1366             flags 
|= REDIS_PROPAGATE_REPL
; 
1368             flags 
|= (REDIS_PROPAGATE_REPL 
| REDIS_PROPAGATE_AOF
); 
1369         if (flags 
!= REDIS_PROPAGATE_NONE
) 
1370             propagate(c
->cmd
,c
->db
->id
,c
->argv
,c
->argc
,flags
); 
1372     /* Commands such as LPUSH or BRPOPLPUSH may propagate an additional 
1374     if (server
.also_propagate
.numops
) { 
1378         for (j 
= 0; j 
< server
.also_propagate
.numops
; j
++) { 
1379             rop 
= &server
.also_propagate
.ops
[j
]; 
1380             propagate(rop
->cmd
, rop
->dbid
, rop
->argv
, rop
->argc
, rop
->target
); 
1382         redisOpArrayFree(&server
.also_propagate
); 
1384     server
.stat_numcommands
++; 
1387 /* If this function gets called we already read a whole 
1388  * command, argments are in the client argv/argc fields. 
1389  * processCommand() execute the command or prepare the 
1390  * server for a bulk read from the client. 
1392  * If 1 is returned the client is still alive and valid and 
1393  * and other operations can be performed by the caller. Otherwise 
1394  * if 0 is returned the client was destroied (i.e. after QUIT). */ 
1395 int processCommand(redisClient 
*c
) { 
1396     /* The QUIT command is handled separately. Normal command procs will 
1397      * go through checking for replication and QUIT will cause trouble 
1398      * when FORCE_REPLICATION is enabled and would be implemented in 
1399      * a regular command proc. */ 
1400     if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) { 
1401         addReply(c
,shared
.ok
); 
1402         c
->flags 
|= REDIS_CLOSE_AFTER_REPLY
; 
1406     /* Now lookup the command and check ASAP about trivial error conditions 
1407      * such as wrong arity, bad command name and so forth. */ 
1408     c
->cmd 
= c
->lastcmd 
= lookupCommand(c
->argv
[0]->ptr
); 
1410         addReplyErrorFormat(c
,"unknown command '%s'", 
1411             (char*)c
->argv
[0]->ptr
); 
1413     } else if ((c
->cmd
->arity 
> 0 && c
->cmd
->arity 
!= c
->argc
) || 
1414                (c
->argc 
< -c
->cmd
->arity
)) { 
1415         addReplyErrorFormat(c
,"wrong number of arguments for '%s' command", 
1420     /* Check if the user is authenticated */ 
1421     if (server
.requirepass 
&& !c
->authenticated 
&& c
->cmd
->proc 
!= authCommand
) 
1423         addReplyError(c
,"operation not permitted"); 
1427     /* Handle the maxmemory directive. 
1429      * First we try to free some memory if possible (if there are volatile 
1430      * keys in the dataset). If there are not the only thing we can do 
1431      * is returning an error. */ 
1432     if (server
.maxmemory
) { 
1433         int retval 
= freeMemoryIfNeeded(); 
1434         if ((c
->cmd
->flags 
& REDIS_CMD_DENYOOM
) && retval 
== REDIS_ERR
) { 
1436                 "command not allowed when used memory > 'maxmemory'"); 
1441     /* Don't accept write commands if there are problems persisting on disk. */ 
1442     if (server
.stop_writes_on_bgsave_err 
&& 
1443         server
.saveparamslen 
> 0 
1444         && server
.lastbgsave_status 
== REDIS_ERR 
&& 
1445         c
->cmd
->flags 
& REDIS_CMD_WRITE
) 
1447         addReply(c
, shared
.bgsaveerr
); 
1451     /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ 
1452     if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0) 
1454         c
->cmd
->proc 
!= subscribeCommand 
&& 
1455         c
->cmd
->proc 
!= unsubscribeCommand 
&& 
1456         c
->cmd
->proc 
!= psubscribeCommand 
&& 
1457         c
->cmd
->proc 
!= punsubscribeCommand
) { 
1458         addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context"); 
1462     /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and 
1463      * we are a slave with a broken link with master. */ 
1464     if (server
.masterhost 
&& server
.repl_state 
!= REDIS_REPL_CONNECTED 
&& 
1465         server
.repl_serve_stale_data 
== 0 && 
1466         c
->cmd
->proc 
!= infoCommand 
&& c
->cmd
->proc 
!= slaveofCommand
) 
1469             "link with MASTER is down and slave-serve-stale-data is set to no"); 
1473     /* Loading DB? Return an error if the command is not INFO */ 
1474     if (server
.loading 
&& c
->cmd
->proc 
!= infoCommand
) { 
1475         addReply(c
, shared
.loadingerr
); 
1479     /* Lua script too slow? Only allow SHUTDOWN NOSAVE and SCRIPT KILL. */ 
1480     if (server
.lua_timedout 
&& 
1481         !(c
->cmd
->proc 
!= shutdownCommand 
&& 
1483           tolower(((char*)c
->argv
[1]->ptr
)[0]) == 'n') && 
1484         !(c
->cmd
->proc 
== scriptCommand 
&& 
1486           tolower(((char*)c
->argv
[1]->ptr
)[0]) == 'k')) 
1488         addReply(c
, shared
.slowscripterr
); 
1492     /* Exec the command */ 
1493     if (c
->flags 
& REDIS_MULTI 
&& 
1494         c
->cmd
->proc 
!= execCommand 
&& c
->cmd
->proc 
!= discardCommand 
&& 
1495         c
->cmd
->proc 
!= multiCommand 
&& c
->cmd
->proc 
!= watchCommand
) 
1497         queueMultiCommand(c
); 
1498         addReply(c
,shared
.queued
); 
1500         call(c
,REDIS_CALL_FULL
); 
1505 /*================================== Shutdown =============================== */ 
1507 int prepareForShutdown(int flags
) { 
1508     int save 
= flags 
& REDIS_SHUTDOWN_SAVE
; 
1509     int nosave 
= flags 
& REDIS_SHUTDOWN_NOSAVE
; 
1511     redisLog(REDIS_WARNING
,"User requested shutdown..."); 
1512     /* Kill the saving child if there is a background saving in progress. 
1513        We want to avoid race conditions, for instance our saving child may 
1514        overwrite the synchronous saving did by SHUTDOWN. */ 
1515     if (server
.rdb_child_pid 
!= -1) { 
1516         redisLog(REDIS_WARNING
,"There is a child saving an .rdb. Killing it!"); 
1517         kill(server
.rdb_child_pid
,SIGKILL
); 
1518         rdbRemoveTempFile(server
.rdb_child_pid
); 
1520     if (server
.aof_state 
!= REDIS_AOF_OFF
) { 
1521         /* Kill the AOF saving child as the AOF we already have may be longer 
1522          * but contains the full dataset anyway. */ 
1523         if (server
.aof_child_pid 
!= -1) { 
1524             redisLog(REDIS_WARNING
, 
1525                 "There is a child rewriting the AOF. Killing it!"); 
1526             kill(server
.aof_child_pid
,SIGKILL
); 
1528         /* Append only file: fsync() the AOF and exit */ 
1529         redisLog(REDIS_NOTICE
,"Calling fsync() on the AOF file."); 
1530         aof_fsync(server
.aof_fd
); 
1532     if ((server
.saveparamslen 
> 0 && !nosave
) || save
) { 
1533         redisLog(REDIS_NOTICE
,"Saving the final RDB snapshot before exiting."); 
1534         /* Snapshotting. Perform a SYNC SAVE and exit */ 
1535         if (rdbSave(server
.rdb_filename
) != REDIS_OK
) { 
1536             /* Ooops.. error saving! The best we can do is to continue 
1537              * operating. Note that if there was a background saving process, 
1538              * in the next cron() Redis will be notified that the background 
1539              * saving aborted, handling special stuff like slaves pending for 
1540              * synchronization... */ 
1541             redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit."); 
1545     if (server
.daemonize
) { 
1546         redisLog(REDIS_NOTICE
,"Removing the pid file."); 
1547         unlink(server
.pidfile
); 
1549     /* Close the listening sockets. Apparently this allows faster restarts. */ 
1550     if (server
.ipfd 
!= -1) close(server
.ipfd
); 
1551     if (server
.sofd 
!= -1) close(server
.sofd
); 
1552     if (server
.unixsocket
) { 
1553         redisLog(REDIS_NOTICE
,"Removing the unix socket file."); 
1554         unlink(server
.unixsocket
); /* don't care if this fails */ 
1557     redisLog(REDIS_WARNING
,"Redis is now ready to exit, bye bye..."); 
1561 /*================================== Commands =============================== */ 
1563 void authCommand(redisClient 
*c
) { 
1564     if (!server
.requirepass
) { 
1565         addReplyError(c
,"Client sent AUTH, but no password is set"); 
1566     } else if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) { 
1567       c
->authenticated 
= 1; 
1568       addReply(c
,shared
.ok
); 
1570       c
->authenticated 
= 0; 
1571       addReplyError(c
,"invalid password"); 
1575 void pingCommand(redisClient 
*c
) { 
1576     addReply(c
,shared
.pong
); 
1579 void echoCommand(redisClient 
*c
) { 
1580     addReplyBulk(c
,c
->argv
[1]); 
1583 void timeCommand(redisClient 
*c
) { 
1586     /* gettimeofday() can only fail if &tv is a bad addresss so we 
1587      * don't check for errors. */ 
1588     gettimeofday(&tv
,NULL
); 
1589     addReplyMultiBulkLen(c
,2); 
1590     addReplyBulkLongLong(c
,tv
.tv_sec
); 
1591     addReplyBulkLongLong(c
,tv
.tv_usec
); 
1594 /* Convert an amount of bytes into a human readable string in the form 
1595  * of 100B, 2G, 100M, 4K, and so forth. */ 
1596 void bytesToHuman(char *s
, unsigned long long n
) { 
1601         sprintf(s
,"%lluB",n
); 
1603     } else if (n 
< (1024*1024)) { 
1604         d 
= (double)n
/(1024); 
1605         sprintf(s
,"%.2fK",d
); 
1606     } else if (n 
< (1024LL*1024*1024)) { 
1607         d 
= (double)n
/(1024*1024); 
1608         sprintf(s
,"%.2fM",d
); 
1609     } else if (n 
< (1024LL*1024*1024*1024)) { 
1610         d 
= (double)n
/(1024LL*1024*1024); 
1611         sprintf(s
,"%.2fG",d
); 
1615 /* Create the string returned by the INFO command. This is decoupled 
1616  * by the INFO command itself as we need to report the same information 
1617  * on memory corruption problems. */ 
1618 sds 
genRedisInfoString(char *section
) { 
1619     sds info 
= sdsempty(); 
1620     time_t uptime 
= time(NULL
)-server
.stat_starttime
; 
1622     struct rusage self_ru
, c_ru
; 
1623     unsigned long lol
, bib
; 
1624     int allsections 
= 0, defsections 
= 0; 
1628         allsections 
= strcasecmp(section
,"all") == 0; 
1629         defsections 
= strcasecmp(section
,"default") == 0; 
1632     getrusage(RUSAGE_SELF
, &self_ru
); 
1633     getrusage(RUSAGE_CHILDREN
, &c_ru
); 
1634     getClientsMaxBuffers(&lol
,&bib
); 
1637     if (allsections 
|| defsections 
|| !strcasecmp(section
,"server")) { 
1638         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1639         info 
= sdscatprintf(info
, 
1641             "redis_version:%s\r\n" 
1642             "redis_git_sha1:%s\r\n" 
1643             "redis_git_dirty:%d\r\n" 
1645             "multiplexing_api:%s\r\n" 
1646             "gcc_version:%d.%d.%d\r\n" 
1647             "process_id:%ld\r\n" 
1650             "uptime_in_seconds:%ld\r\n" 
1651             "uptime_in_days:%ld\r\n" 
1652             "lru_clock:%ld\r\n", 
1655             strtol(redisGitDirty(),NULL
,10) > 0, 
1659             __GNUC__
,__GNUC_MINOR__
,__GNUC_PATCHLEVEL__
, 
1668             (unsigned long) server
.lruclock
); 
1672     if (allsections 
|| defsections 
|| !strcasecmp(section
,"clients")) { 
1673         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1674         info 
= sdscatprintf(info
, 
1676             "connected_clients:%lu\r\n" 
1677             "client_longest_output_list:%lu\r\n" 
1678             "client_biggest_input_buf:%lu\r\n" 
1679             "blocked_clients:%d\r\n", 
1680             listLength(server
.clients
)-listLength(server
.slaves
), 
1682             server
.bpop_blocked_clients
); 
1686     if (allsections 
|| defsections 
|| !strcasecmp(section
,"memory")) { 
1690         bytesToHuman(hmem
,zmalloc_used_memory()); 
1691         bytesToHuman(peak_hmem
,server
.stat_peak_memory
); 
1692         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1693         info 
= sdscatprintf(info
, 
1695             "used_memory:%zu\r\n" 
1696             "used_memory_human:%s\r\n" 
1697             "used_memory_rss:%zu\r\n" 
1698             "used_memory_peak:%zu\r\n" 
1699             "used_memory_peak_human:%s\r\n" 
1700             "used_memory_lua:%lld\r\n" 
1701             "mem_fragmentation_ratio:%.2f\r\n" 
1702             "mem_allocator:%s\r\n", 
1703             zmalloc_used_memory(), 
1706             server
.stat_peak_memory
, 
1708             ((long long)lua_gc(server
.lua
,LUA_GCCOUNT
,0))*1024LL, 
1709             zmalloc_get_fragmentation_ratio(), 
1715     if (allsections 
|| defsections 
|| !strcasecmp(section
,"persistence")) { 
1716         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1717         info 
= sdscatprintf(info
, 
1720             "aof_enabled:%d\r\n" 
1721             "changes_since_last_save:%lld\r\n" 
1722             "bgsave_in_progress:%d\r\n" 
1723             "last_save_time:%ld\r\n" 
1724             "last_bgsave_status:%s\r\n" 
1725             "bgrewriteaof_in_progress:%d\r\n", 
1727             server
.aof_state 
!= REDIS_AOF_OFF
, 
1729             server
.rdb_child_pid 
!= -1, 
1731             server
.lastbgsave_status 
== REDIS_OK 
? "ok" : "err", 
1732             server
.aof_child_pid 
!= -1); 
1734         if (server
.aof_state 
!= REDIS_AOF_OFF
) { 
1735             info 
= sdscatprintf(info
, 
1736                 "aof_current_size:%lld\r\n" 
1737                 "aof_base_size:%lld\r\n" 
1738                 "aof_pending_rewrite:%d\r\n" 
1739                 "aof_buffer_length:%zu\r\n" 
1740                 "aof_pending_bio_fsync:%llu\r\n", 
1741                 (long long) server
.aof_current_size
, 
1742                 (long long) server
.aof_rewrite_base_size
, 
1743                 server
.aof_rewrite_scheduled
, 
1744                 sdslen(server
.aof_buf
), 
1745                 bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
)); 
1748         if (server
.loading
) { 
1750             time_t eta
, elapsed
; 
1751             off_t remaining_bytes 
= server
.loading_total_bytes
- 
1752                                     server
.loading_loaded_bytes
; 
1754             perc 
= ((double)server
.loading_loaded_bytes 
/ 
1755                    server
.loading_total_bytes
) * 100; 
1757             elapsed 
= time(NULL
)-server
.loading_start_time
; 
1759                 eta 
= 1; /* A fake 1 second figure if we don't have 
1762                 eta 
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
; 
1765             info 
= sdscatprintf(info
, 
1766                 "loading_start_time:%ld\r\n" 
1767                 "loading_total_bytes:%llu\r\n" 
1768                 "loading_loaded_bytes:%llu\r\n" 
1769                 "loading_loaded_perc:%.2f\r\n" 
1770                 "loading_eta_seconds:%ld\r\n" 
1771                 ,(unsigned long) server
.loading_start_time
, 
1772                 (unsigned long long) server
.loading_total_bytes
, 
1773                 (unsigned long long) server
.loading_loaded_bytes
, 
1781     if (allsections 
|| defsections 
|| !strcasecmp(section
,"stats")) { 
1782         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1783         info 
= sdscatprintf(info
, 
1785             "total_connections_received:%lld\r\n" 
1786             "total_commands_processed:%lld\r\n" 
1787             "instantaneous_ops_per_sec:%lld\r\n" 
1788             "rejected_connections:%lld\r\n" 
1789             "expired_keys:%lld\r\n" 
1790             "evicted_keys:%lld\r\n" 
1791             "keyspace_hits:%lld\r\n" 
1792             "keyspace_misses:%lld\r\n" 
1793             "pubsub_channels:%ld\r\n" 
1794             "pubsub_patterns:%lu\r\n" 
1795             "latest_fork_usec:%lld\r\n", 
1796             server
.stat_numconnections
, 
1797             server
.stat_numcommands
, 
1798             getOperationsPerSecond(), 
1799             server
.stat_rejected_conn
, 
1800             server
.stat_expiredkeys
, 
1801             server
.stat_evictedkeys
, 
1802             server
.stat_keyspace_hits
, 
1803             server
.stat_keyspace_misses
, 
1804             dictSize(server
.pubsub_channels
), 
1805             listLength(server
.pubsub_patterns
), 
1806             server
.stat_fork_time
); 
1810     if (allsections 
|| defsections 
|| !strcasecmp(section
,"replication")) { 
1811         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1812         info 
= sdscatprintf(info
, 
1815             server
.masterhost 
== NULL 
? "master" : "slave"); 
1816         if (server
.masterhost
) { 
1817             info 
= sdscatprintf(info
, 
1818                 "master_host:%s\r\n" 
1819                 "master_port:%d\r\n" 
1820                 "master_link_status:%s\r\n" 
1821                 "master_last_io_seconds_ago:%d\r\n" 
1822                 "master_sync_in_progress:%d\r\n" 
1825                 (server
.repl_state 
== REDIS_REPL_CONNECTED
) ? 
1828                 ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1, 
1829                 server
.repl_state 
== REDIS_REPL_TRANSFER
 
1832             if (server
.repl_state 
== REDIS_REPL_TRANSFER
) { 
1833                 info 
= sdscatprintf(info
, 
1834                     "master_sync_left_bytes:%ld\r\n" 
1835                     "master_sync_last_io_seconds_ago:%d\r\n" 
1836                     ,(long)server
.repl_transfer_left
, 
1837                     (int)(time(NULL
)-server
.repl_transfer_lastio
) 
1841             if (server
.repl_state 
!= REDIS_REPL_CONNECTED
) { 
1842                 info 
= sdscatprintf(info
, 
1843                     "master_link_down_since_seconds:%ld\r\n", 
1844                     (long)time(NULL
)-server
.repl_down_since
); 
1847         info 
= sdscatprintf(info
, 
1848             "connected_slaves:%lu\r\n", 
1849             listLength(server
.slaves
)); 
1850         if (listLength(server
.slaves
)) { 
1855             listRewind(server
.slaves
,&li
); 
1856             while((ln 
= listNext(&li
))) { 
1857                 redisClient 
*slave 
= listNodeValue(ln
); 
1862                 if (anetPeerToString(slave
->fd
,ip
,&port
) == -1) continue; 
1863                 switch(slave
->replstate
) { 
1864                 case REDIS_REPL_WAIT_BGSAVE_START
: 
1865                 case REDIS_REPL_WAIT_BGSAVE_END
: 
1866                     state 
= "wait_bgsave"; 
1868                 case REDIS_REPL_SEND_BULK
: 
1869                     state 
= "send_bulk"; 
1871                 case REDIS_REPL_ONLINE
: 
1875                 if (state 
== NULL
) continue; 
1876                 info 
= sdscatprintf(info
,"slave%d:%s,%d,%s\r\n", 
1877                     slaveid
,ip
,port
,state
); 
1884     if (allsections 
|| defsections 
|| !strcasecmp(section
,"cpu")) { 
1885         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1886         info 
= sdscatprintf(info
, 
1888         "used_cpu_sys:%.2f\r\n" 
1889         "used_cpu_user:%.2f\r\n" 
1890         "used_cpu_sys_children:%.2f\r\n" 
1891         "used_cpu_user_children:%.2f\r\n", 
1892         (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000, 
1893         (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000, 
1894         (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000, 
1895         (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000); 
1899     if (allsections 
|| !strcasecmp(section
,"commandstats")) { 
1900         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1901         info 
= sdscatprintf(info
, "# Commandstats\r\n"); 
1902         numcommands 
= sizeof(redisCommandTable
)/sizeof(struct redisCommand
); 
1903         for (j 
= 0; j 
< numcommands
; j
++) { 
1904             struct redisCommand 
*c 
= redisCommandTable
+j
; 
1906             if (!c
->calls
) continue; 
1907             info 
= sdscatprintf(info
, 
1908                 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n", 
1909                 c
->name
, c
->calls
, c
->microseconds
, 
1910                 (c
->calls 
== 0) ? 0 : ((float)c
->microseconds
/c
->calls
)); 
1915     if (allsections 
|| defsections 
|| !strcasecmp(section
,"keyspace")) { 
1916         if (sections
++) info 
= sdscat(info
,"\r\n"); 
1917         info 
= sdscatprintf(info
, "# Keyspace\r\n"); 
1918         for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1919             long long keys
, vkeys
; 
1921             keys 
= dictSize(server
.db
[j
].dict
); 
1922             vkeys 
= dictSize(server
.db
[j
].expires
); 
1923             if (keys 
|| vkeys
) { 
1924                 info 
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n", 
1932 void infoCommand(redisClient 
*c
) { 
1933     char *section 
= c
->argc 
== 2 ? c
->argv
[1]->ptr 
: "default"; 
1936         addReply(c
,shared
.syntaxerr
); 
1939     sds info 
= genRedisInfoString(section
); 
1940     addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n", 
1941         (unsigned long)sdslen(info
))); 
1942     addReplySds(c
,info
); 
1943     addReply(c
,shared
.crlf
); 
1946 void monitorCommand(redisClient 
*c
) { 
1947     /* ignore MONITOR if aleady slave or in monitor mode */ 
1948     if (c
->flags 
& REDIS_SLAVE
) return; 
1950     c
->flags 
|= (REDIS_SLAVE
|REDIS_MONITOR
); 
1952     listAddNodeTail(server
.monitors
,c
); 
1953     addReply(c
,shared
.ok
); 
1956 /* ============================ Maxmemory directive  ======================== */ 
1958 /* This function gets called when 'maxmemory' is set on the config file to limit 
1959  * the max memory used by the server, before processing a command. 
1961  * The goal of the function is to free enough memory to keep Redis under the 
1962  * configured memory limit. 
1964  * The function starts calculating how many bytes should be freed to keep 
1965  * Redis under the limit, and enters a loop selecting the best keys to 
1966  * evict accordingly to the configured policy. 
1968  * If all the bytes needed to return back under the limit were freed the 
1969  * function returns REDIS_OK, otherwise REDIS_ERR is returned, and the caller 
1970  * should block the execution of commands that will result in more memory 
1971  * used by the server. 
1973 int freeMemoryIfNeeded(void) { 
1974     size_t mem_used
, mem_tofree
, mem_freed
; 
1975     int slaves 
= listLength(server
.slaves
); 
1977     /* Remove the size of slaves output buffers and AOF buffer from the 
1978      * count of used memory. */ 
1979     mem_used 
= zmalloc_used_memory(); 
1984         listRewind(server
.slaves
,&li
); 
1985         while((ln 
= listNext(&li
))) { 
1986             redisClient 
*slave 
= listNodeValue(ln
); 
1987             unsigned long obuf_bytes 
= getClientOutputBufferMemoryUsage(slave
); 
1988             if (obuf_bytes 
> mem_used
) 
1991                 mem_used 
-= obuf_bytes
; 
1994     if (server
.aof_state 
!= REDIS_AOF_OFF
) { 
1995         mem_used 
-= sdslen(server
.aof_buf
); 
1996         mem_used 
-= sdslen(server
.aof_rewrite_buf
); 
1999     /* Check if we are over the memory limit. */ 
2000     if (mem_used 
<= server
.maxmemory
) return REDIS_OK
; 
2002     if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_NO_EVICTION
) 
2003         return REDIS_ERR
; /* We need to free memory, but policy forbids. */ 
2005     /* Compute how much memory we need to free. */ 
2006     mem_tofree 
= mem_used 
- server
.maxmemory
; 
2008     while (mem_freed 
< mem_tofree
) { 
2009         int j
, k
, keys_freed 
= 0; 
2011         for (j 
= 0; j 
< server
.dbnum
; j
++) { 
2012             long bestval 
= 0; /* just to prevent warning */ 
2014             struct dictEntry 
*de
; 
2015             redisDb 
*db 
= server
.db
+j
; 
2018             if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_LRU 
|| 
2019                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
) 
2021                 dict 
= server
.db
[j
].dict
; 
2023                 dict 
= server
.db
[j
].expires
; 
2025             if (dictSize(dict
) == 0) continue; 
2027             /* volatile-random and allkeys-random policy */ 
2028             if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_RANDOM 
|| 
2029                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_RANDOM
) 
2031                 de 
= dictGetRandomKey(dict
); 
2032                 bestkey 
= dictGetKey(de
); 
2035             /* volatile-lru and allkeys-lru policy */ 
2036             else if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_LRU 
|| 
2037                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_LRU
) 
2039                 for (k 
= 0; k 
< server
.maxmemory_samples
; k
++) { 
2044                     de 
= dictGetRandomKey(dict
); 
2045                     thiskey 
= dictGetKey(de
); 
2046                     /* When policy is volatile-lru we need an additonal lookup 
2047                      * to locate the real key, as dict is set to db->expires. */ 
2048                     if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_LRU
) 
2049                         de 
= dictFind(db
->dict
, thiskey
); 
2051                     thisval 
= estimateObjectIdleTime(o
); 
2053                     /* Higher idle time is better candidate for deletion */ 
2054                     if (bestkey 
== NULL 
|| thisval 
> bestval
) { 
2062             else if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_TTL
) { 
2063                 for (k 
= 0; k 
< server
.maxmemory_samples
; k
++) { 
2067                     de 
= dictGetRandomKey(dict
); 
2068                     thiskey 
= dictGetKey(de
); 
2069                     thisval 
= (long) dictGetVal(de
); 
2071                     /* Expire sooner (minor expire unix timestamp) is better 
2072                      * candidate for deletion */ 
2073                     if (bestkey 
== NULL 
|| thisval 
< bestval
) { 
2080             /* Finally remove the selected key. */ 
2084                 robj 
*keyobj 
= createStringObject(bestkey
,sdslen(bestkey
)); 
2085                 propagateExpire(db
,keyobj
); 
2086                 /* We compute the amount of memory freed by dbDelete() alone. 
2087                  * It is possible that actually the memory needed to propagate 
2088                  * the DEL in AOF and replication link is greater than the one 
2089                  * we are freeing removing the key, but we can't account for 
2090                  * that otherwise we would never exit the loop. 
2092                  * AOF and Output buffer memory will be freed eventually so 
2093                  * we only care about memory used by the key space. */ 
2094                 delta 
= (long long) zmalloc_used_memory(); 
2095                 dbDelete(db
,keyobj
); 
2096                 delta 
-= (long long) zmalloc_used_memory(); 
2098                 server
.stat_evictedkeys
++; 
2099                 decrRefCount(keyobj
); 
2102                 /* When the memory to free starts to be big enough, we may 
2103                  * start spending so much time here that is impossible to 
2104                  * deliver data to the slaves fast enough, so we force the 
2105                  * transmission here inside the loop. */ 
2106                 if (slaves
) flushSlavesOutputBuffers(); 
2109         if (!keys_freed
) return REDIS_ERR
; /* nothing to free... */ 
2114 /* =================================== Main! ================================ */ 
2117 int linuxOvercommitMemoryValue(void) { 
2118     FILE *fp 
= fopen("/proc/sys/vm/overcommit_memory","r"); 
2122     if (fgets(buf
,64,fp
) == NULL
) { 
2131 void linuxOvercommitMemoryWarning(void) { 
2132     if (linuxOvercommitMemoryValue() == 0) { 
2133         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."); 
2136 #endif /* __linux__ */ 
2138 void createPidFile(void) { 
2139     /* Try to write the pid file in a best-effort way. */ 
2140     FILE *fp 
= fopen(server
.pidfile
,"w"); 
2142         fprintf(fp
,"%d\n",(int)getpid()); 
2147 void daemonize(void) { 
2150     if (fork() != 0) exit(0); /* parent exits */ 
2151     setsid(); /* create a new session */ 
2153     /* Every output goes to /dev/null. If Redis is daemonized but 
2154      * the 'logfile' is set to 'stdout' in the configuration file 
2155      * it will not log at all. */ 
2156     if ((fd 
= open("/dev/null", O_RDWR
, 0)) != -1) { 
2157         dup2(fd
, STDIN_FILENO
); 
2158         dup2(fd
, STDOUT_FILENO
); 
2159         dup2(fd
, STDERR_FILENO
); 
2160         if (fd 
> STDERR_FILENO
) close(fd
); 
2165     printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
, 
2166         redisGitSHA1(), atoi(redisGitDirty()) > 0); 
2171     fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf] [options]\n"); 
2172     fprintf(stderr
,"       ./redis-server - (read config from stdin)\n"); 
2173     fprintf(stderr
,"       ./redis-server -v or --version\n"); 
2174     fprintf(stderr
,"       ./redis-server -h or --help\n\n"); 
2175     fprintf(stderr
,"Examples:\n"); 
2176     fprintf(stderr
,"       ./redis-server (run the server with default conf)\n"); 
2177     fprintf(stderr
,"       ./redis-server /etc/redis/6379.conf\n"); 
2178     fprintf(stderr
,"       ./redis-server --port 7777\n"); 
2179     fprintf(stderr
,"       ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n"); 
2180     fprintf(stderr
,"       ./redis-server /etc/myredis.conf --loglevel verbose\n"); 
2184 void redisAsciiArt(void) { 
2185 #include "asciilogo.h" 
2186     char *buf 
= zmalloc(1024*16); 
2188     snprintf(buf
,1024*16,ascii_logo
, 
2191         strtol(redisGitDirty(),NULL
,10) > 0, 
2192         (sizeof(long) == 8) ? "64" : "32", 
2197     redisLogRaw(REDIS_NOTICE
|REDIS_LOG_RAW
,buf
); 
2201 static void sigtermHandler(int sig
) { 
2204     redisLog(REDIS_WARNING
,"Received SIGTERM, scheduling shutdown..."); 
2205     server
.shutdown_asap 
= 1; 
2208 void setupSignalHandlers(void) { 
2209     struct sigaction act
; 
2211     /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. 
2212      * Otherwise, sa_handler is used. */ 
2213     sigemptyset(&act
.sa_mask
); 
2214     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND
; 
2215     act
.sa_handler 
= sigtermHandler
; 
2216     sigaction(SIGTERM
, &act
, NULL
); 
2218 #ifdef HAVE_BACKTRACE 
2219     sigemptyset(&act
.sa_mask
); 
2220     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND 
| SA_SIGINFO
; 
2221     act
.sa_sigaction 
= sigsegvHandler
; 
2222     sigaction(SIGSEGV
, &act
, NULL
); 
2223     sigaction(SIGBUS
, &act
, NULL
); 
2224     sigaction(SIGFPE
, &act
, NULL
); 
2225     sigaction(SIGILL
, &act
, NULL
); 
2230 int main(int argc
, char **argv
) { 
2234     /* We need to initialize our libraries, and the server configuration. */ 
2235     zmalloc_enable_thread_safeness(); 
2236     srand(time(NULL
)^getpid()); 
2237     gettimeofday(&tv
,NULL
); 
2238     dictSetHashFunctionSeed(tv
.tv_sec
^tv
.tv_usec
^getpid()); 
2242         int j 
= 1; /* First option to parse in argv[] */ 
2243         sds options 
= sdsempty(); 
2244         char *configfile 
= NULL
; 
2246         /* Handle special options --help and --version */ 
2247         if (strcmp(argv
[1], "-v") == 0 || 
2248             strcmp(argv
[1], "--version") == 0) version(); 
2249         if (strcmp(argv
[1], "--help") == 0 || 
2250             strcmp(argv
[1], "-h") == 0) usage(); 
2251         /* First argument is the config file name? */ 
2252         if (argv
[j
][0] != '-' || argv
[j
][1] != '-') 
2253             configfile 
= argv
[j
++]; 
2254         /* All the other options are parsed and conceptually appended to the 
2255          * configuration file. For instance --port 6380 will generate the 
2256          * string "port 6380\n" to be parsed after the actual file name 
2257          * is parsed, if any. */ 
2259             if (argv
[j
][0] == '-' && argv
[j
][1] == '-') { 
2261                 if (sdslen(options
)) options 
= sdscat(options
,"\n"); 
2262                 options 
= sdscat(options
,argv
[j
]+2); 
2263                 options 
= sdscat(options
," "); 
2265                 /* Option argument */ 
2266                 options 
= sdscatrepr(options
,argv
[j
],strlen(argv
[j
])); 
2267                 options 
= sdscat(options
," "); 
2271         resetServerSaveParams(); 
2272         loadServerConfig(configfile
,options
); 
2275         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'"); 
2277     if (server
.daemonize
) daemonize(); 
2279     if (server
.daemonize
) createPidFile(); 
2281     redisLog(REDIS_WARNING
,"Server started, Redis version " REDIS_VERSION
); 
2283     linuxOvercommitMemoryWarning(); 
2286     if (server
.aof_state 
== REDIS_AOF_ON
) { 
2287         if (loadAppendOnlyFile(server
.aof_filename
) == REDIS_OK
) 
2288             redisLog(REDIS_NOTICE
,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start
)/1000000); 
2290         if (rdbLoad(server
.rdb_filename
) == REDIS_OK
) { 
2291             redisLog(REDIS_NOTICE
,"DB loaded from disk: %.3f seconds", 
2292                 (float)(ustime()-start
)/1000000); 
2293         } else if (errno 
!= ENOENT
) { 
2294             redisLog(REDIS_WARNING
,"Fatal error loading the DB. Exiting."); 
2298     if (server
.ipfd 
> 0) 
2299         redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
); 
2300     if (server
.sofd 
> 0) 
2301         redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
); 
2302     aeSetBeforeSleepProc(server
.el
,beforeSleep
); 
2304     aeDeleteEventLoop(server
.el
);