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