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