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