2  * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> 
   5  * Redistribution and use in source and binary forms, with or without 
   6  * modification, are permitted provided that the following conditions are met: 
   8  *   * Redistributions of source code must retain the above copyright notice, 
   9  *     this list of conditions and the following disclaimer. 
  10  *   * Redistributions in binary form must reproduce the above copyright 
  11  *     notice, this list of conditions and the following disclaimer in the 
  12  *     documentation and/or other materials provided with the distribution. 
  13  *   * Neither the name of Redis nor the names of its contributors may be used 
  14  *     to endorse or promote products derived from this software without 
  15  *     specific prior written permission. 
  17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
  19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
  20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
  21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
  24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
  25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
  26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  27  * POSSIBILITY OF SUCH DAMAGE. 
  35 #endif /* HAVE_BACKTRACE */ 
  44 #include <arpa/inet.h> 
  48 #include <sys/resource.h> 
  54 #include <sys/resource.h> 
  56 /* Our shared "common" objects */ 
  58 struct sharedObjectsStruct shared
; 
  60 /* Global vars that are actally used as constants. The following double 
  61  * values are used for double on-disk serialization, and are initialized 
  62  * at runtime to avoid strange compiler optimizations. */ 
  64 double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
; 
  66 /*================================= Globals ================================= */ 
  69 struct redisServer server
; /* server global state */ 
  70 struct redisCommand 
*commandTable
; 
  71 struct redisCommand readonlyCommandTable
