]> git.saurik.com Git - redis.git/blame - src/redis.c
removed a test that will never be true fixing the compilation on Linux
[redis.git] / src / redis.c
CommitLineData
e2641e09 1/*
2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
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.
16 *
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.
28 */
29
30#include "redis.h"
31
32#ifdef HAVE_BACKTRACE
33#include <execinfo.h>
34#include <ucontext.h>
35#endif /* HAVE_BACKTRACE */
36
37#include <time.h>
38#include <signal.h>
39#include <sys/wait.h>
40#include <errno.h>
41#include <assert.h>
42#include <ctype.h>
43#include <stdarg.h>
e2641e09 44#include <arpa/inet.h>
45#include <sys/stat.h>
46#include <fcntl.h>
47#include <sys/time.h>
48#include <sys/resource.h>
49#include <sys/uio.h>
50#include <limits.h>
51#include <float.h>
52#include <math.h>
53#include <pthread.h>
2b00385d 54#include <sys/resource.h>
e2641e09 55
56/* Our shared "common" objects */
57
58struct sharedObjectsStruct shared;
59
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. */
63
64double R_Zero, R_PosInf, R_NegInf, R_Nan;
65
66/*================================= Globals ================================= */
67
68/* Global vars */
69struct redisServer server; /* server global state */
70struct redisCommand *commandTable;
71struct redisCommand readonlyCommandTable[] = {
33aba595
PN
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},
33aba595
PN
77 {"strlen",strlenCommand,2,0,NULL,1,1,1},
78 {"del",delCommand,-2,0,NULL,0,0,0},
79 {"exists",existsCommand,2,0,NULL,1,1,1},
3c1bf495
PN
80 {"setbit",setbitCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
81 {"getbit",getbitCommand,3,0,NULL,1,1,1},
9f9e1cea 82 {"setrange",setrangeCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
ef11bccc
PN
83 {"getrange",getrangeCommand,4,0,NULL,1,1,1},
84 {"substr",getrangeCommand,4,0,NULL,1,1,1},
33aba595
PN
85 {"incr",incrCommand,2,REDIS_CMD_DENYOOM,NULL,1,1,1},
86 {"decr",decrCommand,2,REDIS_CMD_DENYOOM,NULL,1,1,1},
87 {"mget",mgetCommand,-2,0,NULL,1,-1,1},
88 {"rpush",rpushCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
89 {"lpush",lpushCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
90 {"rpushx",rpushxCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
91 {"lpushx",lpushxCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
92 {"linsert",linsertCommand,5,REDIS_CMD_DENYOOM,NULL,1,1,1},
93 {"rpop",rpopCommand,2,0,NULL,1,1,1},
94 {"lpop",lpopCommand,2,0,NULL,1,1,1},
95 {"brpop",brpopCommand,-3,0,NULL,1,1,1},
b2a7fd0c 96 {"brpoplpush",brpoplpushCommand,4,REDIS_CMD_DENYOOM,NULL,1,2,1},
33aba595
PN
97 {"blpop",blpopCommand,-3,0,NULL,1,1,1},
98 {"llen",llenCommand,2,0,NULL,1,1,1},
99 {"lindex",lindexCommand,3,0,NULL,1,1,1},
100 {"lset",lsetCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
101 {"lrange",lrangeCommand,4,0,NULL,1,1,1},
102 {"ltrim",ltrimCommand,4,0,NULL,1,1,1},
103 {"lrem",lremCommand,4,0,NULL,1,1,1},
8a979f03 104 {"rpoplpush",rpoplpushCommand,3,REDIS_CMD_DENYOOM,NULL,1,2,1},
33aba595
PN
105 {"sadd",saddCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
106 {"srem",sremCommand,3,0,NULL,1,1,1},
107 {"smove",smoveCommand,4,0,NULL,1,2,1},
108 {"sismember",sismemberCommand,3,0,NULL,1,1,1},
109 {"scard",scardCommand,2,0,NULL,1,1,1},
110 {"spop",spopCommand,2,0,NULL,1,1,1},
111 {"srandmember",srandmemberCommand,2,0,NULL,1,1,1},
112 {"sinter",sinterCommand,-2,REDIS_CMD_DENYOOM,NULL,1,-1,1},
113 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_DENYOOM,NULL,2,-1,1},
114 {"sunion",sunionCommand,-2,REDIS_CMD_DENYOOM,NULL,1,-1,1},
115 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_DENYOOM,NULL,2,-1,1},
116 {"sdiff",sdiffCommand,-2,REDIS_CMD_DENYOOM,NULL,1,-1,1},
117 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_DENYOOM,NULL,2,-1,1},
118 {"smembers",sinterCommand,2,0,NULL,1,1,1},
119 {"zadd",zaddCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
120 {"zincrby",zincrbyCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
121 {"zrem",zremCommand,3,0,NULL,1,1,1},
122 {"zremrangebyscore",zremrangebyscoreCommand,4,0,NULL,1,1,1},
123 {"zremrangebyrank",zremrangebyrankCommand,4,0,NULL,1,1,1},
124 {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
125 {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
126 {"zrange",zrangeCommand,-4,0,NULL,1,1,1},
127 {"zrangebyscore",zrangebyscoreCommand,-4,0,NULL,1,1,1},
21dbc649 128 {"zrevrangebyscore",zrevrangebyscoreCommand,-4,0,NULL,1,1,1},
33aba595
PN
129 {"zcount",zcountCommand,4,0,NULL,1,1,1},
130 {"zrevrange",zrevrangeCommand,-4,0,NULL,1,1,1},
131 {"zcard",zcardCommand,2,0,NULL,1,1,1},
5402c426 132 {"zscore",zscoreCommand,3,0,NULL,1,1,1},
33aba595
PN
133 {"zrank",zrankCommand,3,0,NULL,1,1,1},
134 {"zrevrank",zrevrankCommand,3,0,NULL,1,1,1},
135 {"hset",hsetCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
136 {"hsetnx",hsetnxCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
137 {"hget",hgetCommand,3,0,NULL,1,1,1},
138 {"hmset",hmsetCommand,-4,REDIS_CMD_DENYOOM,NULL,1,1,1},
139 {"hmget",hmgetCommand,-3,0,NULL,1,1,1},
140 {"hincrby",hincrbyCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
141 {"hdel",hdelCommand,3,0,NULL,1,1,1},
142 {"hlen",hlenCommand,2,0,NULL,1,1,1},
143 {"hkeys",hkeysCommand,2,0,NULL,1,1,1},
144 {"hvals",hvalsCommand,2,0,NULL,1,1,1},
145 {"hgetall",hgetallCommand,2,0,NULL,1,1,1},
146 {"hexists",hexistsCommand,3,0,NULL,1,1,1},
147 {"incrby",incrbyCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
148 {"decrby",decrbyCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
149 {"getset",getsetCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
150 {"mset",msetCommand,-3,REDIS_CMD_DENYOOM,NULL,1,-1,2},
151 {"msetnx",msetnxCommand,-3,REDIS_CMD_DENYOOM,NULL,1,-1,2},
152 {"randomkey",randomkeyCommand,1,0,NULL,0,0,0},
153 {"select",selectCommand,2,0,NULL,0,0,0},
154 {"move",moveCommand,3,0,NULL,1,1,1},
155 {"rename",renameCommand,3,0,NULL,1,1,1},
156 {"renamenx",renamenxCommand,3,0,NULL,1,1,1},
157 {"expire",expireCommand,3,0,NULL,0,0,0},
158 {"expireat",expireatCommand,3,0,NULL,0,0,0},
159 {"keys",keysCommand,2,0,NULL,0,0,0},
160 {"dbsize",dbsizeCommand,1,0,NULL,0,0,0},
161 {"auth",authCommand,2,0,NULL,0,0,0},
162 {"ping",pingCommand,1,0,NULL,0,0,0},
163 {"echo",echoCommand,2,0,NULL,0,0,0},
164 {"save",saveCommand,1,0,NULL,0,0,0},
165 {"bgsave",bgsaveCommand,1,0,NULL,0,0,0},
166 {"bgrewriteaof",bgrewriteaofCommand,1,0,NULL,0,0,0},
167 {"shutdown",shutdownCommand,1,0,NULL,0,0,0},
168 {"lastsave",lastsaveCommand,1,0,NULL,0,0,0},
169 {"type",typeCommand,2,0,NULL,1,1,1},
170 {"multi",multiCommand,1,0,NULL,0,0,0},
171 {"exec",execCommand,1,REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
172 {"discard",discardCommand,1,0,NULL,0,0,0},
173 {"sync",syncCommand,1,0,NULL,0,0,0},
174 {"flushdb",flushdbCommand,1,0,NULL,0,0,0},
175 {"flushall",flushallCommand,1,0,NULL,0,0,0},
176 {"sort",sortCommand,-2,REDIS_CMD_DENYOOM,NULL,1,1,1},
177 {"info",infoCommand,1,0,NULL,0,0,0},
178 {"monitor",monitorCommand,1,0,NULL,0,0,0},
179 {"ttl",ttlCommand,2,0,NULL,1,1,1},
180 {"persist",persistCommand,2,0,NULL,1,1,1},
181 {"slaveof",slaveofCommand,3,0,NULL,0,0,0},
182 {"debug",debugCommand,-2,0,NULL,0,0,0},
183 {"config",configCommand,-2,0,NULL,0,0,0},
184 {"subscribe",subscribeCommand,-2,0,NULL,0,0,0},
185 {"unsubscribe",unsubscribeCommand,-1,0,NULL,0,0,0},
186 {"psubscribe",psubscribeCommand,-2,0,NULL,0,0,0},
187 {"punsubscribe",punsubscribeCommand,-1,0,NULL,0,0,0},
188 {"publish",publishCommand,3,REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
189 {"watch",watchCommand,-2,0,NULL,0,0,0},
190 {"unwatch",unwatchCommand,1,0,NULL,0,0,0}
e2641e09 191};
192
193/*============================ Utility functions ============================ */
194
195void redisLog(int level, const char *fmt, ...) {
196 va_list ap;
197 FILE *fp;
23072961 198 char *c = ".-*#";
199 char buf[64];
200 time_t now;
201
202 if (level < server.verbosity) return;
e2641e09 203
204 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
205 if (!fp) return;
206
207 va_start(ap, fmt);
23072961 208 now = time(NULL);
209 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
210 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
211 vfprintf(fp, fmt, ap);
212 fprintf(fp,"\n");
213 fflush(fp);
e2641e09 214 va_end(ap);
215
216 if (server.logfile) fclose(fp);
217}
218
219/* Redis generally does not try to recover from out of memory conditions
220 * when allocating objects or strings, it is not clear if it will be possible
221 * to report this condition to the client since the networking layer itself
222 * is based on heap allocation for send buffers, so we simply abort.
223 * At least the code will be simpler to read... */
224void oom(const char *msg) {
225 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
226 sleep(1);
227 abort();
228}
229
230/*====================== Hash table type implementation ==================== */
231
232/* This is an hash table type that uses the SDS dynamic strings libary as
233 * keys and radis objects as values (objects can hold SDS strings,
234 * lists, sets). */
235
236void dictVanillaFree(void *privdata, void *val)
237{
238 DICT_NOTUSED(privdata);
239 zfree(val);
240}
241
242void dictListDestructor(void *privdata, void *val)
243{
244 DICT_NOTUSED(privdata);
245 listRelease((list*)val);
246}
247
248int dictSdsKeyCompare(void *privdata, const void *key1,
249 const void *key2)
250{
251 int l1,l2;
252 DICT_NOTUSED(privdata);
253
254 l1 = sdslen((sds)key1);
255 l2 = sdslen((sds)key2);
256 if (l1 != l2) return 0;
257 return memcmp(key1, key2, l1) == 0;
258}
259
1b1f47c9 260/* A case insensitive version used for the command lookup table. */
261int dictSdsKeyCaseCompare(void *privdata, const void *key1,
262 const void *key2)
263{
264 DICT_NOTUSED(privdata);
265
266 return strcasecmp(key1, key2) == 0;
267}
268
e2641e09 269void dictRedisObjectDestructor(void *privdata, void *val)
270{
271 DICT_NOTUSED(privdata);
272
273 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
274 decrRefCount(val);
275}
276
277void dictSdsDestructor(void *privdata, void *val)
278{
279 DICT_NOTUSED(privdata);
280
281 sdsfree(val);
282}
283
284int dictObjKeyCompare(void *privdata, const void *key1,
285 const void *key2)
286{
287 const robj *o1 = key1, *o2 = key2;
288 return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
289}
290
291unsigned int dictObjHash(const void *key) {
292 const robj *o = key;
293 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
294}
295
296unsigned int dictSdsHash(const void *key) {
297 return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
298}
299
1b1f47c9 300unsigned int dictSdsCaseHash(const void *key) {
301 return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key));
302}
303
e2641e09 304int dictEncObjKeyCompare(void *privdata, const void *key1,
305 const void *key2)
306{
307 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
308 int cmp;
309
310 if (o1->encoding == REDIS_ENCODING_INT &&
311 o2->encoding == REDIS_ENCODING_INT)
312 return o1->ptr == o2->ptr;
313
314 o1 = getDecodedObject(o1);
315 o2 = getDecodedObject(o2);
316 cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
317 decrRefCount(o1);
318 decrRefCount(o2);
319 return cmp;
320}
321
322unsigned int dictEncObjHash(const void *key) {
323 robj *o = (robj*) key;
324
325 if (o->encoding == REDIS_ENCODING_RAW) {
326 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
327 } else {
328 if (o->encoding == REDIS_ENCODING_INT) {
329 char buf[32];
330 int len;
331
332 len = ll2string(buf,32,(long)o->ptr);
333 return dictGenHashFunction((unsigned char*)buf, len);
334 } else {
335 unsigned int hash;
336
337 o = getDecodedObject(o);
338 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
339 decrRefCount(o);
340 return hash;
341 }
342 }
343}
344
345/* Sets type */
346dictType setDictType = {
347 dictEncObjHash, /* hash function */
348 NULL, /* key dup */
349 NULL, /* val dup */
350 dictEncObjKeyCompare, /* key compare */
351 dictRedisObjectDestructor, /* key destructor */
352 NULL /* val destructor */
353};
354
355/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
356dictType zsetDictType = {
357 dictEncObjHash, /* hash function */
358 NULL, /* key dup */
359 NULL, /* val dup */
360 dictEncObjKeyCompare, /* key compare */
361 dictRedisObjectDestructor, /* key destructor */
69ef89f2 362 NULL /* val destructor */
e2641e09 363};
364
365/* Db->dict, keys are sds strings, vals are Redis objects. */
366dictType dbDictType = {
367 dictSdsHash, /* hash function */
368 NULL, /* key dup */
369 NULL, /* val dup */
370 dictSdsKeyCompare, /* key compare */
371 dictSdsDestructor, /* key destructor */
372 dictRedisObjectDestructor /* val destructor */
373};
374
375/* Db->expires */
376dictType keyptrDictType = {
377 dictSdsHash, /* hash function */
378 NULL, /* key dup */
379 NULL, /* val dup */
380 dictSdsKeyCompare, /* key compare */
381 NULL, /* key destructor */
382 NULL /* val destructor */
383};
384
1b1f47c9 385/* Command table. sds string -> command struct pointer. */
386dictType commandTableDictType = {
387 dictSdsCaseHash, /* hash function */
388 NULL, /* key dup */
389 NULL, /* val dup */
390 dictSdsKeyCaseCompare, /* key compare */
391 dictSdsDestructor, /* key destructor */
392 NULL /* val destructor */
393};
394
e2641e09 395/* Hash type hash table (note that small hashes are represented with zimpaps) */
396dictType hashDictType = {
397 dictEncObjHash, /* hash function */
398 NULL, /* key dup */
399 NULL, /* val dup */
400 dictEncObjKeyCompare, /* key compare */
401 dictRedisObjectDestructor, /* key destructor */
402 dictRedisObjectDestructor /* val destructor */
403};
404
405/* Keylist hash table type has unencoded redis objects as keys and
406 * lists as values. It's used for blocking operations (BLPOP) and to
407 * map swapped keys to a list of clients waiting for this keys to be loaded. */
408dictType keylistDictType = {
409 dictObjHash, /* hash function */
410 NULL, /* key dup */
411 NULL, /* val dup */
412 dictObjKeyCompare, /* key compare */
413 dictRedisObjectDestructor, /* key destructor */
414 dictListDestructor /* val destructor */
415};
416
417int htNeedsResize(dict *dict) {
418 long long size, used;
419
420 size = dictSlots(dict);
421 used = dictSize(dict);
422 return (size && used && size > DICT_HT_INITIAL_SIZE &&
423 (used*100/size < REDIS_HT_MINFILL));
424}
425
426/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
427 * we resize the hash table to save memory */
428void tryResizeHashTables(void) {
429 int j;
430
431 for (j = 0; j < server.dbnum; j++) {
432 if (htNeedsResize(server.db[j].dict))
433 dictResize(server.db[j].dict);
434 if (htNeedsResize(server.db[j].expires))
435 dictResize(server.db[j].expires);
436 }
437}
438
439/* Our hash table implementation performs rehashing incrementally while
440 * we write/read from the hash table. Still if the server is idle, the hash
441 * table will use two tables for a long time. So we try to use 1 millisecond
442 * of CPU time at every serverCron() loop in order to rehash some key. */
443void incrementallyRehash(void) {
444 int j;
445
446 for (j = 0; j < server.dbnum; j++) {
447 if (dictIsRehashing(server.db[j].dict)) {
448 dictRehashMilliseconds(server.db[j].dict,1);
449 break; /* already used our millisecond for this loop... */
450 }
451 }
452}
453
454/* This function is called once a background process of some kind terminates,
455 * as we want to avoid resizing the hash tables when there is a child in order
456 * to play well with copy-on-write (otherwise when a resize happens lots of
457 * memory pages are copied). The goal of this function is to update the ability
458 * for dict.c to resize the hash tables accordingly to the fact we have o not
459 * running childs. */
460void updateDictResizePolicy(void) {
461 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
462 dictEnableResize();
463 else
464 dictDisableResize();
465}
466
467/* ======================= Cron: called every 100 ms ======================== */
468
bcf2995c 469/* Try to expire a few timed out keys. The algorithm used is adaptive and
470 * will use few CPU cycles if there are few expiring keys, otherwise
471 * it will get more aggressive to avoid that too much memory is used by
472 * keys that can be removed from the keyspace. */
473void activeExpireCycle(void) {
474 int j;
475
476 for (j = 0; j < server.dbnum; j++) {
477 int expired;
478 redisDb *db = server.db+j;
479
480 /* Continue to expire if at the end of the cycle more than 25%
481 * of the keys were expired. */
482 do {
483 long num = dictSize(db->expires);
484 time_t now = time(NULL);
485
486 expired = 0;
487 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
488 num = REDIS_EXPIRELOOKUPS_PER_CRON;
489 while (num--) {
490 dictEntry *de;
491 time_t t;
492
493 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
494 t = (time_t) dictGetEntryVal(de);
495 if (now > t) {
496 sds key = dictGetEntryKey(de);
497 robj *keyobj = createStringObject(key,sdslen(key));
498
499 propagateExpire(db,keyobj);
500 dbDelete(db,keyobj);
501 decrRefCount(keyobj);
502 expired++;
503 server.stat_expiredkeys++;
504 }
505 }
506 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
507 }
508}
509
165346ca 510void updateLRUClock(void) {
511 server.lruclock = (time(NULL)/REDIS_LRU_CLOCK_RESOLUTION) &
512 REDIS_LRU_CLOCK_MAX;
513}
bcf2995c 514
e2641e09 515int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
516 int j, loops = server.cronloops++;
517 REDIS_NOTUSED(eventLoop);
518 REDIS_NOTUSED(id);
519 REDIS_NOTUSED(clientData);
520
521 /* We take a cached value of the unix time in the global state because
522 * with virtual memory and aging there is to store the current time
523 * in objects at every object access, and accuracy is not needed.
524 * To access a global var is faster than calling time(NULL) */
525 server.unixtime = time(NULL);
ef59a8bc 526 /* We have just 22 bits per object for LRU information.
165346ca 527 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
528 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
e2641e09 529 *
165346ca 530 * Note that even if this will wrap after 1.5 years it's not a problem,
ef59a8bc 531 * everything will still work but just some object will appear younger
165346ca 532 * to Redis. But for this to happen a given object should never be touched
533 * for 1.5 years.
534 *
535 * Note that you can change the resolution altering the
536 * REDIS_LRU_CLOCK_RESOLUTION define.
e2641e09 537 */
165346ca 538 updateLRUClock();
e2641e09 539
540 /* We received a SIGTERM, shutting down here in a safe way, as it is
541 * not ok doing so inside the signal handler. */
542 if (server.shutdown_asap) {
543 if (prepareForShutdown() == REDIS_OK) exit(0);
544 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
545 }
546
547 /* Show some info about non-empty databases */
548 for (j = 0; j < server.dbnum; j++) {
549 long long size, used, vkeys;
550
551 size = dictSlots(server.db[j].dict);
552 used = dictSize(server.db[j].dict);
553 vkeys = dictSize(server.db[j].expires);
554 if (!(loops % 50) && (used || vkeys)) {
555 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
556 /* dictPrintStats(server.dict); */
557 }
558 }
559
560 /* We don't want to resize the hash tables while a bacground saving
561 * is in progress: the saving child is created using fork() that is
562 * implemented with a copy-on-write semantic in most modern systems, so
563 * if we resize the HT while there is the saving child at work actually
564 * a lot of memory movements in the parent will cause a lot of pages
565 * copied. */
566 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
567 if (!(loops % 10)) tryResizeHashTables();
568 if (server.activerehashing) incrementallyRehash();
569 }
570
571 /* Show information about connected clients */
572 if (!(loops % 50)) {
573 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
574 listLength(server.clients)-listLength(server.slaves),
575 listLength(server.slaves),
ca734d17 576 zmalloc_used_memory());
e2641e09 577 }
578
579 /* Close connections of timedout clients */
5fa95ad7 580 if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients)
e2641e09 581 closeTimedoutClients();
582
583 /* Check if a background saving or AOF rewrite in progress terminated */
584 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
585 int statloc;
586 pid_t pid;
587
588 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
589 if (pid == server.bgsavechildpid) {
590 backgroundSaveDoneHandler(statloc);
591 } else {
592 backgroundRewriteDoneHandler(statloc);
593 }
594 updateDictResizePolicy();
595 }
596 } else {
597 /* If there is not a background saving in progress check if
598 * we have to save now */
599 time_t now = time(NULL);
600 for (j = 0; j < server.saveparamslen; j++) {
601 struct saveparam *sp = server.saveparams+j;
602
603 if (server.dirty >= sp->changes &&
604 now-server.lastsave > sp->seconds) {
605 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
606 sp->changes, sp->seconds);
607 rdbSaveBackground(server.dbfilename);
608 break;
609 }
610 }
611 }
612
bcf2995c 613 /* Expire a few keys per cycle, only if this is a master.
614 * On slaves we wait for DEL operations synthesized by the master
615 * in order to guarantee a strict consistency. */
616 if (server.masterhost == NULL) activeExpireCycle();
e2641e09 617
618 /* Swap a few keys on disk if we are over the memory limit and VM
619 * is enbled. Try to free objects from the free list first. */
620 if (vmCanSwapOut()) {
ca734d17 621 while (server.vm_enabled && zmalloc_used_memory() >
622 server.vm_max_memory)
623 {
a9b18e54 624 int retval = (server.vm_max_threads == 0) ?
e2641e09 625 vmSwapOneObjectBlocking() :
626 vmSwapOneObjectThreaded();
627 if (retval == REDIS_ERR && !(loops % 300) &&
ca734d17 628 zmalloc_used_memory() >
e2641e09 629 (server.vm_max_memory+server.vm_max_memory/10))
630 {
631 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
632 }
633 /* Note that when using threade I/O we free just one object,
634 * because anyway when the I/O thread in charge to swap this
635 * object out will finish, the handler of completed jobs
636 * will try to swap more objects if we are still out of memory. */
637 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
638 }
639 }
640
f4aa600b 641 /* Replication cron function -- used to reconnect to master and
642 * to detect transfer failures. */
62ec599c 643 if (!(loops % 10)) replicationCron();
f4aa600b 644
e2641e09 645 return 100;
646}
647
648/* This function gets called every time Redis is entering the
649 * main loop of the event driven library, that is, before to sleep
650 * for ready file descriptors. */
651void beforeSleep(struct aeEventLoop *eventLoop) {
652 REDIS_NOTUSED(eventLoop);
a4ce7581
PN
653 listNode *ln;
654 redisClient *c;
e2641e09 655
656 /* Awake clients that got all the swapped keys they requested */
657 if (server.vm_enabled && listLength(server.io_ready_clients)) {
658 listIter li;
e2641e09 659
660 listRewind(server.io_ready_clients,&li);
661 while((ln = listNext(&li))) {
a4ce7581 662 c = ln->value;
e2641e09 663 struct redisCommand *cmd;
664
665 /* Resume the client. */
666 listDelNode(server.io_ready_clients,ln);
667 c->flags &= (~REDIS_IO_WAIT);
668 server.vm_blocked_clients--;
669 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
670 readQueryFromClient, c);
671 cmd = lookupCommand(c->argv[0]->ptr);
672 redisAssert(cmd != NULL);
673 call(c,cmd);
674 resetClient(c);
675 /* There may be more data to process in the input buffer. */
676 if (c->querybuf && sdslen(c->querybuf) > 0)
677 processInputBuffer(c);
678 }
679 }
a4ce7581
PN
680
681 /* Try to process pending commands for clients that were just unblocked. */
682 while (listLength(server.unblocked_clients)) {
683 ln = listFirst(server.unblocked_clients);
684 redisAssert(ln != NULL);
685 c = ln->value;
686 listDelNode(server.unblocked_clients,ln);
687
688 /* Process remaining data in the input buffer. */
689 if (c->querybuf && sdslen(c->querybuf) > 0)
690 processInputBuffer(c);
691 }
692
e2641e09 693 /* Write the AOF buffer on disk */
694 flushAppendOnlyFile();
695}
696
697/* =========================== Server initialization ======================== */
698
699void createSharedObjects(void) {
700 int j;
701
702 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
703 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
704 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
705 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
706 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
707 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
708 shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n"));
709 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
710 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
711 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
712 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
713 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
714 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
715 "-ERR Operation against a key holding the wrong kind of value\r\n"));
716 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
717 "-ERR no such key\r\n"));
718 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
719 "-ERR syntax error\r\n"));
720 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
721 "-ERR source and destination objects are the same\r\n"));
722 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
723 "-ERR index out of range\r\n"));
97e7f8ae 724 shared.loadingerr = createObject(REDIS_STRING,sdsnew(
725 "-LOADING Redis is loading the dataset in memory\r\n"));
e2641e09 726 shared.space = createObject(REDIS_STRING,sdsnew(" "));
727 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
728 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
729 shared.select0 = createStringObject("select 0\r\n",10);
730 shared.select1 = createStringObject("select 1\r\n",10);
731 shared.select2 = createStringObject("select 2\r\n",10);
732 shared.select3 = createStringObject("select 3\r\n",10);
733 shared.select4 = createStringObject("select 4\r\n",10);
734 shared.select5 = createStringObject("select 5\r\n",10);
735 shared.select6 = createStringObject("select 6\r\n",10);
736 shared.select7 = createStringObject("select 7\r\n",10);
737 shared.select8 = createStringObject("select 8\r\n",10);
738 shared.select9 = createStringObject("select 9\r\n",10);
739 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
740 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
741 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
742 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
743 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
744 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
745 shared.mbulk3 = createStringObject("*3\r\n",4);
746 shared.mbulk4 = createStringObject("*4\r\n",4);
747 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
748 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
749 shared.integers[j]->encoding = REDIS_ENCODING_INT;
750 }
751}
752
753void initServerConfig() {
e2641e09 754 server.port = REDIS_SERVERPORT;
a5639e7d 755 server.bindaddr = NULL;
5d10923f 756 server.unixsocket = NULL;
a5639e7d
PN
757 server.ipfd = -1;
758 server.sofd = -1;
759 server.dbnum = REDIS_DEFAULT_DBNUM;
e2641e09 760 server.verbosity = REDIS_VERBOSE;
761 server.maxidletime = REDIS_MAXIDLETIME;
762 server.saveparams = NULL;
97e7f8ae 763 server.loading = 0;
e2641e09 764 server.logfile = NULL; /* NULL = log on standard output */
e2641e09 765 server.glueoutputbuf = 1;
766 server.daemonize = 0;
767 server.appendonly = 0;
768 server.appendfsync = APPENDFSYNC_EVERYSEC;
769 server.no_appendfsync_on_rewrite = 0;
770 server.lastfsync = time(NULL);
771 server.appendfd = -1;
772 server.appendseldb = -1; /* Make sure the first time will not match */
773 server.pidfile = zstrdup("/var/run/redis.pid");
774 server.dbfilename = zstrdup("dump.rdb");
775 server.appendfilename = zstrdup("appendonly.aof");
776 server.requirepass = NULL;
777 server.rdbcompression = 1;
778 server.activerehashing = 1;
779 server.maxclients = 0;
5fa95ad7 780 server.bpop_blocked_clients = 0;
e2641e09 781 server.maxmemory = 0;
165346ca 782 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
783 server.maxmemory_samples = 3;
e2641e09 784 server.vm_enabled = 0;
785 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
786 server.vm_page_size = 256; /* 256 bytes per page */
787 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
788 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
789 server.vm_max_threads = 4;
790 server.vm_blocked_clients = 0;
791 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
792 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
793 server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
794 server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
96ffb2fe 795 server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
e2641e09 796 server.shutdown_asap = 0;
797
95506e46 798 updateLRUClock();
e2641e09 799 resetServerSaveParams();
800
801 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
802 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
803 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
804 /* Replication related */
805 server.isslave = 0;
806 server.masterauth = NULL;
807 server.masterhost = NULL;
808 server.masterport = 6379;
809 server.master = NULL;
810 server.replstate = REDIS_REPL_NONE;
4ebfc455 811 server.repl_serve_stale_data = 1;
e2641e09 812
813 /* Double constants initialization */
814 R_Zero = 0.0;
815 R_PosInf = 1.0/R_Zero;
816 R_NegInf = -1.0/R_Zero;
817 R_Nan = R_Zero/R_Zero;
8d3e063a 818
819 /* Command table -- we intiialize it here as it is part of the
820 * initial configuration, since command names may be changed via
821 * redis.conf using the rename-command directive. */
822 server.commands = dictCreate(&commandTableDictType,NULL);
823 populateCommandTable();
824 server.delCommand = lookupCommandByCString("del");
825 server.multiCommand = lookupCommandByCString("multi");
e2641e09 826}
827
828void initServer() {
829 int j;
830
831 signal(SIGHUP, SIG_IGN);
832 signal(SIGPIPE, SIG_IGN);
833 setupSigSegvAction();
834
0e5441d8 835 server.mainthread = pthread_self();
e2641e09 836 server.clients = listCreate();
837 server.slaves = listCreate();
838 server.monitors = listCreate();
a4ce7581 839 server.unblocked_clients = listCreate();
e2641e09 840 createSharedObjects();
841 server.el = aeCreateEventLoop();
842 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
89381980
PN
843 server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr);
844 if (server.ipfd == ANET_ERR) {
845 redisLog(REDIS_WARNING, "Opening port: %s", server.neterr);
846 exit(1);
a5639e7d 847 }
5d10923f
PN
848 if (server.unixsocket != NULL) {
849 unlink(server.unixsocket); /* don't care if this fails */
850 server.sofd = anetUnixServer(server.neterr,server.unixsocket);
a5639e7d
PN
851 if (server.sofd == ANET_ERR) {
852 redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
853 exit(1);
854 }
c61e6925 855 }
a5639e7d
PN
856 if (server.ipfd < 0 && server.sofd < 0) {
857 redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
e2641e09 858 exit(1);
859 }
860 for (j = 0; j < server.dbnum; j++) {
861 server.db[j].dict = dictCreate(&dbDictType,NULL);
862 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
863 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
864 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
865 if (server.vm_enabled)
866 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
867 server.db[j].id = j;
868 }
869 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
870 server.pubsub_patterns = listCreate();
871 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
872 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
873 server.cronloops = 0;
874 server.bgsavechildpid = -1;
875 server.bgrewritechildpid = -1;
876 server.bgrewritebuf = sdsempty();
877 server.aofbuf = sdsempty();
878 server.lastsave = time(NULL);
879 server.dirty = 0;
880 server.stat_numcommands = 0;
881 server.stat_numconnections = 0;
882 server.stat_expiredkeys = 0;
883 server.stat_starttime = time(NULL);
53eeeaff 884 server.stat_keyspace_misses = 0;
885 server.stat_keyspace_hits = 0;
e2641e09 886 server.unixtime = time(NULL);
887 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
a5639e7d 888 if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
ab17b909 889 acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
a5639e7d 890 if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
ab17b909 891 acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");
e2641e09 892
893 if (server.appendonly) {
894 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
895 if (server.appendfd == -1) {
896 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
897 strerror(errno));
898 exit(1);
899 }
900 }
901
902 if (server.vm_enabled) vmInit();
903}
904
1b1f47c9 905/* Populates the Redis Command Table starting from the hard coded list
906 * we have on top of redis.c file. */
907void populateCommandTable(void) {
908 int j;
909 int numcommands = sizeof(readonlyCommandTable)/sizeof(struct redisCommand);
910
911 for (j = 0; j < numcommands; j++) {
912 struct redisCommand *c = readonlyCommandTable+j;
913 int retval;
e2641e09 914
1b1f47c9 915 retval = dictAdd(server.commands, sdsnew(c->name), c);
916 assert(retval == DICT_OK);
917 }
e2641e09 918}
919
920/* ====================== Commands lookup and execution ===================== */
921
1b1f47c9 922struct redisCommand *lookupCommand(sds name) {
923 return dictFetchValue(server.commands, name);
924}
925
926struct redisCommand *lookupCommandByCString(char *s) {
927 struct redisCommand *cmd;
928 sds name = sdsnew(s);
929
930 cmd = dictFetchValue(server.commands, name);
931 sdsfree(name);
932 return cmd;
e2641e09 933}
934
935/* Call() is the core of Redis execution of a command */
936void call(redisClient *c, struct redisCommand *cmd) {
937 long long dirty;
938
939 dirty = server.dirty;
940 cmd->proc(c);
941 dirty = server.dirty-dirty;
942
943 if (server.appendonly && dirty)
944 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
945 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
946 listLength(server.slaves))
947 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
948 if (listLength(server.monitors))
949 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
950 server.stat_numcommands++;
951}
952
953/* If this function gets called we already read a whole
954 * command, argments are in the client argv/argc fields.
955 * processCommand() execute the command or prepare the
956 * server for a bulk read from the client.
957 *
958 * If 1 is returned the client is still alive and valid and
959 * and other operations can be performed by the caller. Otherwise
960 * if 0 is returned the client was destroied (i.e. after QUIT). */
961int processCommand(redisClient *c) {
962 struct redisCommand *cmd;
963
941c9fa2
PN
964 /* The QUIT command is handled separately. Normal command procs will
965 * go through checking for replication and QUIT will cause trouble
966 * when FORCE_REPLICATION is enabled and would be implemented in
967 * a regular command proc. */
e2641e09 968 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
941c9fa2 969 addReply(c,shared.ok);
5e78edb3 970 c->flags |= REDIS_CLOSE_AFTER_REPLY;
cd8788f2 971 return REDIS_ERR;
e2641e09 972 }
973
974 /* Now lookup the command and check ASAP about trivial error conditions
975 * such wrong arity, bad command name and so forth. */
976 cmd = lookupCommand(c->argv[0]->ptr);
977 if (!cmd) {
3ab20376
PN
978 addReplyErrorFormat(c,"unknown command '%s'",
979 (char*)c->argv[0]->ptr);
cd8788f2 980 return REDIS_OK;
e2641e09 981 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
982 (c->argc < -cmd->arity)) {
3ab20376
PN
983 addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
984 cmd->name);
cd8788f2 985 return REDIS_OK;
e2641e09 986 }
e2641e09 987
988 /* Check if the user is authenticated */
989 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
3ab20376 990 addReplyError(c,"operation not permitted");
cd8788f2 991 return REDIS_OK;
e2641e09 992 }
993
1dd10ca2 994 /* Handle the maxmemory directive.
995 *
996 * First we try to free some memory if possible (if there are volatile
997 * keys in the dataset). If there are not the only thing we can do
998 * is returning an error. */
999 if (server.maxmemory) freeMemoryIfNeeded();
e2641e09 1000 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
ca734d17 1001 zmalloc_used_memory() > server.maxmemory)
e2641e09 1002 {
3ab20376 1003 addReplyError(c,"command not allowed when used memory > 'maxmemory'");
cd8788f2 1004 return REDIS_OK;
e2641e09 1005 }
1006
1007 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1008 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
1009 &&
1010 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
1011 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
3ab20376 1012 addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
cd8788f2 1013 return REDIS_OK;
e2641e09 1014 }
1015
4ebfc455 1016 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1017 * we are a slave with a broken link with master. */
1018 if (server.masterhost && server.replstate != REDIS_REPL_CONNECTED &&
1019 server.repl_serve_stale_data == 0 &&
1020 cmd->proc != infoCommand && cmd->proc != slaveofCommand)
1021 {
1022 addReplyError(c,
1023 "link with MASTER is down and slave-serve-stale-data is set to no");
1024 return REDIS_OK;
1025 }
1026
97e7f8ae 1027 /* Loading DB? Return an error if the command is not INFO */
1028 if (server.loading && cmd->proc != infoCommand) {
1029 addReply(c, shared.loadingerr);
1030 return REDIS_OK;
1031 }
1032
e2641e09 1033 /* Exec the command */
1034 if (c->flags & REDIS_MULTI &&
1035 cmd->proc != execCommand && cmd->proc != discardCommand &&
1036 cmd->proc != multiCommand && cmd->proc != watchCommand)
1037 {
1038 queueMultiCommand(c,cmd);
1039 addReply(c,shared.queued);
1040 } else {
1041 if (server.vm_enabled && server.vm_max_threads > 0 &&
9da6caac 1042 blockClientOnSwappedKeys(c,cmd)) return REDIS_ERR;
e2641e09 1043 call(c,cmd);
1044 }
cd8788f2 1045 return REDIS_OK;
e2641e09 1046}
1047
1048/*================================== Shutdown =============================== */
1049
1050int prepareForShutdown() {
1051 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
1052 /* Kill the saving child if there is a background saving in progress.
1053 We want to avoid race conditions, for instance our saving child may
1054 overwrite the synchronous saving did by SHUTDOWN. */
1055 if (server.bgsavechildpid != -1) {
1056 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
1057 kill(server.bgsavechildpid,SIGKILL);
1058 rdbRemoveTempFile(server.bgsavechildpid);
1059 }
1060 if (server.appendonly) {
1061 /* Append only file: fsync() the AOF and exit */
1062 aof_fsync(server.appendfd);
1063 if (server.vm_enabled) unlink(server.vm_swap_file);
d8a717fb 1064 } else if (server.saveparamslen > 0) {
e2641e09 1065 /* Snapshotting. Perform a SYNC SAVE and exit */
695fe874 1066 if (rdbSave(server.dbfilename) != REDIS_OK) {
e2641e09 1067 /* Ooops.. error saving! The best we can do is to continue
1068 * operating. Note that if there was a background saving process,
1069 * in the next cron() Redis will be notified that the background
1070 * saving aborted, handling special stuff like slaves pending for
1071 * synchronization... */
1072 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
1073 return REDIS_ERR;
1074 }
d8a717fb
RP
1075 } else {
1076 redisLog(REDIS_WARNING,"Not saving DB.");
e2641e09 1077 }
695fe874 1078 if (server.daemonize) unlink(server.pidfile);
e2641e09 1079 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
1080 return REDIS_OK;
1081}
1082
1083/*================================== Commands =============================== */
1084
1085void authCommand(redisClient *c) {
1086 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
1087 c->authenticated = 1;
1088 addReply(c,shared.ok);
1089 } else {
1090 c->authenticated = 0;
3ab20376 1091 addReplyError(c,"invalid password");
e2641e09 1092 }
1093}
1094
1095void pingCommand(redisClient *c) {
1096 addReply(c,shared.pong);
1097}
1098
1099void echoCommand(redisClient *c) {
1100 addReplyBulk(c,c->argv[1]);
1101}
1102
1103/* Convert an amount of bytes into a human readable string in the form
1104 * of 100B, 2G, 100M, 4K, and so forth. */
1105void bytesToHuman(char *s, unsigned long long n) {
1106 double d;
1107
1108 if (n < 1024) {
1109 /* Bytes */
1110 sprintf(s,"%lluB",n);
1111 return;
1112 } else if (n < (1024*1024)) {
1113 d = (double)n/(1024);
1114 sprintf(s,"%.2fK",d);
1115 } else if (n < (1024LL*1024*1024)) {
1116 d = (double)n/(1024*1024);
1117 sprintf(s,"%.2fM",d);
1118 } else if (n < (1024LL*1024*1024*1024)) {
1119 d = (double)n/(1024LL*1024*1024);
1120 sprintf(s,"%.2fG",d);
1121 }
1122}
1123
1124/* Create the string returned by the INFO command. This is decoupled
1125 * by the INFO command itself as we need to report the same information
1126 * on memory corruption problems. */
1127sds genRedisInfoString(void) {
1128 sds info;
1129 time_t uptime = time(NULL)-server.stat_starttime;
1130 int j;
1131 char hmem[64];
2b00385d 1132 struct rusage self_ru, c_ru;
1133
1134 getrusage(RUSAGE_SELF, &self_ru);
1135 getrusage(RUSAGE_CHILDREN, &c_ru);
e2641e09 1136
ca734d17 1137 bytesToHuman(hmem,zmalloc_used_memory());
e2641e09 1138 info = sdscatprintf(sdsempty(),
1139 "redis_version:%s\r\n"
1140 "redis_git_sha1:%s\r\n"
1141 "redis_git_dirty:%d\r\n"
1142 "arch_bits:%s\r\n"
1143 "multiplexing_api:%s\r\n"
1144 "process_id:%ld\r\n"
1145 "uptime_in_seconds:%ld\r\n"
1146 "uptime_in_days:%ld\r\n"
ef59a8bc 1147 "lru_clock:%ld\r\n"
2b00385d 1148 "used_cpu_sys:%.2f\r\n"
1149 "used_cpu_user:%.2f\r\n"
1150 "used_cpu_sys_childrens:%.2f\r\n"
1151 "used_cpu_user_childrens:%.2f\r\n"
e2641e09 1152 "connected_clients:%d\r\n"
1153 "connected_slaves:%d\r\n"
1154 "blocked_clients:%d\r\n"
1155 "used_memory:%zu\r\n"
1156 "used_memory_human:%s\r\n"
539fb438 1157 "used_memory_rss:%zu\r\n"
eddb388e 1158 "mem_fragmentation_ratio:%.2f\r\n"
13b37159 1159 "use_tcmalloc:%d\r\n"
97e7f8ae 1160 "loading:%d\r\n"
1161 "aof_enabled:%d\r\n"
e2641e09 1162 "changes_since_last_save:%lld\r\n"
1163 "bgsave_in_progress:%d\r\n"
1164 "last_save_time:%ld\r\n"
1165 "bgrewriteaof_in_progress:%d\r\n"
1166 "total_connections_received:%lld\r\n"
1167 "total_commands_processed:%lld\r\n"
1168 "expired_keys:%lld\r\n"
53eeeaff 1169 "keyspace_hits:%lld\r\n"
1170 "keyspace_misses:%lld\r\n"
e2641e09 1171 "hash_max_zipmap_entries:%zu\r\n"
1172 "hash_max_zipmap_value:%zu\r\n"
1173 "pubsub_channels:%ld\r\n"
1174 "pubsub_patterns:%u\r\n"
1175 "vm_enabled:%d\r\n"
1176 "role:%s\r\n"
1177 ,REDIS_VERSION,
1178 redisGitSHA1(),
1179 strtol(redisGitDirty(),NULL,10) > 0,
1180 (sizeof(long) == 8) ? "64" : "32",
1181 aeGetApiName(),
1182 (long) getpid(),
1183 uptime,
1184 uptime/(3600*24),
ef59a8bc 1185 (unsigned long) server.lruclock,
2b00385d 1186 (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000,
1187 (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000,
1188 (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000,
1189 (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000,
e2641e09 1190 listLength(server.clients)-listLength(server.slaves),
1191 listLength(server.slaves),
5fa95ad7 1192 server.bpop_blocked_clients,
a3e60027 1193 zmalloc_used_memory(),
ca734d17 1194 hmem,
539fb438 1195 zmalloc_get_rss(),
eddb388e 1196 zmalloc_get_fragmentation_ratio(),
13b37159 1197#ifdef USE_TCMALLOC
1198 1,
1199#else
1200 0,
1201#endif
97e7f8ae 1202 server.loading,
1203 server.appendonly,
e2641e09 1204 server.dirty,
1205 server.bgsavechildpid != -1,
1206 server.lastsave,
1207 server.bgrewritechildpid != -1,
1208 server.stat_numconnections,
1209 server.stat_numcommands,
1210 server.stat_expiredkeys,
53eeeaff 1211 server.stat_keyspace_hits,
1212 server.stat_keyspace_misses,
e2641e09 1213 server.hash_max_zipmap_entries,
1214 server.hash_max_zipmap_value,
1215 dictSize(server.pubsub_channels),
1216 listLength(server.pubsub_patterns),
1217 server.vm_enabled != 0,
1218 server.masterhost == NULL ? "master" : "slave"
1219 );
1220 if (server.masterhost) {
1221 info = sdscatprintf(info,
1222 "master_host:%s\r\n"
1223 "master_port:%d\r\n"
1224 "master_link_status:%s\r\n"
1225 "master_last_io_seconds_ago:%d\r\n"
12ebe2ac 1226 "master_sync_in_progress:%d\r\n"
e2641e09 1227 ,server.masterhost,
1228 server.masterport,
1229 (server.replstate == REDIS_REPL_CONNECTED) ?
1230 "up" : "down",
12ebe2ac 1231 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1,
1232 server.replstate == REDIS_REPL_TRANSFER
e2641e09 1233 );
12ebe2ac 1234
1235 if (server.replstate == REDIS_REPL_TRANSFER) {
1236 info = sdscatprintf(info,
1237 "master_sync_left_bytes:%ld\r\n"
1238 "master_sync_last_io_seconds_ago:%d\r\n"
1239 ,(long)server.repl_transfer_left,
1240 (int)(time(NULL)-server.repl_transfer_lastio)
1241 );
1242 }
e2641e09 1243 }
1244 if (server.vm_enabled) {
1245 lockThreadedIO();
1246 info = sdscatprintf(info,
1247 "vm_conf_max_memory:%llu\r\n"
1248 "vm_conf_page_size:%llu\r\n"
1249 "vm_conf_pages:%llu\r\n"
1250 "vm_stats_used_pages:%llu\r\n"
1251 "vm_stats_swapped_objects:%llu\r\n"
1252 "vm_stats_swappin_count:%llu\r\n"
1253 "vm_stats_swappout_count:%llu\r\n"
1254 "vm_stats_io_newjobs_len:%lu\r\n"
1255 "vm_stats_io_processing_len:%lu\r\n"
1256 "vm_stats_io_processed_len:%lu\r\n"
1257 "vm_stats_io_active_threads:%lu\r\n"
1258 "vm_stats_blocked_clients:%lu\r\n"
1259 ,(unsigned long long) server.vm_max_memory,
1260 (unsigned long long) server.vm_page_size,
1261 (unsigned long long) server.vm_pages,
1262 (unsigned long long) server.vm_stats_used_pages,
1263 (unsigned long long) server.vm_stats_swapped_objects,
1264 (unsigned long long) server.vm_stats_swapins,
1265 (unsigned long long) server.vm_stats_swapouts,
1266 (unsigned long) listLength(server.io_newjobs),
1267 (unsigned long) listLength(server.io_processing),
1268 (unsigned long) listLength(server.io_processed),
1269 (unsigned long) server.io_active_threads,
1270 (unsigned long) server.vm_blocked_clients
1271 );
1272 unlockThreadedIO();
1273 }
97e7f8ae 1274 if (server.loading) {
1275 double perc;
1276 time_t eta, elapsed;
1277 off_t remaining_bytes = server.loading_total_bytes-
1278 server.loading_loaded_bytes;
1279
1280 perc = ((double)server.loading_loaded_bytes /
1281 server.loading_total_bytes) * 100;
1282
1283 elapsed = time(NULL)-server.loading_start_time;
1284 if (elapsed == 0) {
1285 eta = 1; /* A fake 1 second figure if we don't have enough info */
1286 } else {
1287 eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
1288 }
1289
1290 info = sdscatprintf(info,
1291 "loading_start_time:%ld\r\n"
1292 "loading_total_bytes:%llu\r\n"
1293 "loading_loaded_bytes:%llu\r\n"
1294 "loading_loaded_perc:%.2f\r\n"
1295 "loading_eta_seconds:%ld\r\n"
1296 ,(unsigned long) server.loading_start_time,
1297 (unsigned long long) server.loading_total_bytes,
1298 (unsigned long long) server.loading_loaded_bytes,
1299 perc,
1300 eta
1301 );
1302 }
e2641e09 1303 for (j = 0; j < server.dbnum; j++) {
1304 long long keys, vkeys;
1305
1306 keys = dictSize(server.db[j].dict);
1307 vkeys = dictSize(server.db[j].expires);
1308 if (keys || vkeys) {
1309 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
1310 j, keys, vkeys);
1311 }
1312 }
1313 return info;
1314}
1315
1316void infoCommand(redisClient *c) {
1317 sds info = genRedisInfoString();
1318 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
1319 (unsigned long)sdslen(info)));
1320 addReplySds(c,info);
1321 addReply(c,shared.crlf);
1322}
1323
1324void monitorCommand(redisClient *c) {
1325 /* ignore MONITOR if aleady slave or in monitor mode */
1326 if (c->flags & REDIS_SLAVE) return;
1327
1328 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
1329 c->slaveseldb = 0;
1330 listAddNodeTail(server.monitors,c);
1331 addReply(c,shared.ok);
1332}
1333
1334/* ============================ Maxmemory directive ======================== */
1335
e2641e09 1336/* This function gets called when 'maxmemory' is set on the config file to limit
1337 * the max memory used by the server, and we are out of memory.
1338 * This function will try to, in order:
1339 *
1340 * - Free objects from the free list
1341 * - Try to remove keys with an EXPIRE set
1342 *
1343 * It is not possible to free enough memory to reach used-memory < maxmemory
1344 * the server will start refusing commands that will enlarge even more the
1345 * memory usage.
1346 */
1347void freeMemoryIfNeeded(void) {
165346ca 1348 /* Remove keys accordingly to the active policy as long as we are
1349 * over the memory limit. */
5402c426 1350 if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return;
1351
ca734d17 1352 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
e2641e09 1353 int j, k, freed = 0;
1354
165346ca 1355 for (j = 0; j < server.dbnum; j++) {
10c12171 1356 long bestval = 0; /* just to prevent warning */
165346ca 1357 sds bestkey = NULL;
1358 struct dictEntry *de;
1359 redisDb *db = server.db+j;
1360 dict *dict;
1361
1362 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1363 server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
1364 {
1365 dict = server.db[j].dict;
1366 } else {
1367 dict = server.db[j].expires;
1368 }
1369 if (dictSize(dict) == 0) continue;
1370
1371 /* volatile-random and allkeys-random policy */
1372 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
1373 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
1374 {
1375 de = dictGetRandomKey(dict);
1376 bestkey = dictGetEntryKey(de);
1377 }
1378
1379 /* volatile-lru and allkeys-lru policy */
1380 else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1381 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1382 {
1383 for (k = 0; k < server.maxmemory_samples; k++) {
1384 sds thiskey;
1385 long thisval;
1386 robj *o;
1387
1388 de = dictGetRandomKey(dict);
1389 thiskey = dictGetEntryKey(de);
0c2f75c6 1390 /* When policy is volatile-lru we need an additonal lookup
1391 * to locate the real key, as dict is set to db->expires. */
1392 if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1393 de = dictFind(db->dict, thiskey);
165346ca 1394 o = dictGetEntryVal(de);
1395 thisval = estimateObjectIdleTime(o);
1396
1397 /* Higher idle time is better candidate for deletion */
1398 if (bestkey == NULL || thisval > bestval) {
1399 bestkey = thiskey;
1400 bestval = thisval;
1401 }
1402 }
1403 }
1404
1405 /* volatile-ttl */
1406 else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
1407 for (k = 0; k < server.maxmemory_samples; k++) {
1408 sds thiskey;
1409 long thisval;
1410
1411 de = dictGetRandomKey(dict);
1412 thiskey = dictGetEntryKey(de);
1413 thisval = (long) dictGetEntryVal(de);
1414
1415 /* Expire sooner (minor expire unix timestamp) is better
1416 * candidate for deletion */
1417 if (bestkey == NULL || thisval < bestval) {
1418 bestkey = thiskey;
1419 bestval = thisval;
1420 }
1421 }
1422 }
1423
1424 /* Finally remove the selected key. */
1425 if (bestkey) {
1426 robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
1427 dbDelete(db,keyobj);
1428 server.stat_expiredkeys++;
1429 decrRefCount(keyobj);
1430 freed++;
1431 }
1432 }
1433 if (!freed) return; /* nothing to free... */
1434 }
1435
1436 while(0) {
1437 int j, k, freed = 0;
e2641e09 1438 for (j = 0; j < server.dbnum; j++) {
1439 int minttl = -1;
357d3673 1440 sds minkey = NULL;
1441 robj *keyobj = NULL;
e2641e09 1442 struct dictEntry *de;
1443
1444 if (dictSize(server.db[j].expires)) {
1445 freed = 1;
1446 /* From a sample of three keys drop the one nearest to
1447 * the natural expire */
1448 for (k = 0; k < 3; k++) {
1449 time_t t;
1450
1451 de = dictGetRandomKey(server.db[j].expires);
1452 t = (time_t) dictGetEntryVal(de);
1453 if (minttl == -1 || t < minttl) {
1454 minkey = dictGetEntryKey(de);
1455 minttl = t;
1456 }
1457 }
357d3673 1458 keyobj = createStringObject(minkey,sdslen(minkey));
1459 dbDelete(server.db+j,keyobj);
3856f147 1460 server.stat_expiredkeys++;
357d3673 1461 decrRefCount(keyobj);
e2641e09 1462 }
1463 }
1464 if (!freed) return; /* nothing to free... */
1465 }
1466}
1467
1468/* =================================== Main! ================================ */
1469
1470#ifdef __linux__
1471int linuxOvercommitMemoryValue(void) {
1472 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
1473 char buf[64];
1474
1475 if (!fp) return -1;
1476 if (fgets(buf,64,fp) == NULL) {
1477 fclose(fp);
1478 return -1;
1479 }
1480 fclose(fp);
1481
1482 return atoi(buf);
1483}
1484
1485void linuxOvercommitMemoryWarning(void) {
1486 if (linuxOvercommitMemoryValue() == 0) {
1487 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.");
1488 }
1489}
1490#endif /* __linux__ */
1491
695fe874 1492void createPidFile(void) {
1493 /* Try to write the pid file in a best-effort way. */
1494 FILE *fp = fopen(server.pidfile,"w");
1495 if (fp) {
1496 fprintf(fp,"%d\n",getpid());
1497 fclose(fp);
1498 }
1499}
1500
e2641e09 1501void daemonize(void) {
1502 int fd;
e2641e09 1503
1504 if (fork() != 0) exit(0); /* parent exits */
1505 setsid(); /* create a new session */
1506
1507 /* Every output goes to /dev/null. If Redis is daemonized but
1508 * the 'logfile' is set to 'stdout' in the configuration file
1509 * it will not log at all. */
1510 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
1511 dup2(fd, STDIN_FILENO);
1512 dup2(fd, STDOUT_FILENO);
1513 dup2(fd, STDERR_FILENO);
1514 if (fd > STDERR_FILENO) close(fd);
1515 }
e2641e09 1516}
1517
1518void version() {
1519 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
1520 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1521 exit(0);
1522}
1523
1524void usage() {
1525 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
1526 fprintf(stderr," ./redis-server - (read config from stdin)\n");
1527 exit(1);
1528}
1529
1530int main(int argc, char **argv) {
1531 time_t start;
1532
1533 initServerConfig();
e2641e09 1534 if (argc == 2) {
1535 if (strcmp(argv[1], "-v") == 0 ||
1536 strcmp(argv[1], "--version") == 0) version();
1537 if (strcmp(argv[1], "--help") == 0) usage();
1538 resetServerSaveParams();
1539 loadServerConfig(argv[1]);
1540 } else if ((argc > 2)) {
1541 usage();
1542 } else {
1543 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'");
1544 }
1545 if (server.daemonize) daemonize();
1546 initServer();
695fe874 1547 if (server.daemonize) createPidFile();
e2641e09 1548 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
1549#ifdef __linux__
1550 linuxOvercommitMemoryWarning();
1551#endif
1552 start = time(NULL);
1553 if (server.appendonly) {
1554 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
1555 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
1556 } else {
1557 if (rdbLoad(server.dbfilename) == REDIS_OK)
1558 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
1559 }
a5639e7d
PN
1560 if (server.ipfd > 0)
1561 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
1562 if (server.sofd > 0)
5d10923f 1563 redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
e2641e09 1564 aeSetBeforeSleepProc(server.el,beforeSleep);
1565 aeMain(server.el);
1566 aeDeleteEventLoop(server.el);
1567 return 0;
1568}
1569
1570/* ============================= Backtrace support ========================= */
1571
1572#ifdef HAVE_BACKTRACE
1573void *getMcontextEip(ucontext_t *uc) {
1574#if defined(__FreeBSD__)
1575 return (void*) uc->uc_mcontext.mc_eip;
1576#elif defined(__dietlibc__)
1577 return (void*) uc->uc_mcontext.eip;
1578#elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
1579 #if __x86_64__
1580 return (void*) uc->uc_mcontext->__ss.__rip;
1581 #else
1582 return (void*) uc->uc_mcontext->__ss.__eip;
1583 #endif
1584#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
1585 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
1586 return (void*) uc->uc_mcontext->__ss.__rip;
1587 #else
1588 return (void*) uc->uc_mcontext->__ss.__eip;
1589 #endif
3688d7f3 1590#elif defined(__i386__)
1591 return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
1592#elif defined(__X86_64__) || defined(__x86_64__)
1593 return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
e2641e09 1594#elif defined(__ia64__) /* Linux IA64 */
1595 return (void*) uc->uc_mcontext.sc_ip;
1596#else
1597 return NULL;
1598#endif
1599}
1600
1601void segvHandler(int sig, siginfo_t *info, void *secret) {
1602 void *trace[100];
1603 char **messages = NULL;
1604 int i, trace_size = 0;
1605 ucontext_t *uc = (ucontext_t*) secret;
1606 sds infostring;
da47440d 1607 struct sigaction act;
e2641e09 1608 REDIS_NOTUSED(info);
1609
1610 redisLog(REDIS_WARNING,
1611 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
1612 infostring = genRedisInfoString();
1613 redisLog(REDIS_WARNING, "%s",infostring);
1614 /* It's not safe to sdsfree() the returned string under memory
1615 * corruption conditions. Let it leak as we are going to abort */
1616
1617 trace_size = backtrace(trace, 100);
1618 /* overwrite sigaction with caller's address */
1619 if (getMcontextEip(uc) != NULL) {
1620 trace[1] = getMcontextEip(uc);
1621 }
1622 messages = backtrace_symbols(trace, trace_size);
1623
1624 for (i=1; i<trace_size; ++i)
1625 redisLog(REDIS_WARNING,"%s", messages[i]);
1626
1627 /* free(messages); Don't call free() with possibly corrupted memory. */
695fe874 1628 if (server.daemonize) unlink(server.pidfile);
da47440d 1629
1630 /* Make sure we exit with the right signal at the end. So for instance
1631 * the core will be dumped if enabled. */
1632 sigemptyset (&act.sa_mask);
1633 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1634 * is used. Otherwise, sa_handler is used */
1635 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1636 act.sa_handler = SIG_DFL;
1637 sigaction (sig, &act, NULL);
1638 kill(getpid(),sig);
e2641e09 1639}
1640
1641void sigtermHandler(int sig) {
1642 REDIS_NOTUSED(sig);
1643
1644 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
1645 server.shutdown_asap = 1;
1646}
1647
1648void setupSigSegvAction(void) {
1649 struct sigaction act;
1650
1651 sigemptyset (&act.sa_mask);
1652 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
1653 * is used. Otherwise, sa_handler is used */
1654 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
1655 act.sa_sigaction = segvHandler;
1656 sigaction (SIGSEGV, &act, NULL);
1657 sigaction (SIGBUS, &act, NULL);
1658 sigaction (SIGFPE, &act, NULL);
1659 sigaction (SIGILL, &act, NULL);
1660 sigaction (SIGBUS, &act, NULL);
1661
1662 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1663 act.sa_handler = sigtermHandler;
1664 sigaction (SIGTERM, &act, NULL);
1665 return;
1666}
1667
1668#else /* HAVE_BACKTRACE */
1669void setupSigSegvAction(void) {
1670}
1671#endif /* HAVE_BACKTRACE */
1672
1673/* The End */