]> git.saurik.com Git - redis.git/blob - src/redis.c
Merge remote branch 'pietern/cli-monitor'
[redis.git] / src / redis.c
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>
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>
54 #include <sys/resource.h>
55
56 /* Our shared "common" objects */
57
58 struct 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
64 double R_Zero, R_PosInf, R_NegInf, R_Nan;
65
66 /*================================= Globals ================================= */
67
68 /* Global vars */
69 struct redisServer server; /* server global state */
70 struct redisCommand *commandTable;
71 struct redisCommand readonlyCommandTable[] = {
72 {"get",getCommand,2,0,NULL,1,1,1},
73 {"set",setCommand,3,REDIS_CMD_DENYOOM,NULL,0,0,0},
74 {"setnx",setnxCommand,3,REDIS_CMD_DENYOOM,NULL,0,0,0},
75 {"setex",setexCommand,4,REDIS_CMD_DENYOOM,NULL,0,0,0},
76 {"append",appendCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
77 {"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},
80 {"setbit",setbitCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
81 {"getbit",getbitCommand,3,0,NULL,1,1,1},
82 {"setrange",setrangeCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
83 {"getrange",getrangeCommand,4,0,NULL,1,1,1},
84 {"substr",getrangeCommand,4,0,NULL,1,1,1},
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},
96 {"brpoplpush",brpoplpushCommand,4,REDIS_CMD_DENYOOM,NULL,1,2,1},
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},
104 {"rpoplpush",rpoplpushCommand,3,REDIS_CMD_DENYOOM,NULL,1,2,1},
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},
128 {"zrevrangebyscore",zrevrangebyscoreCommand,-4,0,NULL,1,1,1},
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},
132 {"zscore",zscoreCommand,3,0,NULL,1,1,1},
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}
191 };
192
193 /*============================ Utility functions ============================ */
194
195 void redisLog(int level, const char *fmt, ...) {
196 va_list ap;
197 FILE *fp;
198 char *c = ".-*#";
199 char buf[64];
200 time_t now;
201
202 if (level < server.verbosity) return;
203
204 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
205 if (!fp) return;
206
207 va_start(ap, fmt);
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);
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... */
224 void 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
236 void dictVanillaFree(void *privdata, void *val)
237 {
238 DICT_NOTUSED(privdata);
239 zfree(val);
240 }
241
242 void dictListDestructor(void *privdata, void *val)
243 {
244 DICT_NOTUSED(privdata);
245 listRelease((list*)val);
246 }
247
248 int 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
260 /* A case insensitive version used for the command lookup table. */
261 int dictSdsKeyCaseCompare(void *privdata, const void *key1,
262 const void *key2)
263 {
264 DICT_NOTUSED(privdata);
265
266 return strcasecmp(key1, key2) == 0;
267 }
268
269 void 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
277 void dictSdsDestructor(void *privdata, void *val)
278 {
279 DICT_NOTUSED(privdata);
280
281 sdsfree(val);
282 }
283
284 int 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
291 unsigned int dictObjHash(const void *key) {
292 const robj *o = key;
293 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
294 }
295
296 unsigned int dictSdsHash(const void *key) {
297 return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
298 }
299
300 unsigned int dictSdsCaseHash(const void *key) {
301 return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key));
302 }
303
304 int 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
322 unsigned 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 */
346 dictType 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) */
356 dictType zsetDictType = {
357 dictEncObjHash, /* hash function */
358 NULL, /* key dup */
359 NULL, /* val dup */
360 dictEncObjKeyCompare, /* key compare */
361 dictRedisObjectDestructor, /* key destructor */
362 NULL /* val destructor */
363 };
364
365 /* Db->dict, keys are sds strings, vals are Redis objects. */
366 dictType 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 */
376 dictType 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
385 /* Command table. sds string -> command struct pointer. */
386 dictType 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
395 /* Hash type hash table (note that small hashes are represented with zimpaps) */
396 dictType 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. */
408 dictType 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
417 int 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 */
428 void 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. */
443 void 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. */
460 void 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
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. */
473 void 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
510 void updateLRUClock(void) {
511 server.lruclock = (time(NULL)/REDIS_LRU_CLOCK_RESOLUTION) &
512 REDIS_LRU_CLOCK_MAX;
513 }
514
515 int 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);
526 /* We have just 22 bits per object for LRU information.
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.
529 *
530 * Note that even if this will wrap after 1.5 years it's not a problem,
531 * everything will still work but just some object will appear younger
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.
537 */
538 updateLRUClock();
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),
576 zmalloc_used_memory());
577 }
578
579 /* Close connections of timedout clients */
580 if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients)
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
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();
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()) {
621 while (server.vm_enabled && zmalloc_used_memory() >
622 server.vm_max_memory)
623 {
624 int retval = (server.vm_max_threads == 0) ?
625 vmSwapOneObjectBlocking() :
626 vmSwapOneObjectThreaded();
627 if (retval == REDIS_ERR && !(loops % 300) &&
628 zmalloc_used_memory() >
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
641 /* Replication cron function -- used to reconnect to master and
642 * to detect transfer failures. */
643 if (!(loops % 10)) replicationCron();
644
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. */
651 void beforeSleep(struct aeEventLoop *eventLoop) {
652 REDIS_NOTUSED(eventLoop);
653 listNode *ln;
654 redisClient *c;
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;
659
660 listRewind(server.io_ready_clients,&li);
661 while((ln = listNext(&li))) {
662 c = ln->value;
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 }
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
693 /* Write the AOF buffer on disk */
694 flushAppendOnlyFile();
695 }
696
697 /* =========================== Server initialization ======================== */
698
699 void 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"));
724 shared.loadingerr = createObject(REDIS_STRING,sdsnew(
725 "-LOADING Redis is loading the dataset in memory\r\n"));
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
753 void initServerConfig() {
754 server.port = REDIS_SERVERPORT;
755 server.bindaddr = NULL;
756 server.unixsocket = NULL;
757 server.ipfd = -1;
758 server.sofd = -1;
759 server.dbnum = REDIS_DEFAULT_DBNUM;
760 server.verbosity = REDIS_VERBOSE;
761 server.maxidletime = REDIS_MAXIDLETIME;
762 server.saveparams = NULL;
763 server.loading = 0;
764 server.logfile = NULL; /* NULL = log on standard output */
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;
780 server.bpop_blocked_clients = 0;
781 server.maxmemory = 0;
782 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
783 server.maxmemory_samples = 3;
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;
795 server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
796 server.shutdown_asap = 0;
797
798 updateLRUClock();
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;
811 server.repl_serve_stale_data = 1;
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;
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");
826 }
827
828 void initServer() {
829 int j;
830
831 signal(SIGHUP, SIG_IGN);
832 signal(SIGPIPE, SIG_IGN);
833 setupSigSegvAction();
834
835 server.mainthread = pthread_self();
836 server.clients = listCreate();
837 server.slaves = listCreate();
838 server.monitors = listCreate();
839 server.unblocked_clients = listCreate();
840 createSharedObjects();
841 server.el = aeCreateEventLoop();
842 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
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);
847 }
848 if (server.unixsocket != NULL) {
849 unlink(server.unixsocket); /* don't care if this fails */
850 server.sofd = anetUnixServer(server.neterr,server.unixsocket);
851 if (server.sofd == ANET_ERR) {
852 redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
853 exit(1);
854 }
855 }
856 if (server.ipfd < 0 && server.sofd < 0) {
857 redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
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);
884 server.stat_keyspace_misses = 0;
885 server.stat_keyspace_hits = 0;
886 server.unixtime = time(NULL);
887 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
888 if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
889 acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
890 if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
891 acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");
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
905 /* Populates the Redis Command Table starting from the hard coded list
906 * we have on top of redis.c file. */
907 void 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;
914
915 retval = dictAdd(server.commands, sdsnew(c->name), c);
916 assert(retval == DICT_OK);
917 }
918 }
919
920 /* ====================== Commands lookup and execution ===================== */
921
922 struct redisCommand *lookupCommand(sds name) {
923 return dictFetchValue(server.commands, name);
924 }
925
926 struct 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;
933 }
934
935 /* Call() is the core of Redis execution of a command */
936 void 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). */
961 int processCommand(redisClient *c) {
962 struct redisCommand *cmd;
963
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. */
968 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
969 addReply(c,shared.ok);
970 c->flags |= REDIS_CLOSE_AFTER_REPLY;
971 return REDIS_ERR;
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) {
978 addReplyErrorFormat(c,"unknown command '%s'",
979 (char*)c->argv[0]->ptr);
980 return REDIS_OK;
981 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
982 (c->argc < -cmd->arity)) {
983 addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
984 cmd->name);
985 return REDIS_OK;
986 }
987
988 /* Check if the user is authenticated */
989 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
990 addReplyError(c,"operation not permitted");
991 return REDIS_OK;
992 }
993
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();
1000 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
1001 zmalloc_used_memory() > server.maxmemory)
1002 {
1003 addReplyError(c,"command not allowed when used memory > 'maxmemory'");
1004 return REDIS_OK;
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) {
1012 addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1013 return REDIS_OK;
1014 }
1015
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
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
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 &&
1042 blockClientOnSwappedKeys(c,cmd)) return REDIS_ERR;
1043 call(c,cmd);
1044 }
1045 return REDIS_OK;
1046 }
1047
1048 /*================================== Shutdown =============================== */
1049
1050 int 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);
1064 } else if (server.saveparamslen > 0) {
1065 /* Snapshotting. Perform a SYNC SAVE and exit */
1066 if (rdbSave(server.dbfilename) != REDIS_OK) {
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 }
1075 } else {
1076 redisLog(REDIS_WARNING,"Not saving DB.");
1077 }
1078 if (server.daemonize) unlink(server.pidfile);
1079 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
1080 return REDIS_OK;
1081 }
1082
1083 /*================================== Commands =============================== */
1084
1085 void 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;
1091 addReplyError(c,"invalid password");
1092 }
1093 }
1094
1095 void pingCommand(redisClient *c) {
1096 addReply(c,shared.pong);
1097 }
1098
1099 void 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. */
1105 void 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. */
1127 sds genRedisInfoString(void) {
1128 sds info;
1129 time_t uptime = time(NULL)-server.stat_starttime;
1130 int j;
1131 char hmem[64];
1132 struct rusage self_ru, c_ru;
1133
1134 getrusage(RUSAGE_SELF, &self_ru);
1135 getrusage(RUSAGE_CHILDREN, &c_ru);
1136
1137 bytesToHuman(hmem,zmalloc_used_memory());
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"
1147 "lru_clock:%ld\r\n"
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"
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"
1157 "used_memory_rss:%zu\r\n"
1158 "mem_fragmentation_ratio:%.2f\r\n"
1159 "use_tcmalloc:%d\r\n"
1160 "loading:%d\r\n"
1161 "aof_enabled:%d\r\n"
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"
1169 "keyspace_hits:%lld\r\n"
1170 "keyspace_misses:%lld\r\n"
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),
1185 (unsigned long) server.lruclock,
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,
1190 listLength(server.clients)-listLength(server.slaves),
1191 listLength(server.slaves),
1192 server.bpop_blocked_clients,
1193 zmalloc_used_memory(),
1194 hmem,
1195 zmalloc_get_rss(),
1196 zmalloc_get_fragmentation_ratio(),
1197 #ifdef USE_TCMALLOC
1198 1,
1199 #else
1200 0,
1201 #endif
1202 server.loading,
1203 server.appendonly,
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,
1211 server.stat_keyspace_hits,
1212 server.stat_keyspace_misses,
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"
1226 "master_sync_in_progress:%d\r\n"
1227 ,server.masterhost,
1228 server.masterport,
1229 (server.replstate == REDIS_REPL_CONNECTED) ?
1230 "up" : "down",
1231 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1,
1232 server.replstate == REDIS_REPL_TRANSFER
1233 );
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 }
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 }
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 }
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
1316 void 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
1324 void 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
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 */
1347 void freeMemoryIfNeeded(void) {
1348 /* Remove keys accordingly to the active policy as long as we are
1349 * over the memory limit. */
1350 if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return;
1351
1352 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
1353 int j, k, freed = 0;
1354
1355 for (j = 0; j < server.dbnum; j++) {
1356 long bestval = 0; /* just to prevent warning */
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);
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);
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;
1438 for (j = 0; j < server.dbnum; j++) {
1439 int minttl = -1;
1440 sds minkey = NULL;
1441 robj *keyobj = NULL;
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 }
1458 keyobj = createStringObject(minkey,sdslen(minkey));
1459 dbDelete(server.db+j,keyobj);
1460 server.stat_expiredkeys++;
1461 decrRefCount(keyobj);
1462 }
1463 }
1464 if (!freed) return; /* nothing to free... */
1465 }
1466 }
1467
1468 /* =================================== Main! ================================ */
1469
1470 #ifdef __linux__
1471 int 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
1485 void 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
1492 void 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
1501 void daemonize(void) {
1502 int fd;
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 }
1516 }
1517
1518 void version() {
1519 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
1520 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1521 exit(0);
1522 }
1523
1524 void 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
1530 int main(int argc, char **argv) {
1531 time_t start;
1532
1533 initServerConfig();
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();
1547 if (server.daemonize) createPidFile();
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 }
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)
1563 redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
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
1573 void *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
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 */
1594 #elif defined(__ia64__) /* Linux IA64 */
1595 return (void*) uc->uc_mcontext.sc_ip;
1596 #else
1597 return NULL;
1598 #endif
1599 }
1600
1601 void 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;
1607 struct sigaction act;
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. */
1628 if (server.daemonize) unlink(server.pidfile);
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);
1639 }
1640
1641 void sigtermHandler(int sig) {
1642 REDIS_NOTUSED(sig);
1643
1644 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
1645 server.shutdown_asap = 1;
1646 }
1647
1648 void 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 */
1669 void setupSigSegvAction(void) {
1670 }
1671 #endif /* HAVE_BACKTRACE */
1672
1673 /* The End */