[] = { 
  72     {"get",getCommand
,2,0,NULL
,1,1,1}, 
  73     {"set",setCommand
,3,REDIS_CMD_DENYOOM
,NULL
,0,0,0}, 
  74     {"setnx",setnxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,0,0,0}, 
  75     {"setex",setexCommand
,4,REDIS_CMD_DENYOOM
,NULL
,0,0,0}, 
  76     {"append",appendCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  77     {"substr",substrCommand
,4,0,NULL
,1,1,1}, 
  78     {"strlen",strlenCommand
,2,0,NULL
,1,1,1}, 
  79     {"del",delCommand
,-2,0,NULL
,0,0,0}, 
  80     {"exists",existsCommand
,2,0,NULL
,1,1,1}, 
  81     {"setbit",setbitCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  82     {"getbit",getbitCommand
,3,0,NULL
,1,1,1}, 
  83     {"incr",incrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  84     {"decr",decrCommand
,2,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  85     {"mget",mgetCommand
,-2,0,NULL
,1,-1,1}, 
  86     {"rpush",rpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  87     {"lpush",lpushCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  88     {"rpushx",rpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  89     {"lpushx",lpushxCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  90     {"linsert",linsertCommand
,5,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  91     {"rpop",rpopCommand
,2,0,NULL
,1,1,1}, 
  92     {"lpop",lpopCommand
,2,0,NULL
,1,1,1}, 
  93     {"brpop",brpopCommand
,-3,0,NULL
,1,1,1}, 
  94     {"blpop",blpopCommand
,-3,0,NULL
,1,1,1}, 
  95     {"llen",llenCommand
,2,0,NULL
,1,1,1}, 
  96     {"lindex",lindexCommand
,3,0,NULL
,1,1,1}, 
  97     {"lset",lsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
  98     {"lrange",lrangeCommand
,4,0,NULL
,1,1,1}, 
  99     {"ltrim",ltrimCommand
,4,0,NULL
,1,1,1}, 
 100     {"lrem",lremCommand
,4,0,NULL
,1,1,1}, 
 101     {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,2,1}, 
 102     {"sadd",saddCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 103     {"srem",sremCommand
,3,0,NULL
,1,1,1}, 
 104     {"smove",smoveCommand
,4,0,NULL
,1,2,1}, 
 105     {"sismember",sismemberCommand
,3,0,NULL
,1,1,1}, 
 106     {"scard",scardCommand
,2,0,NULL
,1,1,1}, 
 107     {"spop",spopCommand
,2,0,NULL
,1,1,1}, 
 108     {"srandmember",srandmemberCommand
,2,0,NULL
,1,1,1}, 
 109     {"sinter",sinterCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1}, 
 110     {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1}, 
 111     {"sunion",sunionCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1}, 
 112     {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1}, 
 113     {"sdiff",sdiffCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,-1,1}, 
 114     {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,2,-1,1}, 
 115     {"smembers",sinterCommand
,2,0,NULL
,1,1,1}, 
 116     {"zadd",zaddCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 117     {"zincrby",zincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 118     {"zrem",zremCommand
,3,0,NULL
,1,1,1}, 
 119     {"zremrangebyscore",zremrangebyscoreCommand
,4,0,NULL
,1,1,1}, 
 120     {"zremrangebyrank",zremrangebyrankCommand
,4,0,NULL
,1,1,1}, 
 121     {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0}, 
 122     {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0}, 
 123     {"zrange",zrangeCommand
,-4,0,NULL
,1,1,1}, 
 124     {"zrangebyscore",zrangebyscoreCommand
,-4,0,NULL
,1,1,1}, 
 125     {"zrevrangebyscore",zrevrangebyscoreCommand
,-4,0,NULL
,1,1,1}, 
 126     {"zcount",zcountCommand
,4,0,NULL
,1,1,1}, 
 127     {"zrevrange",zrevrangeCommand
,-4,0,NULL
,1,1,1}, 
 128     {"zcard",zcardCommand
,2,0,NULL
,1,1,1}, 
 129     {"zscore",zscoreCommand
,3,0,NULL
,1,1,1}, 
 130     {"zrank",zrankCommand
,3,0,NULL
,1,1,1}, 
 131     {"zrevrank",zrevrankCommand
,3,0,NULL
,1,1,1}, 
 132     {"hset",hsetCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 133     {"hsetnx",hsetnxCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 134     {"hget",hgetCommand
,3,0,NULL
,1,1,1}, 
 135     {"hmset",hmsetCommand
,-4,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 136     {"hmget",hmgetCommand
,-3,0,NULL
,1,1,1}, 
 137     {"hincrby",hincrbyCommand
,4,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 138     {"hdel",hdelCommand
,3,0,NULL
,1,1,1}, 
 139     {"hlen",hlenCommand
,2,0,NULL
,1,1,1}, 
 140     {"hkeys",hkeysCommand
,2,0,NULL
,1,1,1}, 
 141     {"hvals",hvalsCommand
,2,0,NULL
,1,1,1}, 
 142     {"hgetall",hgetallCommand
,2,0,NULL
,1,1,1}, 
 143     {"hexists",hexistsCommand
,3,0,NULL
,1,1,1}, 
 144     {"incrby",incrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 145     {"decrby",decrbyCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 146     {"getset",getsetCommand
,3,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 147     {"mset",msetCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2}, 
 148     {"msetnx",msetnxCommand
,-3,REDIS_CMD_DENYOOM
,NULL
,1,-1,2}, 
 149     {"randomkey",randomkeyCommand
,1,0,NULL
,0,0,0}, 
 150     {"select",selectCommand
,2,0,NULL
,0,0,0}, 
 151     {"move",moveCommand
,3,0,NULL
,1,1,1}, 
 152     {"rename",renameCommand
,3,0,NULL
,1,1,1}, 
 153     {"renamenx",renamenxCommand
,3,0,NULL
,1,1,1}, 
 154     {"expire",expireCommand
,3,0,NULL
,0,0,0}, 
 155     {"expireat",expireatCommand
,3,0,NULL
,0,0,0}, 
 156     {"keys",keysCommand
,2,0,NULL
,0,0,0}, 
 157     {"dbsize",dbsizeCommand
,1,0,NULL
,0,0,0}, 
 158     {"auth",authCommand
,2,0,NULL
,0,0,0}, 
 159     {"ping",pingCommand
,1,0,NULL
,0,0,0}, 
 160     {"echo",echoCommand
,2,0,NULL
,0,0,0}, 
 161     {"save",saveCommand
,1,0,NULL
,0,0,0}, 
 162     {"bgsave",bgsaveCommand
,1,0,NULL
,0,0,0}, 
 163     {"bgrewriteaof",bgrewriteaofCommand
,1,0,NULL
,0,0,0}, 
 164     {"shutdown",shutdownCommand
,1,0,NULL
,0,0,0}, 
 165     {"lastsave",lastsaveCommand
,1,0,NULL
,0,0,0}, 
 166     {"type",typeCommand
,2,0,NULL
,1,1,1}, 
 167     {"multi",multiCommand
,1,0,NULL
,0,0,0}, 
 168     {"exec",execCommand
,1,REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0}, 
 169     {"discard",discardCommand
,1,0,NULL
,0,0,0}, 
 170     {"sync",syncCommand
,1,0,NULL
,0,0,0}, 
 171     {"flushdb",flushdbCommand
,1,0,NULL
,0,0,0}, 
 172     {"flushall",flushallCommand
,1,0,NULL
,0,0,0}, 
 173     {"sort",sortCommand
,-2,REDIS_CMD_DENYOOM
,NULL
,1,1,1}, 
 174     {"info",infoCommand
,1,0,NULL
,0,0,0}, 
 175     {"monitor",monitorCommand
,1,0,NULL
,0,0,0}, 
 176     {"ttl",ttlCommand
,2,0,NULL
,1,1,1}, 
 177     {"persist",persistCommand
,2,0,NULL
,1,1,1}, 
 178     {"slaveof",slaveofCommand
,3,0,NULL
,0,0,0}, 
 179     {"debug",debugCommand
,-2,0,NULL
,0,0,0}, 
 180     {"config",configCommand
,-2,0,NULL
,0,0,0}, 
 181     {"subscribe",subscribeCommand
,-2,0,NULL
,0,0,0}, 
 182     {"unsubscribe",unsubscribeCommand
,-1,0,NULL
,0,0,0}, 
 183     {"psubscribe",psubscribeCommand
,-2,0,NULL
,0,0,0}, 
 184     {"punsubscribe",punsubscribeCommand
,-1,0,NULL
,0,0,0}, 
 185     {"publish",publishCommand
,3,REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0}, 
 186     {"watch",watchCommand
,-2,0,NULL
,0,0,0}, 
 187     {"unwatch",unwatchCommand
,1,0,NULL
,0,0,0} 
 190 /*============================ Utility functions ============================ */ 
 192 void redisLog(int level
, const char *fmt
, ...) { 
 199     if (level 
< server
.verbosity
) return; 
 201     fp 
= (server
.logfile 
== NULL
) ? stdout 
: fopen(server
.logfile
,"a"); 
 206     strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
)); 
 207     fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]); 
 208     vfprintf(fp
, fmt
, ap
); 
 213     if (server
.logfile
) fclose(fp
); 
 216 /* Redis generally does not try to recover from out of memory conditions 
 217  * when allocating objects or strings, it is not clear if it will be possible 
 218  * to report this condition to the client since the networking layer itself 
 219  * is based on heap allocation for send buffers, so we simply abort. 
 220  * At least the code will be simpler to read... */ 
 221 void oom(const char *msg
) { 
 222     redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
); 
 227 /*====================== Hash table type implementation  ==================== */ 
 229 /* This is an hash table type that uses the SDS dynamic strings libary as 
 230  * keys and radis objects as values (objects can hold SDS strings, 
 233 void dictVanillaFree(void *privdata
, void *val
) 
 235     DICT_NOTUSED(privdata
); 
 239 void dictListDestructor(void *privdata
, void *val
) 
 241     DICT_NOTUSED(privdata
); 
 242     listRelease((list
*)val
); 
 245 int dictSdsKeyCompare(void *privdata
, const void *key1
, 
 249     DICT_NOTUSED(privdata
); 
 251     l1 
= sdslen((sds
)key1
); 
 252     l2 
= sdslen((sds
)key2
); 
 253     if (l1 
!= l2
) return 0; 
 254     return memcmp(key1
, key2
, l1
) == 0; 
 257 /* A case insensitive version used for the command lookup table. */ 
 258 int dictSdsKeyCaseCompare(void *privdata
, const void *key1
, 
 261     DICT_NOTUSED(privdata
); 
 263     return strcasecmp(key1
, key2
) == 0; 
 266 void dictRedisObjectDestructor(void *privdata
, void *val
) 
 268     DICT_NOTUSED(privdata
); 
 270     if (val 
== NULL
) return; /* Values of swapped out keys as set to NULL */ 
 274 void dictSdsDestructor(void *privdata
, void *val
) 
 276     DICT_NOTUSED(privdata
); 
 281 int dictObjKeyCompare(void *privdata
, const void *key1
, 
 284     const robj 
*o1 
= key1
, *o2 
= key2
; 
 285     return dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 288 unsigned int dictObjHash(const void *key
) { 
 290     return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 293 unsigned int dictSdsHash(const void *key
) { 
 294     return dictGenHashFunction((unsigned char*)key
, sdslen((char*)key
)); 
 297 unsigned int dictSdsCaseHash(const void *key
) { 
 298     return dictGenCaseHashFunction((unsigned char*)key
, sdslen((char*)key
)); 
 301 int dictEncObjKeyCompare(void *privdata
, const void *key1
, 
 304     robj 
*o1 
= (robj
*) key1
, *o2 
= (robj
*) key2
; 
 307     if (o1
->encoding 
== REDIS_ENCODING_INT 
&& 
 308         o2
->encoding 
== REDIS_ENCODING_INT
) 
 309             return o1
->ptr 
== o2
->ptr
; 
 311     o1 
= getDecodedObject(o1
); 
 312     o2 
= getDecodedObject(o2
); 
 313     cmp 
= dictSdsKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 319 unsigned int dictEncObjHash(const void *key
) { 
 320     robj 
*o 
= (robj
*) key
; 
 322     if (o
->encoding 
== REDIS_ENCODING_RAW
) { 
 323         return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 325         if (o
->encoding 
== REDIS_ENCODING_INT
) { 
 329             len 
= ll2string(buf
,32,(long)o
->ptr
); 
 330             return dictGenHashFunction((unsigned char*)buf
, len
); 
 334             o 
= getDecodedObject(o
); 
 335             hash 
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 343 dictType setDictType 
= { 
 344     dictEncObjHash
,            /* hash function */ 
 347     dictEncObjKeyCompare
,      /* key compare */ 
 348     dictRedisObjectDestructor
, /* key destructor */ 
 349     NULL                       
/* val destructor */ 
 352 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ 
 353 dictType zsetDictType 
= { 
 354     dictEncObjHash
,            /* hash function */ 
 357     dictEncObjKeyCompare
,      /* key compare */ 
 358     dictRedisObjectDestructor
, /* key destructor */ 
 359     NULL                       
/* val destructor */ 
 362 /* Db->dict, keys are sds strings, vals are Redis objects. */ 
 363 dictType dbDictType 
= { 
 364     dictSdsHash
,                /* hash function */ 
 367     dictSdsKeyCompare
,          /* key compare */ 
 368     dictSdsDestructor
,          /* key destructor */ 
 369     dictRedisObjectDestructor   
/* val destructor */ 
 373 dictType keyptrDictType 
= { 
 374     dictSdsHash
,               /* hash function */ 
 377     dictSdsKeyCompare
,         /* key compare */ 
 378     NULL
,                      /* key destructor */ 
 379     NULL                       
/* val destructor */ 
 382 /* Command table. sds string -> command struct pointer. */ 
 383 dictType commandTableDictType 
= { 
 384     dictSdsCaseHash
,           /* hash function */ 
 387     dictSdsKeyCaseCompare
,     /* key compare */ 
 388     dictSdsDestructor
,         /* key destructor */ 
 389     NULL                       
/* val destructor */ 
 392 /* Hash type hash table (note that small hashes are represented with zimpaps) */ 
 393 dictType hashDictType 
= { 
 394     dictEncObjHash
,             /* hash function */ 
 397     dictEncObjKeyCompare
,       /* key compare */ 
 398     dictRedisObjectDestructor
,  /* key destructor */ 
 399     dictRedisObjectDestructor   
/* val destructor */ 
 402 /* Keylist hash table type has unencoded redis objects as keys and 
 403  * lists as values. It's used for blocking operations (BLPOP) and to 
 404  * map swapped keys to a list of clients waiting for this keys to be loaded. */ 
 405 dictType keylistDictType 
= { 
 406     dictObjHash
,                /* hash function */ 
 409     dictObjKeyCompare
,          /* key compare */ 
 410     dictRedisObjectDestructor
,  /* key destructor */ 
 411     dictListDestructor          
/* val destructor */ 
 414 int htNeedsResize(dict 
*dict
) { 
 415     long long size
, used
; 
 417     size 
= dictSlots(dict
); 
 418     used 
= dictSize(dict
); 
 419     return (size 
&& used 
&& size 
> DICT_HT_INITIAL_SIZE 
&& 
 420             (used
*100/size 
< REDIS_HT_MINFILL
)); 
 423 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL 
 424  * we resize the hash table to save memory */ 
 425 void tryResizeHashTables(void) { 
 428     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 429         if (htNeedsResize(server
.db
[j
].dict
)) 
 430             dictResize(server
.db
[j
].dict
); 
 431         if (htNeedsResize(server
.db
[j
].expires
)) 
 432             dictResize(server
.db
[j
].expires
); 
 436 /* Our hash table implementation performs rehashing incrementally while 
 437  * we write/read from the hash table. Still if the server is idle, the hash 
 438  * table will use two tables for a long time. So we try to use 1 millisecond 
 439  * of CPU time at every serverCron() loop in order to rehash some key. */ 
 440 void incrementallyRehash(void) { 
 443     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 444         if (dictIsRehashing(server
.db
[j
].dict
)) { 
 445             dictRehashMilliseconds(server
.db
[j
].dict
,1); 
 446             break; /* already used our millisecond for this loop... */ 
 451 /* This function is called once a background process of some kind terminates, 
 452  * as we want to avoid resizing the hash tables when there is a child in order 
 453  * to play well with copy-on-write (otherwise when a resize happens lots of 
 454  * memory pages are copied). The goal of this function is to update the ability 
 455  * for dict.c to resize the hash tables accordingly to the fact we have o not 
 457 void updateDictResizePolicy(void) { 
 458     if (server
.bgsavechildpid 
== -1 && server
.bgrewritechildpid 
== -1) 
 464 /* ======================= Cron: called every 100 ms ======================== */ 
 466 /* Try to expire a few timed out keys. The algorithm used is adaptive and 
 467  * will use few CPU cycles if there are few expiring keys, otherwise 
 468  * it will get more aggressive to avoid that too much memory is used by 
 469  * keys that can be removed from the keyspace. */ 
 470 void activeExpireCycle(void) { 
 473     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 475         redisDb 
*db 
= server
.db
+j
; 
 477         /* Continue to expire if at the end of the cycle more than 25% 
 478          * of the keys were expired. */ 
 480             long num 
= dictSize(db
->expires
); 
 481             time_t now 
= time(NULL
); 
 484             if (num 
> REDIS_EXPIRELOOKUPS_PER_CRON
) 
 485                 num 
= REDIS_EXPIRELOOKUPS_PER_CRON
; 
 490                 if ((de 
= dictGetRandomKey(db
->expires
)) == NULL
) break; 
 491                 t 
= (time_t) dictGetEntryVal(de
); 
 493                     sds key 
= dictGetEntryKey(de
); 
 494                     robj 
*keyobj 
= createStringObject(key
,sdslen(key
)); 
 496                     propagateExpire(db
,keyobj
); 
 498                     decrRefCount(keyobj
); 
 500                     server
.stat_expiredkeys
++; 
 503         } while (expired 
> REDIS_EXPIRELOOKUPS_PER_CRON
/4); 
 507 void updateLRUClock(void) { 
 508     server
.lruclock 
= (time(NULL
)/REDIS_LRU_CLOCK_RESOLUTION
) & 
 512 int serverCron(struct aeEventLoop 
*eventLoop
, long long id
, void *clientData
) { 
 513     int j
, loops 
= server
.cronloops
++; 
 514     REDIS_NOTUSED(eventLoop
); 
 516     REDIS_NOTUSED(clientData
); 
 518     /* We take a cached value of the unix time in the global state because 
 519      * with virtual memory and aging there is to store the current time 
 520      * in objects at every object access, and accuracy is not needed. 
 521      * To access a global var is faster than calling time(NULL) */ 
 522     server
.unixtime 
= time(NULL
); 
 523     /* We have just 22 bits per object for LRU information. 
 524      * So we use an (eventually wrapping) LRU clock with 10 seconds resolution. 
 525      * 2^22 bits with 10 seconds resoluton is more or less 1.5 years. 
 527      * Note that even if this will wrap after 1.5 years it's not a problem, 
 528      * everything will still work but just some object will appear younger 
 529      * to Redis. But for this to happen a given object should never be touched 
 532      * Note that you can change the resolution altering the 
 533      * REDIS_LRU_CLOCK_RESOLUTION define. 
 537     /* We received a SIGTERM, shutting down here in a safe way, as it is 
 538      * not ok doing so inside the signal handler. */ 
 539     if (server
.shutdown_asap
) { 
 540         if (prepareForShutdown() == REDIS_OK
) exit(0); 
 541         redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); 
 544     /* Show some info about non-empty databases */ 
 545     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 546         long long size
, used
, vkeys
; 
 548         size 
= dictSlots(server
.db
[j
].dict
); 
 549         used 
= dictSize(server
.db
[j
].dict
); 
 550         vkeys 
= dictSize(server
.db
[j
].expires
); 
 551         if (!(loops 
% 50) && (used 
|| vkeys
)) { 
 552             redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
); 
 553             /* dictPrintStats(server.dict); */ 
 557     /* We don't want to resize the hash tables while a bacground saving 
 558      * is in progress: the saving child is created using fork() that is 
 559      * implemented with a copy-on-write semantic in most modern systems, so 
 560      * if we resize the HT while there is the saving child at work actually 
 561      * a lot of memory movements in the parent will cause a lot of pages 
 563     if (server
.bgsavechildpid 
== -1 && server
.bgrewritechildpid 
== -1) { 
 564         if (!(loops 
% 10)) tryResizeHashTables(); 
 565         if (server
.activerehashing
) incrementallyRehash(); 
 568     /* Show information about connected clients */ 
 570         redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use", 
 571             listLength(server
.clients
)-listLength(server
.slaves
), 
 572             listLength(server
.slaves
), 
 573             zmalloc_used_memory()); 
 576     /* Close connections of timedout clients */ 
 577     if ((server
.maxidletime 
&& !(loops 
% 100)) || server
.blpop_blocked_clients
) 
 578         closeTimedoutClients(); 
 580     /* Check if a background saving or AOF rewrite in progress terminated */ 
 581     if (server
.bgsavechildpid 
!= -1 || server
.bgrewritechildpid 
!= -1) { 
 585         if ((pid 
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) { 
 586             if (pid 
== server
.bgsavechildpid
) { 
 587                 backgroundSaveDoneHandler(statloc
); 
 589                 backgroundRewriteDoneHandler(statloc
); 
 591             updateDictResizePolicy(); 
 594         /* If there is not a background saving in progress check if 
 595          * we have to save now */ 
 596          time_t now 
= time(NULL
); 
 597          for (j 
= 0; j 
< server
.saveparamslen
; j
++) { 
 598             struct saveparam 
*sp 
= server
.saveparams
+j
; 
 600             if (server
.dirty 
>= sp
->changes 
&& 
 601                 now
-server
.lastsave 
> sp
->seconds
) { 
 602                 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...", 
 603                     sp
->changes
, sp
->seconds
); 
 604                 rdbSaveBackground(server
.dbfilename
); 
 610     /* Expire a few keys per cycle, only if this is a master. 
 611      * On slaves we wait for DEL operations synthesized by the master 
 612      * in order to guarantee a strict consistency. */ 
 613     if (server
.masterhost 
== NULL
) activeExpireCycle(); 
 615     /* Swap a few keys on disk if we are over the memory limit and VM 
 616      * is enbled. Try to free objects from the free list first. */ 
 617     if (vmCanSwapOut()) { 
 618         while (server
.vm_enabled 
&& zmalloc_used_memory() > 
 619                 server
.vm_max_memory
) 
 621             int retval 
= (server
.vm_max_threads 
== 0) ? 
 622                         vmSwapOneObjectBlocking() : 
 623                         vmSwapOneObjectThreaded(); 
 624             if (retval 
== REDIS_ERR 
&& !(loops 
% 300) && 
 625                 zmalloc_used_memory() > 
 626                 (server
.vm_max_memory
+server
.vm_max_memory
/10)) 
 628                 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!"); 
 630             /* Note that when using threade I/O we free just one object, 
 631              * because anyway when the I/O thread in charge to swap this 
 632              * object out will finish, the handler of completed jobs 
 633              * will try to swap more objects if we are still out of memory. */ 
 634             if (retval 
== REDIS_ERR 
|| server
.vm_max_threads 
> 0) break; 
 638     /* Replication cron function -- used to reconnect to master and 
 639      * to detect transfer failures. */ 
 640     if (!(loops 
% 10)) replicationCron(); 
 645 /* This function gets called every time Redis is entering the 
 646  * main loop of the event driven library, that is, before to sleep 
 647  * for ready file descriptors. */ 
 648 void beforeSleep(struct aeEventLoop 
*eventLoop
) { 
 649     REDIS_NOTUSED(eventLoop
); 
 651     /* Awake clients that got all the swapped keys they requested */ 
 652     if (server
.vm_enabled 
&& listLength(server
.io_ready_clients
)) { 
 656         listRewind(server
.io_ready_clients
,&li
); 
 657         while((ln 
= listNext(&li
))) { 
 658             redisClient 
*c 
= ln
->value
; 
 659             struct redisCommand 
*cmd
; 
 661             /* Resume the client. */ 
 662             listDelNode(server
.io_ready_clients
,ln
); 
 663             c
->flags 
&= (~REDIS_IO_WAIT
); 
 664             server
.vm_blocked_clients
--; 
 665             aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, 
 666                 readQueryFromClient
, c
); 
 667             cmd 
= lookupCommand(c
->argv
[0]->ptr
); 
 668             redisAssert(cmd 
!= NULL
); 
 671             /* There may be more data to process in the input buffer. */ 
 672             if (c
->querybuf 
&& sdslen(c
->querybuf
) > 0) 
 673                 processInputBuffer(c
); 
 676     /* Write the AOF buffer on disk */ 
 677     flushAppendOnlyFile(); 
 680 /* =========================== Server initialization ======================== */ 
 682 void createSharedObjects(void) { 
 685     shared
.crlf 
= createObject(REDIS_STRING
,sdsnew("\r\n")); 
 686     shared
.ok 
= createObject(REDIS_STRING
,sdsnew("+OK\r\n")); 
 687     shared
.err 
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n")); 
 688     shared
.emptybulk 
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n")); 
 689     shared
.czero 
= createObject(REDIS_STRING
,sdsnew(":0\r\n")); 
 690     shared
.cone 
= createObject(REDIS_STRING
,sdsnew(":1\r\n")); 
 691     shared
.cnegone 
= createObject(REDIS_STRING
,sdsnew(":-1\r\n")); 
 692     shared
.nullbulk 
= createObject(REDIS_STRING
,sdsnew("$-1\r\n")); 
 693     shared
.nullmultibulk 
= createObject(REDIS_STRING
,sdsnew("*-1\r\n")); 
 694     shared
.emptymultibulk 
= createObject(REDIS_STRING
,sdsnew("*0\r\n")); 
 695     shared
.pong 
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n")); 
 696     shared
.queued 
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n")); 
 697     shared
.wrongtypeerr 
= createObject(REDIS_STRING
,sdsnew( 
 698         "-ERR Operation against a key holding the wrong kind of value\r\n")); 
 699     shared
.nokeyerr 
= createObject(REDIS_STRING
,sdsnew( 
 700         "-ERR no such key\r\n")); 
 701     shared
.syntaxerr 
= createObject(REDIS_STRING
,sdsnew( 
 702         "-ERR syntax error\r\n")); 
 703     shared
.sameobjecterr 
= createObject(REDIS_STRING
,sdsnew( 
 704         "-ERR source and destination objects are the same\r\n")); 
 705     shared
.outofrangeerr 
= createObject(REDIS_STRING
,sdsnew( 
 706         "-ERR index out of range\r\n")); 
 707     shared
.loadingerr 
= createObject(REDIS_STRING
,sdsnew( 
 708         "-LOADING Redis is loading the dataset in memory\r\n")); 
 709     shared
.space 
= createObject(REDIS_STRING
,sdsnew(" ")); 
 710     shared
.colon 
= createObject(REDIS_STRING
,sdsnew(":")); 
 711     shared
.plus 
= createObject(REDIS_STRING
,sdsnew("+")); 
 712     shared
.select0 
= createStringObject("select 0\r\n",10); 
 713     shared
.select1 
= createStringObject("select 1\r\n",10); 
 714     shared
.select2 
= createStringObject("select 2\r\n",10); 
 715     shared
.select3 
= createStringObject("select 3\r\n",10); 
 716     shared
.select4 
= createStringObject("select 4\r\n",10); 
 717     shared
.select5 
= createStringObject("select 5\r\n",10); 
 718     shared
.select6 
= createStringObject("select 6\r\n",10); 
 719     shared
.select7 
= createStringObject("select 7\r\n",10); 
 720     shared
.select8 
= createStringObject("select 8\r\n",10); 
 721     shared
.select9 
= createStringObject("select 9\r\n",10); 
 722     shared
.messagebulk 
= createStringObject("$7\r\nmessage\r\n",13); 
 723     shared
.pmessagebulk 
= createStringObject("$8\r\npmessage\r\n",14); 
 724     shared
.subscribebulk 
= createStringObject("$9\r\nsubscribe\r\n",15); 
 725     shared
.unsubscribebulk 
= createStringObject("$11\r\nunsubscribe\r\n",18); 
 726     shared
.psubscribebulk 
= createStringObject("$10\r\npsubscribe\r\n",17); 
 727     shared
.punsubscribebulk 
= createStringObject("$12\r\npunsubscribe\r\n",19); 
 728     shared
.mbulk3 
= createStringObject("*3\r\n",4); 
 729     shared
.mbulk4 
= createStringObject("*4\r\n",4); 
 730     for (j 
= 0; j 
< REDIS_SHARED_INTEGERS
; j
++) { 
 731         shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
); 
 732         shared
.integers
[j
]->encoding 
= REDIS_ENCODING_INT
; 
 736 void initServerConfig() { 
 737     server
.port 
= REDIS_SERVERPORT
; 
 738     server
.bindaddr 
= NULL
; 
 739     server
.unixsocket 
= NULL
; 
 742     server
.dbnum 
= REDIS_DEFAULT_DBNUM
; 
 743     server
.verbosity 
= REDIS_VERBOSE
; 
 744     server
.maxidletime 
= REDIS_MAXIDLETIME
; 
 745     server
.saveparams 
= NULL
; 
 747     server
.logfile 
= NULL
; /* NULL = log on standard output */ 
 748     server
.glueoutputbuf 
= 1; 
 749     server
.daemonize 
= 0; 
 750     server
.appendonly 
= 0; 
 751     server
.appendfsync 
= APPENDFSYNC_EVERYSEC
; 
 752     server
.no_appendfsync_on_rewrite 
= 0; 
 753     server
.lastfsync 
= time(NULL
); 
 754     server
.appendfd 
= -1; 
 755     server
.appendseldb 
= -1; /* Make sure the first time will not match */ 
 756     server
.pidfile 
= zstrdup("/var/run/redis.pid"); 
 757     server
.dbfilename 
= zstrdup("dump.rdb"); 
 758     server
.appendfilename 
= zstrdup("appendonly.aof"); 
 759     server
.requirepass 
= NULL
; 
 760     server
.rdbcompression 
= 1; 
 761     server
.activerehashing 
= 1; 
 762     server
.maxclients 
= 0; 
 763     server
.blpop_blocked_clients 
= 0; 
 764     server
.maxmemory 
= 0; 
 765     server
.maxmemory_policy 
= REDIS_MAXMEMORY_VOLATILE_LRU
; 
 766     server
.maxmemory_samples 
= 3; 
 767     server
.vm_enabled 
= 0; 
 768     server
.vm_swap_file 
= zstrdup("/tmp/redis-%p.vm"); 
 769     server
.vm_page_size 
= 256;          /* 256 bytes per page */ 
 770     server
.vm_pages 
= 1024*1024*100;    /* 104 millions of pages */ 
 771     server
.vm_max_memory 
= 1024LL*1024*1024*1; /* 1 GB of RAM */ 
 772     server
.vm_max_threads 
= 4; 
 773     server
.vm_blocked_clients 
= 0; 
 774     server
.hash_max_zipmap_entries 
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
; 
 775     server
.hash_max_zipmap_value 
= REDIS_HASH_MAX_ZIPMAP_VALUE
; 
 776     server
.list_max_ziplist_entries 
= REDIS_LIST_MAX_ZIPLIST_ENTRIES
; 
 777     server
.list_max_ziplist_value 
= REDIS_LIST_MAX_ZIPLIST_VALUE
; 
 778     server
.set_max_intset_entries 
= REDIS_SET_MAX_INTSET_ENTRIES
; 
 779     server
.shutdown_asap 
= 0; 
 782     resetServerSaveParams(); 
 784     appendServerSaveParams(60*60,1);  /* save after 1 hour and 1 change */ 
 785     appendServerSaveParams(300,100);  /* save after 5 minutes and 100 changes */ 
 786     appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ 
 787     /* Replication related */ 
 789     server
.masterauth 
= NULL
; 
 790     server
.masterhost 
= NULL
; 
 791     server
.masterport 
= 6379; 
 792     server
.master 
= NULL
; 
 793     server
.replstate 
= REDIS_REPL_NONE
; 
 794     server
.repl_serve_stale_data 
= 1; 
 796     /* Double constants initialization */ 
 798     R_PosInf 
= 1.0/R_Zero
; 
 799     R_NegInf 
= -1.0/R_Zero
; 
 800     R_Nan 
= R_Zero
/R_Zero
; 
 802     /* Command table -- we intiialize it here as it is part of the 
 803      * initial configuration, since command names may be changed via 
 804      * redis.conf using the rename-command directive. */ 
 805     server
.commands 
= dictCreate(&commandTableDictType
,NULL
); 
 806     populateCommandTable(); 
 807     server
.delCommand 
= lookupCommandByCString("del"); 
 808     server
.multiCommand 
= lookupCommandByCString("multi"); 
 814     signal(SIGHUP
, SIG_IGN
); 
 815     signal(SIGPIPE
, SIG_IGN
); 
 816     setupSigSegvAction(); 
 818     server
.mainthread 
= pthread_self(); 
 819     server
.clients 
= listCreate(); 
 820     server
.slaves 
= listCreate(); 
 821     server
.monitors 
= listCreate(); 
 822     createSharedObjects(); 
 823     server
.el 
= aeCreateEventLoop(); 
 824     server
.db 
= zmalloc(sizeof(redisDb
)*server
.dbnum
); 
 825     server
.ipfd 
= anetTcpServer(server
.neterr
,server
.port
,server
.bindaddr
); 
 826     if (server
.ipfd 
== ANET_ERR
) { 
 827         redisLog(REDIS_WARNING
, "Opening port: %s", server
.neterr
); 
 830     if (server
.unixsocket 
!= NULL
) { 
 831         unlink(server
.unixsocket
); /* don't care if this fails */ 
 832         server
.sofd 
= anetUnixServer(server
.neterr
,server
.unixsocket
); 
 833         if (server
.sofd 
== ANET_ERR
) { 
 834             redisLog(REDIS_WARNING
, "Opening socket: %s", server
.neterr
); 
 838     if (server
.ipfd 
< 0 && server
.sofd 
< 0) { 
 839         redisLog(REDIS_WARNING
, "Configured to not listen anywhere, exiting."); 
 842     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 843         server
.db
[j
].dict 
= dictCreate(&dbDictType
,NULL
); 
 844         server
.db
[j
].expires 
= dictCreate(&keyptrDictType
,NULL
); 
 845         server
.db
[j
].blocking_keys 
= dictCreate(&keylistDictType
,NULL
); 
 846         server
.db
[j
].watched_keys 
= dictCreate(&keylistDictType
,NULL
); 
 847         if (server
.vm_enabled
) 
 848             server
.db
[j
].io_keys 
= dictCreate(&keylistDictType
,NULL
); 
 851     server
.pubsub_channels 
= dictCreate(&keylistDictType
,NULL
); 
 852     server
.pubsub_patterns 
= listCreate(); 
 853     listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
); 
 854     listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
); 
 855     server
.cronloops 
= 0; 
 856     server
.bgsavechildpid 
= -1; 
 857     server
.bgrewritechildpid 
= -1; 
 858     server
.bgrewritebuf 
= sdsempty(); 
 859     server
.aofbuf 
= sdsempty(); 
 860     server
.lastsave 
= time(NULL
); 
 862     server
.stat_numcommands 
= 0; 
 863     server
.stat_numconnections 
= 0; 
 864     server
.stat_expiredkeys 
= 0; 
 865     server
.stat_starttime 
= time(NULL
); 
 866     server
.stat_keyspace_misses 
= 0; 
 867     server
.stat_keyspace_hits 
= 0; 
 868     server
.unixtime 
= time(NULL
); 
 869     aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
); 
 870     if (server
.ipfd 
> 0 && aeCreateFileEvent(server
.el
,server
.ipfd
,AE_READABLE
, 
 871         acceptTcpHandler
,NULL
) == AE_ERR
) oom("creating file event"); 
 872     if (server
.sofd 
> 0 && aeCreateFileEvent(server
.el
,server
.sofd
,AE_READABLE
, 
 873         acceptUnixHandler
,NULL
) == AE_ERR
) oom("creating file event"); 
 875     if (server
.appendonly
) { 
 876         server
.appendfd 
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644); 
 877         if (server
.appendfd 
== -1) { 
 878             redisLog(REDIS_WARNING
, "Can't open the append-only file: %s", 
 884     if (server
.vm_enabled
) vmInit(); 
 887 /* Populates the Redis Command Table starting from the hard coded list 
 888  * we have on top of redis.c file. */ 
 889 void populateCommandTable(void) { 
 891     int numcommands 
= sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
); 
 893     for (j 
= 0; j 
< numcommands
; j
++) { 
 894         struct redisCommand 
*c 
= readonlyCommandTable
+j
; 
 897         retval 
= dictAdd(server
.commands
, sdsnew(c
->name
), c
); 
 898         assert(retval 
== DICT_OK
); 
 902 /* ====================== Commands lookup and execution ===================== */ 
 904 struct redisCommand 
*lookupCommand(sds name
) { 
 905     return dictFetchValue(server
.commands
, name
); 
 908 struct redisCommand 
*lookupCommandByCString(char *s
) { 
 909     struct redisCommand 
*cmd
; 
 910     sds name 
= sdsnew(s
); 
 912     cmd 
= dictFetchValue(server
.commands
, name
); 
 917 /* Call() is the core of Redis execution of a command */ 
 918 void call(redisClient 
*c
, struct redisCommand 
*cmd
) { 
 921     dirty 
= server
.dirty
; 
 923     dirty 
= server
.dirty
-dirty
; 
 925     if (server
.appendonly 
&& dirty
) 
 926         feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
); 
 927     if ((dirty 
|| cmd
->flags 
& REDIS_CMD_FORCE_REPLICATION
) && 
 928         listLength(server
.slaves
)) 
 929         replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
); 
 930     if (listLength(server
.monitors
)) 
 931         replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
); 
 932     server
.stat_numcommands
++; 
 935 /* If this function gets called we already read a whole 
 936  * command, argments are in the client argv/argc fields. 
 937  * processCommand() execute the command or prepare the 
 938  * server for a bulk read from the client. 
 940  * If 1 is returned the client is still alive and valid and 
 941  * and other operations can be performed by the caller. Otherwise 
 942  * if 0 is returned the client was destroied (i.e. after QUIT). */ 
 943 int processCommand(redisClient 
*c
) { 
 944     struct redisCommand 
*cmd
; 
 946     /* The QUIT command is handled separately. Normal command procs will 
 947      * go through checking for replication and QUIT will cause trouble 
 948      * when FORCE_REPLICATION is enabled and would be implemented in 
 949      * a regular command proc. */ 
 950     if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) { 
 951         addReply(c
,shared
.ok
); 
 952         c
->flags 
|= REDIS_CLOSE_AFTER_REPLY
; 
 956     /* Now lookup the command and check ASAP about trivial error conditions 
 957      * such wrong arity, bad command name and so forth. */ 
 958     cmd 
= lookupCommand(c
->argv
[0]->ptr
); 
 960         addReplyErrorFormat(c
,"unknown command '%s'", 
 961             (char*)c
->argv
[0]->ptr
); 
 963     } else if ((cmd
->arity 
> 0 && cmd
->arity 
!= c
->argc
) || 
 964                (c
->argc 
< -cmd
->arity
)) { 
 965         addReplyErrorFormat(c
,"wrong number of arguments for '%s' command", 
 970     /* Check if the user is authenticated */ 
 971     if (server
.requirepass 
&& !c
->authenticated 
&& cmd
->proc 
!= authCommand
) { 
 972         addReplyError(c
,"operation not permitted"); 
 976     /* Handle the maxmemory directive. 
 978      * First we try to free some memory if possible (if there are volatile 
 979      * keys in the dataset). If there are not the only thing we can do 
 980      * is returning an error. */ 
 981     if (server
.maxmemory
) freeMemoryIfNeeded(); 
 982     if (server
.maxmemory 
&& (cmd
->flags 
& REDIS_CMD_DENYOOM
) && 
 983         zmalloc_used_memory() > server
.maxmemory
) 
 985         addReplyError(c
,"command not allowed when used memory > 'maxmemory'"); 
 989     /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ 
 990     if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0) 
 992         cmd
->proc 
!= subscribeCommand 
&& cmd
->proc 
!= unsubscribeCommand 
&& 
 993         cmd
->proc 
!= psubscribeCommand 
&& cmd
->proc 
!= punsubscribeCommand
) { 
 994         addReplyError(c
,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context"); 
 998     /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and 
 999      * we are a slave with a broken link with master. */ 
1000     if (server
.masterhost 
&& server
.replstate 
!= REDIS_REPL_CONNECTED 
&& 
1001         server
.repl_serve_stale_data 
== 0 && 
1002         cmd
->proc 
!= infoCommand 
&& cmd
->proc 
!= slaveofCommand
) 
1005             "link with MASTER is down and slave-serve-stale-data is set to no"); 
1009     /* Loading DB? Return an error if the command is not INFO */ 
1010     if (server
.loading 
&& cmd
->proc 
!= infoCommand
) { 
1011         addReply(c
, shared
.loadingerr
); 
1015     /* Exec the command */ 
1016     if (c
->flags 
& REDIS_MULTI 
&& 
1017         cmd
->proc 
!= execCommand 
&& cmd
->proc 
!= discardCommand 
&& 
1018         cmd
->proc 
!= multiCommand 
&& cmd
->proc 
!= watchCommand
) 
1020         queueMultiCommand(c
,cmd
); 
1021         addReply(c
,shared
.queued
); 
1023         if (server
.vm_enabled 
&& server
.vm_max_threads 
> 0 && 
1024             blockClientOnSwappedKeys(c
,cmd
)) return REDIS_ERR
; 
1030 /*================================== Shutdown =============================== */ 
1032 int prepareForShutdown() { 
1033     redisLog(REDIS_WARNING
,"User requested shutdown, saving DB..."); 
1034     /* Kill the saving child if there is a background saving in progress. 
1035        We want to avoid race conditions, for instance our saving child may 
1036        overwrite the synchronous saving did by SHUTDOWN. */ 
1037     if (server
.bgsavechildpid 
!= -1) { 
1038         redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!"); 
1039         kill(server
.bgsavechildpid
,SIGKILL
); 
1040         rdbRemoveTempFile(server
.bgsavechildpid
); 
1042     if (server
.appendonly
) { 
1043         /* Append only file: fsync() the AOF and exit */ 
1044         aof_fsync(server
.appendfd
); 
1045         if (server
.vm_enabled
) unlink(server
.vm_swap_file
); 
1046     } else if (server
.saveparamslen 
> 0) { 
1047         /* Snapshotting. Perform a SYNC SAVE and exit */ 
1048         if (rdbSave(server
.dbfilename
) != REDIS_OK
) { 
1049             /* Ooops.. error saving! The best we can do is to continue 
1050              * operating. Note that if there was a background saving process, 
1051              * in the next cron() Redis will be notified that the background 
1052              * saving aborted, handling special stuff like slaves pending for 
1053              * synchronization... */ 
1054             redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit"); 
1058         redisLog(REDIS_WARNING
,"Not saving DB."); 
1060     if (server
.daemonize
) unlink(server
.pidfile
); 
1061     redisLog(REDIS_WARNING
,"Server exit now, bye bye..."); 
1065 /*================================== Commands =============================== */ 
1067 void authCommand(redisClient 
*c
) { 
1068     if (!server
.requirepass 
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) { 
1069       c
->authenticated 
= 1; 
1070       addReply(c
,shared
.ok
); 
1072       c
->authenticated 
= 0; 
1073       addReplyError(c
,"invalid password"); 
1077 void pingCommand(redisClient 
*c
) { 
1078     addReply(c
,shared
.pong
); 
1081 void echoCommand(redisClient 
*c
) { 
1082     addReplyBulk(c
,c
->argv
[1]); 
1085 /* Convert an amount of bytes into a human readable string in the form 
1086  * of 100B, 2G, 100M, 4K, and so forth. */ 
1087 void bytesToHuman(char *s
, unsigned long long n
) { 
1092         sprintf(s
,"%lluB",n
); 
1094     } else if (n 
< (1024*1024)) { 
1095         d 
= (double)n
/(1024); 
1096         sprintf(s
,"%.2fK",d
); 
1097     } else if (n 
< (1024LL*1024*1024)) { 
1098         d 
= (double)n
/(1024*1024); 
1099         sprintf(s
,"%.2fM",d
); 
1100     } else if (n 
< (1024LL*1024*1024*1024)) { 
1101         d 
= (double)n
/(1024LL*1024*1024); 
1102         sprintf(s
,"%.2fG",d
); 
1106 /* Create the string returned by the INFO command. This is decoupled 
1107  * by the INFO command itself as we need to report the same information 
1108  * on memory corruption problems. */ 
1109 sds 
genRedisInfoString(void) { 
1111     time_t uptime 
= time(NULL
)-server
.stat_starttime
; 
1114     struct rusage self_ru
, c_ru
; 
1116     getrusage(RUSAGE_SELF
, &self_ru
); 
1117     getrusage(RUSAGE_CHILDREN
, &c_ru
); 
1119     bytesToHuman(hmem
,zmalloc_used_memory()); 
1120     info 
= sdscatprintf(sdsempty(), 
1121         "redis_version:%s\r\n" 
1122         "redis_git_sha1:%s\r\n" 
1123         "redis_git_dirty:%d\r\n" 
1125         "multiplexing_api:%s\r\n" 
1126         "process_id:%ld\r\n" 
1127         "uptime_in_seconds:%ld\r\n" 
1128         "uptime_in_days:%ld\r\n" 
1130         "used_cpu_sys:%.2f\r\n" 
1131         "used_cpu_user:%.2f\r\n" 
1132         "used_cpu_sys_childrens:%.2f\r\n" 
1133         "used_cpu_user_childrens:%.2f\r\n" 
1134         "connected_clients:%d\r\n" 
1135         "connected_slaves:%d\r\n" 
1136         "blocked_clients:%d\r\n" 
1137         "used_memory:%zu\r\n" 
1138         "used_memory_human:%s\r\n" 
1139         "used_memory_rss:%zu\r\n" 
1140         "mem_fragmentation_ratio:%.2f\r\n" 
1141         "use_tcmalloc:%d\r\n" 
1143         "aof_enabled:%d\r\n" 
1144         "changes_since_last_save:%lld\r\n" 
1145         "bgsave_in_progress:%d\r\n" 
1146         "last_save_time:%ld\r\n" 
1147         "bgrewriteaof_in_progress:%d\r\n" 
1148         "total_connections_received:%lld\r\n" 
1149         "total_commands_processed:%lld\r\n" 
1150         "expired_keys:%lld\r\n" 
1151         "keyspace_hits:%lld\r\n" 
1152         "keyspace_misses:%lld\r\n" 
1153         "hash_max_zipmap_entries:%zu\r\n" 
1154         "hash_max_zipmap_value:%zu\r\n" 
1155         "pubsub_channels:%ld\r\n" 
1156         "pubsub_patterns:%u\r\n" 
1161         strtol(redisGitDirty(),NULL
,10) > 0, 
1162         (sizeof(long) == 8) ? "64" : "32", 
1167         (unsigned long) server
.lruclock
, 
1168         (float)self_ru
.ru_utime
.tv_sec
+(float)self_ru
.ru_utime
.tv_usec
/1000000, 
1169         (float)self_ru
.ru_stime
.tv_sec
+(float)self_ru
.ru_stime
.tv_usec
/1000000, 
1170         (float)c_ru
.ru_utime
.tv_sec
+(float)c_ru
.ru_utime
.tv_usec
/1000000, 
1171         (float)c_ru
.ru_stime
.tv_sec
+(float)c_ru
.ru_stime
.tv_usec
/1000000, 
1172         listLength(server
.clients
)-listLength(server
.slaves
), 
1173         listLength(server
.slaves
), 
1174         server
.blpop_blocked_clients
, 
1175         zmalloc_used_memory(), 
1178         zmalloc_get_fragmentation_ratio(), 
1187         server
.bgsavechildpid 
!= -1, 
1189         server
.bgrewritechildpid 
!= -1, 
1190         server
.stat_numconnections
, 
1191         server
.stat_numcommands
, 
1192         server
.stat_expiredkeys
, 
1193         server
.stat_keyspace_hits
, 
1194         server
.stat_keyspace_misses
, 
1195         server
.hash_max_zipmap_entries
, 
1196         server
.hash_max_zipmap_value
, 
1197         dictSize(server
.pubsub_channels
), 
1198         listLength(server
.pubsub_patterns
), 
1199         server
.vm_enabled 
!= 0, 
1200         server
.masterhost 
== NULL 
? "master" : "slave" 
1202     if (server
.masterhost
) { 
1203         info 
= sdscatprintf(info
, 
1204             "master_host:%s\r\n" 
1205             "master_port:%d\r\n" 
1206             "master_link_status:%s\r\n" 
1207             "master_last_io_seconds_ago:%d\r\n" 
1208             "master_sync_in_progress:%d\r\n" 
1211             (server
.replstate 
== REDIS_REPL_CONNECTED
) ? 
1213             server
.master 
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1, 
1214             server
.replstate 
== REDIS_REPL_TRANSFER
 
1217         if (server
.replstate 
== REDIS_REPL_TRANSFER
) { 
1218             info 
= sdscatprintf(info
, 
1219                 "master_sync_left_bytes:%ld\r\n" 
1220                 "master_sync_last_io_seconds_ago:%d\r\n" 
1221                 ,(long)server
.repl_transfer_left
, 
1222                 (int)(time(NULL
)-server
.repl_transfer_lastio
) 
1226     if (server
.vm_enabled
) { 
1228         info 
= sdscatprintf(info
, 
1229             "vm_conf_max_memory:%llu\r\n" 
1230             "vm_conf_page_size:%llu\r\n" 
1231             "vm_conf_pages:%llu\r\n" 
1232             "vm_stats_used_pages:%llu\r\n" 
1233             "vm_stats_swapped_objects:%llu\r\n" 
1234             "vm_stats_swappin_count:%llu\r\n" 
1235             "vm_stats_swappout_count:%llu\r\n" 
1236             "vm_stats_io_newjobs_len:%lu\r\n" 
1237             "vm_stats_io_processing_len:%lu\r\n" 
1238             "vm_stats_io_processed_len:%lu\r\n" 
1239             "vm_stats_io_active_threads:%lu\r\n" 
1240             "vm_stats_blocked_clients:%lu\r\n" 
1241             ,(unsigned long long) server
.vm_max_memory
, 
1242             (unsigned long long) server
.vm_page_size
, 
1243             (unsigned long long) server
.vm_pages
, 
1244             (unsigned long long) server
.vm_stats_used_pages
, 
1245             (unsigned long long) server
.vm_stats_swapped_objects
, 
1246             (unsigned long long) server
.vm_stats_swapins
, 
1247             (unsigned long long) server
.vm_stats_swapouts
, 
1248             (unsigned long) listLength(server
.io_newjobs
), 
1249             (unsigned long) listLength(server
.io_processing
), 
1250             (unsigned long) listLength(server
.io_processed
), 
1251             (unsigned long) server
.io_active_threads
, 
1252             (unsigned long) server
.vm_blocked_clients
 
1256     if (server
.loading
) { 
1258         time_t eta
, elapsed
; 
1259         off_t remaining_bytes 
= server
.loading_total_bytes
- 
1260                                 server
.loading_loaded_bytes
; 
1262         perc 
= ((double)server
.loading_loaded_bytes 
/ 
1263                server
.loading_total_bytes
) * 100; 
1265         elapsed 
= time(NULL
)-server
.loading_start_time
; 
1267             eta 
= 1; /* A fake 1 second figure if we don't have enough info */ 
1269             eta 
= (elapsed
*remaining_bytes
)/server
.loading_loaded_bytes
; 
1272         info 
= sdscatprintf(info
, 
1273             "loading_start_time:%ld\r\n" 
1274             "loading_total_bytes:%llu\r\n" 
1275             "loading_loaded_bytes:%llu\r\n" 
1276             "loading_loaded_perc:%.2f\r\n" 
1277             "loading_eta_seconds:%ld\r\n" 
1278             ,(unsigned long) server
.loading_start_time
, 
1279             (unsigned long long) server
.loading_total_bytes
, 
1280             (unsigned long long) server
.loading_loaded_bytes
, 
1285     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1286         long long keys
, vkeys
; 
1288         keys 
= dictSize(server
.db
[j
].dict
); 
1289         vkeys 
= dictSize(server
.db
[j
].expires
); 
1290         if (keys 
|| vkeys
) { 
1291             info 
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n", 
1298 void infoCommand(redisClient 
*c
) { 
1299     sds info 
= genRedisInfoString(); 
1300     addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n", 
1301         (unsigned long)sdslen(info
))); 
1302     addReplySds(c
,info
); 
1303     addReply(c
,shared
.crlf
); 
1306 void monitorCommand(redisClient 
*c
) { 
1307     /* ignore MONITOR if aleady slave or in monitor mode */ 
1308     if (c
->flags 
& REDIS_SLAVE
) return; 
1310     c
->flags 
|= (REDIS_SLAVE
|REDIS_MONITOR
); 
1312     listAddNodeTail(server
.monitors
,c
); 
1313     addReply(c
,shared
.ok
); 
1316 /* ============================ Maxmemory directive  ======================== */ 
1318 /* This function gets called when 'maxmemory' is set on the config file to limit 
1319  * the max memory used by the server, and we are out of memory. 
1320  * This function will try to, in order: 
1322  * - Free objects from the free list 
1323  * - Try to remove keys with an EXPIRE set 
1325  * It is not possible to free enough memory to reach used-memory < maxmemory 
1326  * the server will start refusing commands that will enlarge even more the 
1329 void freeMemoryIfNeeded(void) { 
1330     /* Remove keys accordingly to the active policy as long as we are 
1331      * over the memory limit. */ 
1332     if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_NO_EVICTION
) return; 
1334     while (server
.maxmemory 
&& zmalloc_used_memory() > server
.maxmemory
) { 
1335         int j
, k
, freed 
= 0; 
1337         for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1338             long bestval 
= 0; /* just to prevent warning */ 
1340             struct dictEntry 
*de
; 
1341             redisDb 
*db 
= server
.db
+j
; 
1344             if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_LRU 
|| 
1345                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_RANDOM
) 
1347                 dict 
= server
.db
[j
].dict
; 
1349                 dict 
= server
.db
[j
].expires
; 
1351             if (dictSize(dict
) == 0) continue; 
1353             /* volatile-random and allkeys-random policy */ 
1354             if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_RANDOM 
|| 
1355                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_RANDOM
) 
1357                 de 
= dictGetRandomKey(dict
); 
1358                 bestkey 
= dictGetEntryKey(de
); 
1361             /* volatile-lru and allkeys-lru policy */ 
1362             else if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_ALLKEYS_LRU 
|| 
1363                 server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_LRU
) 
1365                 for (k 
= 0; k 
< server
.maxmemory_samples
; k
++) { 
1370                     de 
= dictGetRandomKey(dict
); 
1371                     thiskey 
= dictGetEntryKey(de
); 
1372                     /* When policy is volatile-lru we need an additonal lookup 
1373                      * to locate the real key, as dict is set to db->expires. */ 
1374                     if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_LRU
) 
1375                         de 
= dictFind(db
->dict
, thiskey
); 
1376                     o 
= dictGetEntryVal(de
); 
1377                     thisval 
= estimateObjectIdleTime(o
); 
1379                     /* Higher idle time is better candidate for deletion */ 
1380                     if (bestkey 
== NULL 
|| thisval 
> bestval
) { 
1388             else if (server
.maxmemory_policy 
== REDIS_MAXMEMORY_VOLATILE_TTL
) { 
1389                 for (k 
= 0; k 
< server
.maxmemory_samples
; k
++) { 
1393                     de 
= dictGetRandomKey(dict
); 
1394                     thiskey 
= dictGetEntryKey(de
); 
1395                     thisval 
= (long) dictGetEntryVal(de
); 
1397                     /* Expire sooner (minor expire unix timestamp) is better 
1398                      * candidate for deletion */ 
1399                     if (bestkey 
== NULL 
|| thisval 
< bestval
) { 
1406             /* Finally remove the selected key. */ 
1408                 robj 
*keyobj 
= createStringObject(bestkey
,sdslen(bestkey
)); 
1409                 dbDelete(db
,keyobj
); 
1410                 server
.stat_expiredkeys
++; 
1411                 decrRefCount(keyobj
); 
1415         if (!freed
) return; /* nothing to free... */ 
1419         int j
, k
, freed 
= 0; 
1420         for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1423             robj 
*keyobj 
= NULL
; 
1424             struct dictEntry 
*de
; 
1426             if (dictSize(server
.db
[j
].expires
)) { 
1428                 /* From a sample of three keys drop the one nearest to 
1429                  * the natural expire */ 
1430                 for (k 
= 0; k 
< 3; k
++) { 
1433                     de 
= dictGetRandomKey(server
.db
[j
].expires
); 
1434                     t 
= (time_t) dictGetEntryVal(de
); 
1435                     if (minttl 
== -1 || t 
< minttl
) { 
1436                         minkey 
= dictGetEntryKey(de
); 
1440                 keyobj 
= createStringObject(minkey
,sdslen(minkey
)); 
1441                 dbDelete(server
.db
+j
,keyobj
); 
1442                 server
.stat_expiredkeys
++; 
1443                 decrRefCount(keyobj
); 
1446         if (!freed
) return; /* nothing to free... */ 
1450 /* =================================== Main! ================================ */ 
1453 int linuxOvercommitMemoryValue(void) { 
1454     FILE *fp 
= fopen("/proc/sys/vm/overcommit_memory","r"); 
1458     if (fgets(buf
,64,fp
) == NULL
) { 
1467 void linuxOvercommitMemoryWarning(void) { 
1468     if (linuxOvercommitMemoryValue() == 0) { 
1469         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."); 
1472 #endif /* __linux__ */ 
1474 void createPidFile(void) { 
1475     /* Try to write the pid file in a best-effort way. */ 
1476     FILE *fp 
= fopen(server
.pidfile
,"w"); 
1478         fprintf(fp
,"%d\n",getpid()); 
1483 void daemonize(void) { 
1486     if (fork() != 0) exit(0); /* parent exits */ 
1487     setsid(); /* create a new session */ 
1489     /* Every output goes to /dev/null. If Redis is daemonized but 
1490      * the 'logfile' is set to 'stdout' in the configuration file 
1491      * it will not log at all. */ 
1492     if ((fd 
= open("/dev/null", O_RDWR
, 0)) != -1) { 
1493         dup2(fd
, STDIN_FILENO
); 
1494         dup2(fd
, STDOUT_FILENO
); 
1495         dup2(fd
, STDERR_FILENO
); 
1496         if (fd 
> STDERR_FILENO
) close(fd
); 
1501     printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
, 
1502         redisGitSHA1(), atoi(redisGitDirty()) > 0); 
1507     fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n"); 
1508     fprintf(stderr
,"       ./redis-server - (read config from stdin)\n"); 
1512 int main(int argc
, char **argv
) { 
1517         if (strcmp(argv
[1], "-v") == 0 || 
1518             strcmp(argv
[1], "--version") == 0) version(); 
1519         if (strcmp(argv
[1], "--help") == 0) usage(); 
1520         resetServerSaveParams(); 
1521         loadServerConfig(argv
[1]); 
1522     } else if ((argc 
> 2)) { 
1525         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'"); 
1527     if (server
.daemonize
) daemonize(); 
1529     if (server
.daemonize
) createPidFile(); 
1530     redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
); 
1532     linuxOvercommitMemoryWarning(); 
1535     if (server
.appendonly
) { 
1536         if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
) 
1537             redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
); 
1539         if (rdbLoad(server
.dbfilename
) == REDIS_OK
) 
1540             redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
); 
1542     if (server
.ipfd 
> 0) 
1543         redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
); 
1544     if (server
.sofd 
> 0) 
1545         redisLog(REDIS_NOTICE
,"The server is now ready to accept connections at %s", server
.unixsocket
); 
1546     aeSetBeforeSleepProc(server
.el
,beforeSleep
); 
1548     aeDeleteEventLoop(server
.el
); 
1552 /* ============================= Backtrace support ========================= */ 
1554 #ifdef HAVE_BACKTRACE 
1555 void *getMcontextEip(ucontext_t 
*uc
) { 
1556 #if defined(__FreeBSD__) 
1557     return (void*) uc
->uc_mcontext
.mc_eip
; 
1558 #elif defined(__dietlibc__) 
1559     return (void*) uc
->uc_mcontext
.eip
; 
1560 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6) 
1562     return (void*) uc
->uc_mcontext
->__ss
.__rip
; 
1564     return (void*) uc
->uc_mcontext
->__ss
.__eip
; 
1566 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) 
1567   #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) 
1568     return (void*) uc
->uc_mcontext
->__ss
.__rip
; 
1570     return (void*) uc
->uc_mcontext
->__ss
.__eip
; 
1572 #elif defined(__i386__) 
1573     return (void*) uc
->uc_mcontext
.gregs
[14]; /* Linux 32 */ 
1574 #elif defined(__X86_64__) || defined(__x86_64__) 
1575     return (void*) uc
->uc_mcontext
.gregs
[16]; /* Linux 64 */ 
1576 #elif defined(__ia64__) /* Linux IA64 */ 
1577     return (void*) uc
->uc_mcontext
.sc_ip
; 
1583 void segvHandler(int sig
, siginfo_t 
*info
, void *secret
) { 
1585     char **messages 
= NULL
; 
1586     int i
, trace_size 
= 0; 
1587     ucontext_t 
*uc 
= (ucontext_t
*) secret
; 
1589     struct sigaction act
; 
1590     REDIS_NOTUSED(info
); 
1592     redisLog(REDIS_WARNING
, 
1593         "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
); 
1594     infostring 
= genRedisInfoString(); 
1595     redisLog(REDIS_WARNING
, "%s",infostring
); 
1596     /* It's not safe to sdsfree() the returned string under memory 
1597      * corruption conditions. Let it leak as we are going to abort */ 
1599     trace_size 
= backtrace(trace
, 100); 
1600     /* overwrite sigaction with caller's address */ 
1601     if (getMcontextEip(uc
) != NULL
) { 
1602         trace
[1] = getMcontextEip(uc
); 
1604     messages 
= backtrace_symbols(trace
, trace_size
); 
1606     for (i
=1; i
<trace_size
; ++i
) 
1607         redisLog(REDIS_WARNING
,"%s", messages
[i
]); 
1609     /* free(messages); Don't call free() with possibly corrupted memory. */ 
1610     if (server
.daemonize
) unlink(server
.pidfile
); 
1612     /* Make sure we exit with the right signal at the end. So for instance 
1613      * the core will be dumped if enabled. */ 
1614     sigemptyset (&act
.sa_mask
); 
1615     /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction 
1616      * is used. Otherwise, sa_handler is used */ 
1617     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND
; 
1618     act
.sa_handler 
= SIG_DFL
; 
1619     sigaction (sig
, &act
, NULL
); 
1623 void sigtermHandler(int sig
) { 
1626     redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down..."); 
1627     server
.shutdown_asap 
= 1; 
1630 void setupSigSegvAction(void) { 
1631     struct sigaction act
; 
1633     sigemptyset (&act
.sa_mask
); 
1634     /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction 
1635      * is used. Otherwise, sa_handler is used */ 
1636     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND 
| SA_SIGINFO
; 
1637     act
.sa_sigaction 
= segvHandler
; 
1638     sigaction (SIGSEGV
, &act
, NULL
); 
1639     sigaction (SIGBUS
, &act
, NULL
); 
1640     sigaction (SIGFPE
, &act
, NULL
); 
1641     sigaction (SIGILL
, &act
, NULL
); 
1642     sigaction (SIGBUS
, &act
, NULL
); 
1644     act
.sa_flags 
= SA_NODEFER 
| SA_ONSTACK 
| SA_RESETHAND
; 
1645     act
.sa_handler 
= sigtermHandler
; 
1646     sigaction (SIGTERM
, &act
, NULL
); 
1650 #else /* HAVE_BACKTRACE */ 
1651 void setupSigSegvAction(void) { 
1653 #endif /* HAVE_BACKTRACE */