]> arthur.barton.de Git - netdata.git/blob - src/main.c
health parsing almost complete
[netdata.git] / src / main.c
1 #include "common.h"
2
3 extern void *cgroups_main(void *ptr);
4
5 void netdata_cleanup_and_exit(int ret) {
6     netdata_exit = 1;
7
8     error_log_limit_unlimited();
9
10     info("Called: netdata_cleanup_and_exit()");
11 #ifdef NETDATA_INTERNAL_CHECKS
12     rrdset_free_all();
13 #else
14     rrdset_save_all();
15 #endif
16     // kill_childs();
17
18     if(pidfile[0]) {
19         if(unlink(pidfile) != 0)
20             error("Cannot unlink pidfile '%s'.", pidfile);
21     }
22
23     info("NetData exiting. Bye bye...");
24     exit(ret);
25 }
26
27 struct netdata_static_thread {
28     char *name;
29
30     char *config_section;
31     char *config_name;
32
33     int enabled;
34
35     pthread_t *thread;
36
37     void (*init_routine) (void);
38     void *(*start_routine) (void *);
39 } static_threads[] = {
40 #ifdef INTERNAL_PLUGIN_NFACCT
41 // nfacct requires root access
42     // so, we build it as an external plugin with setuid to root
43     {"nfacct",              "plugins",  "nfacct",     1, NULL, NULL, nfacct_main},
44 #endif
45
46     {"tc",                 "plugins",   "tc",         1, NULL, NULL, tc_main},
47     {"idlejitter",         "plugins",   "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
48     {"proc",               "plugins",   "proc",       1, NULL, NULL, proc_main},
49     {"cgroups",            "plugins",   "cgroups",    1, NULL, NULL, cgroups_main},
50     {"plugins.d",           NULL,       NULL,         1, NULL, NULL, pluginsd_main},
51     {"check",               "plugins",  "checks",     0, NULL, NULL, checks_main},
52     {"web",                 NULL,       NULL,         1, NULL, NULL, socket_listen_main_multi_threaded},
53     {"web-single-threaded", NULL,       NULL,         0, NULL, NULL, socket_listen_main_single_threaded},
54     {NULL,                  NULL,       NULL,         0, NULL, NULL, NULL}
55 };
56
57 void web_server_threading_selection(void) {
58     int threaded = config_get_boolean("global", "multi threaded web server", 1);
59
60     int i;
61     for(i = 0; static_threads[i].name ; i++) {
62         if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
63             static_threads[i].enabled = threaded?1:0;
64
65         if(static_threads[i].start_routine == socket_listen_main_single_threaded)
66             static_threads[i].enabled = threaded?0:1;
67     }
68
69     web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
70
71     web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
72
73 #ifdef NETDATA_WITH_ZLIB
74     web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
75
76     char *s = config_get("global", "web compression strategy", "default");
77     if(!strcmp(s, "default"))
78         web_gzip_strategy = Z_DEFAULT_STRATEGY;
79     else if(!strcmp(s, "filtered"))
80         web_gzip_strategy = Z_FILTERED;
81     else if(!strcmp(s, "huffman only"))
82         web_gzip_strategy = Z_HUFFMAN_ONLY;
83     else if(!strcmp(s, "rle"))
84         web_gzip_strategy = Z_RLE;
85     else if(!strcmp(s, "fixed"))
86         web_gzip_strategy = Z_FIXED;
87     else {
88         error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
89         web_gzip_strategy = Z_DEFAULT_STRATEGY;
90     }
91
92     web_gzip_level = (int)config_get_number("global", "web compression level", 3);
93     if(web_gzip_level < 1) {
94         error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
95         web_gzip_level = 1;
96     }
97     else if(web_gzip_level > 9) {
98         error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
99         web_gzip_level = 9;
100     }
101 #endif /* NETDATA_WITH_ZLIB */
102 }
103
104
105 int killpid(pid_t pid, int sig)
106 {
107     int ret = -1;
108     debug(D_EXIT, "Request to kill pid %d", pid);
109
110     errno = 0;
111     if(kill(pid, 0) == -1) {
112         switch(errno) {
113             case ESRCH:
114                 error("Request to kill pid %d, but it is not running.", pid);
115                 break;
116
117             case EPERM:
118                 error("Request to kill pid %d, but I do not have enough permissions.", pid);
119                 break;
120
121             default:
122                 error("Request to kill pid %d, but I received an error.", pid);
123                 break;
124         }
125     }
126     else {
127         errno = 0;
128         ret = kill(pid, sig);
129         if(ret == -1) {
130             switch(errno) {
131                 case ESRCH:
132                     error("Cannot kill pid %d, but it is not running.", pid);
133                     break;
134
135                 case EPERM:
136                     error("Cannot kill pid %d, but I do not have enough permissions.", pid);
137                     break;
138
139                 default:
140                     error("Cannot kill pid %d, but I received an error.", pid);
141                     break;
142             }
143         }
144     }
145
146     return ret;
147 }
148
149 void kill_childs()
150 {
151     siginfo_t info;
152
153     struct web_client *w;
154     for(w = web_clients; w ; w = w->next) {
155         debug(D_EXIT, "Stopping web client %s", w->client_ip);
156         pthread_cancel(w->thread);
157         pthread_join(w->thread, NULL);
158     }
159
160     int i;
161     for (i = 0; static_threads[i].name != NULL ; i++) {
162         if(static_threads[i].thread) {
163             debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
164             pthread_cancel(*static_threads[i].thread);
165             pthread_join(*static_threads[i].thread, NULL);
166             static_threads[i].thread = NULL;
167         }
168     }
169
170     if(tc_child_pid) {
171         info("Killing tc-qos-helper procees");
172         if(killpid(tc_child_pid, SIGTERM) != -1)
173             waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
174     }
175     tc_child_pid = 0;
176
177     struct plugind *cd;
178     for(cd = pluginsd_root ; cd ; cd = cd->next) {
179         debug(D_EXIT, "Stopping %s plugin thread", cd->id);
180         pthread_cancel(cd->thread);
181         pthread_join(cd->thread, NULL);
182
183         if(cd->pid && !cd->obsolete) {
184             debug(D_EXIT, "killing %s plugin process", cd->id);
185             if(killpid(cd->pid, SIGTERM) != -1)
186                 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
187         }
188     }
189
190     // if, for any reason there is any child exited
191     // catch it here
192     waitid(P_PID, 0, &info, WEXITED|WNOHANG);
193
194     debug(D_EXIT, "All threads/childs stopped.");
195 }
196
197 struct option_def options[] = {
198     // opt description                                                       arg name                     default value
199     {'c', "Load alternate configuration file",                               "config_file",                          CONFIG_DIR "/" CONFIG_FILENAME},
200     {'D', "Disable fork into background",                                    NULL,                                   NULL},
201     {'h', "Display help message",                                            NULL,                                   NULL},
202     {'P', "File to save a pid while running",                                "FILE",                                 NULL},
203     {'i', "The IP address to listen to.",                                    "address",                              "All addresses"},
204     {'k', "Check daemon configuration.",                                     NULL,                                   NULL},
205     {'p', "Port to listen. Can be from 1 to 65535.",                         "port_number",                          "19999"},
206     {'s', "Path to access host /proc and /sys when running in a container.", "PATH",                                 NULL},
207     {'t', "The frequency in seconds, for data collection. \
208 Same as 'update every' config file option.",                                 "seconds",                              "1"},
209     {'u', "System username to run as.",                                      "username",                             "netdata"},
210     {'v', "Version of the program",                                          NULL,                                   NULL},
211     {'W', "vendor options.",                                                 "stacksize=<size>|unittest|debug_flag", NULL},
212 };
213
214 void help(int exitcode) {
215     FILE *stream;
216     if(exitcode == 0)
217         stream = stdout;
218     else
219         stream = stderr;
220
221     int num_opts = sizeof(options) / sizeof(struct option_def);
222     int i;
223     int max_len_arg = 0;
224
225     // Compute maximum argument length
226     for( i = 0; i < num_opts; i++ ) {
227         if(options[i].arg_name) {
228             int len_arg = (int)strlen(options[i].arg_name);
229             if(len_arg > max_len_arg) max_len_arg = len_arg;
230         }
231     }
232
233     fprintf(stream, "SYNOPSIS: netdata [options]\n");
234     fprintf(stream, "\n");
235     fprintf(stream, "Options:\n");
236
237     // Output options description.
238     for( i = 0; i < num_opts; i++ ) {
239         fprintf(stream, "  -%c %-*s  %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
240         if(options[i].default_value) {
241             fprintf(stream, " Default: %s\n", options[i].default_value);
242         } else {
243             fprintf(stream, "\n");
244         }
245     }
246
247     fflush(stream);
248     exit(exitcode);
249 }
250
251 // TODO: Remove this function with the nix major release.
252 void remove_option(int opt_index, int *argc, char **argv) {
253     int i = opt_index;
254     // remove the options.
255     do {
256         *argc = *argc - 1;
257         for(i = opt_index; i < *argc; i++) {
258             argv[i] = argv[i+1];
259         }
260         i = opt_index;
261     } while(argv[i][0] != '-' && opt_index >= *argc);
262 }
263
264
265 int main(int argc, char **argv)
266 {
267     int i, check_config = 0;
268     int config_loaded = 0;
269     int dont_fork = 0;
270     size_t wanted_stacksize = 0, stacksize = 0;
271     pthread_attr_t attr;
272
273     // global initialization
274     get_HZ();
275
276     // set the name for logging
277     program_name = "netdata";
278
279     // parse command line.
280
281     // parse depercated options
282     // TODO: Remove this block with the next major release.
283     {
284         i = 1;
285         while(i < argc) {
286             if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
287                 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
288                 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
289                 remove_option(i, &argc, argv);
290             }
291             else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
292                 dont_fork = 1;
293                 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
294                 remove_option(i, &argc, argv);
295             }
296             else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
297                 config_set("global", "host access prefix", argv[i+1]);
298                 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
299                 remove_option(i, &argc, argv);
300             }
301             else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
302                 config_set("global", "history", argv[i+1]);
303                 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
304                 remove_option(i, &argc, argv);
305             }
306             else i++;
307         }
308     }
309
310     // parse options
311     {
312         int num_opts = sizeof(options) / sizeof(struct option_def);
313         char optstring[(num_opts * 2) + 1];
314
315         int string_i = 0;
316         for( i = 0; i < num_opts; i++ ) {
317             optstring[string_i] = options[i].val;
318             string_i++;
319             if(options[i].arg_name) {
320                 optstring[string_i] = ':';
321                 string_i++;
322             }
323         }
324
325         int opt;
326         while( (opt = getopt(argc, argv, optstring)) != -1 ) {
327             switch(opt) {
328                 case 'c':
329                     if(load_config(optarg, 1) != 1) {
330                         error("Cannot load configuration file %s.", optarg);
331                         exit(1);
332                     }
333                     else {
334                         debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
335                         config_loaded = 1;
336                     }
337                     break;
338                 case 'D':
339                     dont_fork = 1;
340                     break;
341                 case 'h':
342                     help(0);
343                     break;
344                 case 'i':
345                     config_set("global", "bind to", optarg);
346                     break;
347                 case 'k':
348                     dont_fork = 1;
349                     check_config = 1;
350                     break;
351                 case 'P':
352                     strncpy(pidfile, optarg, FILENAME_MAX);
353                     pidfile[FILENAME_MAX] = '\0';
354                     break;
355                 case 'p':
356                     config_set("global", "default port", optarg);
357                     break;
358                 case 's':
359                     config_set("global", "host access prefix", optarg);
360                     break;
361                 case 't':
362                     config_set("global", "update every", optarg);
363                     break;
364                 case 'u':
365                     config_set("global", "run as user", optarg);
366                     break;
367                 case 'v':
368                     // TODO: Outsource version to makefile which can compute version from git.
369                     printf("netdata 1.2.1_master\n");
370                     return 0;
371                 case 'W':
372                     {
373                         char* stacksize_string = "stacksize=";
374                         char* debug_flags_string = "debug_flags=";
375                         if(strcmp(optarg, "unittest") == 0) {
376                             rrd_update_every = 1;
377                             if(run_all_mockup_tests()) exit(1);
378                             if(unit_test_storage()) exit(1);
379                             fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
380                             exit(0);
381                         } else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
382                             optarg += strlen(stacksize_string);
383                             config_set("global", "pthread stack size", optarg);
384                         } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
385                             optarg += strlen(debug_flags_string);
386                             config_set("global", "debug flags",  optarg);
387                             debug_flags = strtoull(optarg, NULL, 0);
388                         }
389                     }
390                     break;
391                 default: /* ? */
392                     help(1);
393                     break;
394             }
395         }
396     }
397
398     if(!config_loaded) load_config(NULL, 0);
399
400     // prepare configuration environment variables for the plugins
401     setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory"   , CONFIG_DIR) , 1);
402     setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory"  , PLUGINS_DIR), 1);
403     setenv("NETDATA_WEB_DIR"    , config_get("global", "web files directory", WEB_DIR)    , 1);
404     setenv("NETDATA_CACHE_DIR"  , config_get("global", "cache directory"    , CACHE_DIR)  , 1);
405     setenv("NETDATA_LIB_DIR"    , config_get("global", "lib directory"      , VARLIB_DIR) , 1);
406     setenv("NETDATA_LOG_DIR"    , config_get("global", "log directory"      , LOG_DIR)    , 1);
407     setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "")         , 1);
408     setenv("HOME"               , config_get("global", "home directory"     , CACHE_DIR)  , 1);
409
410     // disable buffering for python plugins
411     setenv("PYTHONUNBUFFERED", "1", 1);
412
413     // avoid flood calls to stat(/etc/localtime)
414     // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
415     setenv("TZ", ":/etc/localtime", 0);
416
417     {
418         char path[1024 + 1], *p = getenv("PATH");
419         if(!p) p = "/bin:/usr/bin";
420         snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
421         setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
422     }
423
424     // cd to /tmp to avoid any plugins writing files at random places
425     if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
426
427     char *user = NULL;
428     {
429         char *flags = config_get("global", "debug flags",  "0x00000000");
430         setenv("NETDATA_DEBUG_FLAGS", flags, 1);
431
432         debug_flags = strtoull(flags, NULL, 0);
433         debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
434
435         if(debug_flags != 0) {
436             struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
437             if(setrlimit(RLIMIT_CORE, &rl) != 0)
438                 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
439             prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
440         }
441
442         // --------------------------------------------------------------------
443
444 #ifdef MADV_MERGEABLE
445         enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
446 #else
447 #warning "Kernel memory deduplication (KSM) is not available"
448 #endif
449
450         // --------------------------------------------------------------------
451
452         global_host_prefix = config_get("global", "host access prefix", "");
453         setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
454
455         // --------------------------------------------------------------------
456
457         stdout_filename    = config_get("global", "debug log",  LOG_DIR "/debug.log");
458         stderr_filename    = config_get("global", "error log",  LOG_DIR "/error.log");
459         stdaccess_filename = config_get("global", "access log", LOG_DIR "/access.log");
460
461         error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
462         setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period"    , ""), 1);
463
464         error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
465         setenv("NETDATA_ERRORS_PER_PERIOD"     , config_get("global", "errors to trigger flood protection", ""), 1);
466
467         if(check_config) {
468             stdout_filename = stderr_filename = stdaccess_filename = "system";
469             error_log_throttle_period = 0;
470             error_log_errors_per_period = 0;
471         }
472
473         // --------------------------------------------------------------------
474
475         rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
476
477         // --------------------------------------------------------------------
478
479         {
480             char hostnamebuf[HOSTNAME_MAX + 1];
481             if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
482                 error("WARNING: Cannot get machine hostname.");
483             hostname = config_get("global", "hostname", hostnamebuf);
484             debug(D_OPTIONS, "hostname set to '%s'", hostname);
485         }
486
487         // --------------------------------------------------------------------
488
489         rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
490         if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
491             info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
492             rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
493         }
494         else {
495             debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
496         }
497
498         // --------------------------------------------------------------------
499
500         rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
501         if(rrd_update_every < 1 || rrd_update_every > 600) {
502             info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
503             rrd_update_every = UPDATE_EVERY;
504         }
505         else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
506
507         // let the plugins know the min update_every
508         {
509             char buf[16];
510             snprintfz(buf, 15, "%d", rrd_update_every);
511             setenv("NETDATA_UPDATE_EVERY", buf, 1);
512         }
513
514         // --------------------------------------------------------------------
515
516         // block signals while initializing threads.
517         // this causes the threads to block signals.
518         sigset_t sigset;
519         sigfillset(&sigset);
520
521         if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
522             error("Could not block signals for threads");
523         }
524
525         // Catch signals which we want to use
526         struct sigaction sa;
527         sigemptyset(&sa.sa_mask);
528         sigaddset(&sa.sa_mask, SIGINT);
529         sigaddset(&sa.sa_mask, SIGTERM);
530         sa.sa_handler = sig_handler_exit;
531         sa.sa_flags = 0;
532         if(sigaction(SIGINT, &sa, NULL) == -1) {
533             error("Failed to change signal handler for SIGINT");
534         }
535         if(sigaction(SIGTERM, &sa, NULL) == -1) {
536             error("Failed to change signal handler for SIGTERM");
537         }
538
539         sigemptyset(&sa.sa_mask);
540         sigaddset(&sa.sa_mask, SIGHUP);
541         sa.sa_handler = sig_handler_logrotate;
542         sa.sa_flags = 0;
543         if(sigaction(SIGHUP, &sa, NULL) == -1) {
544             error("Failed to change signal handler for SIGHUP");
545         }
546
547         // save database on SIGUSR1
548         sigemptyset(&sa.sa_mask);
549         sigaddset(&sa.sa_mask, SIGUSR1);
550         sa.sa_handler = sig_handler_save;
551         if(sigaction(SIGUSR1, &sa, NULL) == -1) {
552             error("Failed to change signal handler for SIGUSR1");
553         }
554
555         // Ignore SIGPIPE completely.
556         // INFO: If we add signals here we have to unblock them
557         // at popen.c when running a external plugin.
558         sigemptyset(&sa.sa_mask);
559         sigaddset(&sa.sa_mask, SIGPIPE);
560         sa.sa_handler = SIG_IGN;
561         if(sigaction(SIGPIPE, &sa, NULL) == -1) {
562             error("Failed to change signal handler for SIGPIPE");
563         }
564
565         // --------------------------------------------------------------------
566
567         i = pthread_attr_init(&attr);
568         if(i != 0)
569             fatal("pthread_attr_init() failed with code %d.", i);
570
571         i = pthread_attr_getstacksize(&attr, &stacksize);
572         if(i != 0)
573             fatal("pthread_attr_getstacksize() failed with code %d.", i);
574         else
575             debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
576
577         wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
578
579         // --------------------------------------------------------------------
580
581         for (i = 0; static_threads[i].name != NULL ; i++) {
582             struct netdata_static_thread *st = &static_threads[i];
583
584             if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
585             if(st->enabled && st->init_routine) st->init_routine();
586         }
587
588         // --------------------------------------------------------------------
589
590         // get the user we should run
591         // IMPORTANT: this is required before web_files_uid()
592         user = config_get("global", "run as user"    , (getuid() == 0)?NETDATA_USER:"");
593
594         // IMPORTANT: these have to run once, while single threaded
595         web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
596         web_files_gid();
597
598         // --------------------------------------------------------------------
599
600         create_listen_sockets();
601     }
602
603     // initialize the log files
604     open_all_log_files();
605
606 #ifdef NETDATA_INTERNAL_CHECKS
607     if(debug_flags != 0) {
608         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
609         if(setrlimit(RLIMIT_CORE, &rl) != 0)
610             info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
611         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
612     }
613 #endif /* NETDATA_INTERNAL_CHECKS */
614
615     // fork, switch user, create pid file, set process priority
616     if(become_daemon(dont_fork, user) == -1)
617         fatal("Cannot demonize myself.");
618
619     info("NetData started on pid %d", getpid());
620
621
622     // ------------------------------------------------------------------------
623     // get default pthread stack size
624
625     if(stacksize < wanted_stacksize) {
626         i = pthread_attr_setstacksize(&attr, wanted_stacksize);
627         if(i != 0)
628             fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
629         else
630             info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
631     }
632
633     // ------------------------------------------------------------------------
634     // initialize the registry
635
636     registry_init();
637
638     // ------------------------------------------------------------------------
639     // initialize health monitoring
640
641     health_init();
642
643     if(check_config)
644         exit(1);
645
646     // ------------------------------------------------------------------------
647     // spawn the threads
648
649     web_server_threading_selection();
650
651     for (i = 0; static_threads[i].name != NULL ; i++) {
652         struct netdata_static_thread *st = &static_threads[i];
653
654         if(st->enabled) {
655             st->thread = mallocz(sizeof(pthread_t));
656
657             info("Starting thread %s.", st->name);
658
659             if(pthread_create(st->thread, &attr, st->start_routine, NULL))
660                 error("failed to create new thread for %s.", st->name);
661
662             else if(pthread_detach(*st->thread))
663                 error("Cannot request detach of newly created %s thread.", st->name);
664         }
665         else info("Not starting thread %s.", st->name);
666     }
667
668     // ------------------------------------------------------------------------
669     // block signals while initializing threads.
670     sigset_t sigset;
671     sigfillset(&sigset);
672
673     if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
674         error("Could not unblock signals for threads");
675     }
676
677     // Handle flags set in the signal handler.
678     while(1) {
679         pause();
680         if(netdata_exit) {
681             info("Exit main loop of netdata.");
682             netdata_cleanup_and_exit(0);
683             exit(0);
684         }
685     }
686 }