3 extern void *cgroups_main(void *ptr);
5 void netdata_cleanup_and_exit(int ret) {
8 error_log_limit_unlimited();
10 debug(D_EXIT, "Called: netdata_cleanup_and_exit()");
17 if(unlink(pidfile) != 0)
18 error("Cannot unlink pidfile '%s'.", pidfile);
21 #ifdef NETDATA_INTERNAL_CHECKS
30 info("netdata exiting. Bye bye...");
34 struct netdata_static_thread static_threads[] = {
35 #ifdef INTERNAL_PLUGIN_NFACCT
36 // nfacct requires root access
37 // so, we build it as an external plugin with setuid to root
38 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
41 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
42 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
43 #if defined(__FreeBSD__)
44 {"freebsd", "plugins", "freebsd", 1, NULL, NULL, freebsd_main},
45 #elif defined(__APPLE__)
46 {"macos", "plugins", "macos", 1, NULL, NULL, macos_main},
48 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
49 {"diskspace", "plugins", "diskspace", 1, NULL, NULL, proc_diskspace_main},
50 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
51 #endif /* __FreeBSD__, __APPLE__*/
52 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
53 {"backends", NULL, NULL, 1, NULL, NULL, backends_main},
54 {"health", NULL, NULL, 1, NULL, NULL, health_main},
55 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
56 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
57 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
58 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
61 void web_server_threading_selection(void) {
62 int threaded = config_get_boolean("global", "multi threaded web server", 1);
65 for(i = 0; static_threads[i].name ; i++) {
66 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
67 static_threads[i].enabled = threaded?1:0;
69 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
70 static_threads[i].enabled = threaded?0:1;
73 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
75 respect_web_browser_do_not_track_policy = config_get_boolean("global", "respect web browser do not track policy", respect_web_browser_do_not_track_policy);
76 web_x_frame_options = config_get("global", "web x-frame-options header", "");
77 if(!*web_x_frame_options) web_x_frame_options = NULL;
79 #ifdef NETDATA_WITH_ZLIB
80 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
82 char *s = config_get("global", "web compression strategy", "default");
83 if(!strcmp(s, "default"))
84 web_gzip_strategy = Z_DEFAULT_STRATEGY;
85 else if(!strcmp(s, "filtered"))
86 web_gzip_strategy = Z_FILTERED;
87 else if(!strcmp(s, "huffman only"))
88 web_gzip_strategy = Z_HUFFMAN_ONLY;
89 else if(!strcmp(s, "rle"))
90 web_gzip_strategy = Z_RLE;
91 else if(!strcmp(s, "fixed"))
92 web_gzip_strategy = Z_FIXED;
94 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
95 web_gzip_strategy = Z_DEFAULT_STRATEGY;
98 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
99 if(web_gzip_level < 1) {
100 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
103 else if(web_gzip_level > 9) {
104 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
107 #endif /* NETDATA_WITH_ZLIB */
111 int killpid(pid_t pid, int sig)
114 debug(D_EXIT, "Request to kill pid %d", pid);
117 if(kill(pid, 0) == -1) {
120 error("Request to kill pid %d, but it is not running.", pid);
124 error("Request to kill pid %d, but I do not have enough permissions.", pid);
128 error("Request to kill pid %d, but I received an error.", pid);
134 ret = kill(pid, sig);
138 error("Cannot kill pid %d, but it is not running.", pid);
142 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
146 error("Cannot kill pid %d, but I received an error.", pid);
157 error_log_limit_unlimited();
161 struct web_client *w;
162 for(w = web_clients; w ; w = w->next) {
163 info("Stopping web client %s", w->client_ip);
164 pthread_cancel(w->thread);
166 // pthread_join(w->thread, NULL);
172 for (i = 0; static_threads[i].name != NULL ; i++) {
173 if(static_threads[i].enabled) {
174 info("Stopping %s thread", static_threads[i].name);
175 pthread_cancel(*static_threads[i].thread);
177 // pthread_join(*static_threads[i].thread, NULL);
179 static_threads[i].enabled = 0;
184 info("Killing tc-qos-helper process %d", tc_child_pid);
185 if(killpid(tc_child_pid, SIGTERM) != -1)
186 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
192 for(cd = pluginsd_root ; cd ; cd = cd->next) {
193 if(cd->enabled && !cd->obsolete) {
194 info("Stopping %s plugin thread", cd->id);
195 pthread_cancel(cd->thread);
198 info("killing %s plugin child process pid %d", cd->id, cd->pid);
199 if(killpid(cd->pid, SIGTERM) != -1)
200 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
209 // if, for any reason there is any child exited
211 info("Cleaning up an other children");
212 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
214 info("All threads/childs stopped.");
217 struct option_def options[] = {
218 // opt description arg name default value
219 { 'c', "Configuration file to load.", "filename", CONFIG_DIR "/" CONFIG_FILENAME},
220 { 'D', "Do not fork. Run in the foreground.", NULL, "run in the background"},
221 { 'h', "Display this help message.", NULL, NULL},
222 { 'P', "File to save a pid while running.", "filename", "do not save pid to a file"},
223 { 'i', "The IP address to listen to.", "IP", "all IP addresses IPv4 and IPv6"},
224 { 'k', "Check health configuration and exit.", NULL, NULL},
225 { 'p', "API/Web port to use.", "port", "19999"},
226 { 's', "Prefix for /proc and /sys (for containers).", "path", "no prefix"},
227 { 't', "The internal clock of netdata.", "seconds", "1"},
228 { 'u', "Run as user.", "username", "netdata"},
229 { 'v', "Print netdata version and exit.", NULL, NULL},
230 { 'W', "See Advanced options below.", "options", NULL},
233 void help(int exitcode) {
240 int num_opts = sizeof(options) / sizeof(struct option_def);
244 // Compute maximum argument length
245 for( i = 0; i < num_opts; i++ ) {
246 if(options[i].arg_name) {
247 int len_arg = (int)strlen(options[i].arg_name);
248 if(len_arg > max_len_arg) max_len_arg = len_arg;
252 if(max_len_arg > 30) max_len_arg = 30;
253 if(max_len_arg < 20) max_len_arg = 20;
255 fprintf(stream, "%s", "\n"
257 " |.-. .-. .-. .-. . netdata \n"
258 " | '-' '-' '-' '-' real-time performance monitoring, done right! \n"
259 " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
261 " Copyright (C) 2016-2017, Costa Tsaousis <costa@tsaousis.gr>\n"
262 " Released under GNU General Public License v3 or later.\n"
263 " All rights reserved.\n"
265 " Home Page : https://my-netdata.io\n"
266 " Source Code: https://github.com/firehol/netdata\n"
267 " Wiki / Docs: https://github.com/firehol/netdata/wiki\n"
268 " Support : https://github.com/firehol/netdata/issues\n"
269 " License : https://github.com/firehol/netdata/blob/master/LICENSE.md\n"
271 " Twitter : https://twitter.com/linuxnetdata\n"
272 " Facebook : https://www.facebook.com/linuxnetdata/\n"
274 " netdata is a https://firehol.org project.\n"
279 fprintf(stream, " SYNOPSIS: netdata [options]\n");
280 fprintf(stream, "\n");
281 fprintf(stream, " Options:\n\n");
283 // Output options description.
284 for( i = 0; i < num_opts; i++ ) {
285 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
286 if(options[i].default_value) {
287 fprintf(stream, "\n %c %-*s Default: %s\n", ' ', max_len_arg, "", options[i].default_value);
289 fprintf(stream, "\n");
291 fprintf(stream, "\n");
294 fprintf(stream, "\n Advanced options:\n\n"
295 " -W stacksize=N Set the stacksize (in bytes).\n\n"
296 " -W debug_flags=N Set runtime tracing to debug.log.\n\n"
297 " -W unittest Run internal unittests and exit.\n\n"
298 " -W simple-pattern pattern string\n"
299 " Check if string matches pattern and exit.\n\n"
302 fprintf(stream, "\n Signals netdata handles:\n\n"
303 " - HUP Close and reopen log files.\n"
304 " - USR1 Save internal DB to disk.\n"
305 " - USR2 Reload health configuration.\n"
313 // TODO: Remove this function with the nix major release.
314 void remove_option(int opt_index, int *argc, char **argv) {
316 // remove the options.
319 for(i = opt_index; i < *argc; i++) {
323 } while(argv[i][0] != '-' && opt_index >= *argc);
326 static const char *verify_required_directory(const char *dir) {
328 fatal("Cannot cd to directory '%s'", dir);
330 DIR *d = opendir(dir);
332 fatal("Cannot examine the contents of directory '%s'", dir);
338 int main(int argc, char **argv) {
339 char *hostname = "localhost";
340 int i, check_config = 0;
341 int config_loaded = 0;
343 size_t wanted_stacksize = 0, stacksize = 0;
346 // set the name for logging
347 program_name = "netdata";
349 // parse depercated options
350 // TODO: Remove this block with the next major release.
354 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
355 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
356 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
357 remove_option(i, &argc, argv);
359 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
361 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
362 remove_option(i, &argc, argv);
364 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
365 config_set("global", "host access prefix", argv[i+1]);
366 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
367 remove_option(i, &argc, argv);
369 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
370 config_set("global", "history", argv[i+1]);
371 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
372 remove_option(i, &argc, argv);
380 int num_opts = sizeof(options) / sizeof(struct option_def);
381 char optstring[(num_opts * 2) + 1];
384 for( i = 0; i < num_opts; i++ ) {
385 optstring[string_i] = options[i].val;
387 if(options[i].arg_name) {
388 optstring[string_i] = ':';
392 // terminate optstring
393 optstring[string_i] ='\0';
394 optstring[(num_opts *2)] ='\0';
397 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
400 if(load_config(optarg, 1) != 1) {
401 error("Cannot load configuration file %s.", optarg);
405 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
416 config_set("global", "bind to", optarg);
423 strncpy(pidfile, optarg, FILENAME_MAX);
424 pidfile[FILENAME_MAX] = '\0';
427 config_set("global", "default port", optarg);
430 config_set("global", "host access prefix", optarg);
433 config_set("global", "update every", optarg);
436 config_set("global", "run as user", optarg);
439 printf("%s %s\n", program_name, program_version);
443 char* stacksize_string = "stacksize=";
444 char* debug_flags_string = "debug_flags=";
445 if(strcmp(optarg, "unittest") == 0) {
446 rrd_update_every = 1;
447 if(run_all_mockup_tests()) exit(1);
448 if(unit_test_storage()) exit(1);
449 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
452 else if(strcmp(optarg, "simple-pattern") == 0) {
453 if(optind + 2 > argc) {
454 fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
455 " Checks if 'pattern' matches the given 'string'.\n"
456 " - 'pattern' can be one or more space separated words.\n"
457 " - each 'word' can contain one or more asterisks.\n"
458 " - words starting with '!' give negative matches.\n"
459 " - words are processed left to right\n"
463 " > match all veth interfaces, except veth0:\n"
465 " -W simple-pattern '!veth0 veth*' 'veth12'\n"
468 " > match all *.ext files directly in /path/:\n"
469 " (this will not match *.ext files in a subdir of /path/)\n"
471 " -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
477 const char *heystack = argv[optind];
478 const char *needle = argv[optind + 1];
480 SIMPLE_PATTERN *p = simple_pattern_create(heystack
481 , SIMPLE_PATTERN_EXACT);
482 int ret = simple_pattern_matches(p, needle);
483 simple_pattern_free(p);
486 fprintf(stdout, "RESULT: MATCHED - pattern '%s' matches '%s'\n", heystack, needle);
490 fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s'\n", heystack, needle);
494 else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
495 optarg += strlen(stacksize_string);
496 config_set("global", "pthread stack size", optarg);
498 else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
499 optarg += strlen(debug_flags_string);
500 config_set("global", "debug flags", optarg);
501 debug_flags = strtoull(optarg, NULL, 0);
513 // close all open file descriptors, except the standard ones
514 // the caller may have left open files (lxc-attach has this issue)
517 for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
518 if(fd_is_valid(fd)) close(fd);
523 load_config(NULL, 0);
526 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
528 setenv("MALLOC_ARENA_MAX", pmax, 1);
530 #if defined(HAVE_C_MALLOPT)
531 int i = config_get_number("global", "glibc malloc arena max for netdata", 1);
533 mallopt(M_ARENA_MAX, 1);
536 // prepare configuration environment variables for the plugins
538 netdata_configured_config_dir = config_get("global", "config directory", CONFIG_DIR);
539 netdata_configured_log_dir = config_get("global", "log directory", LOG_DIR);
540 netdata_configured_plugins_dir = config_get("global", "plugins directory", PLUGINS_DIR);
541 netdata_configured_web_dir = config_get("global", "web files directory", WEB_DIR);
542 netdata_configured_cache_dir = config_get("global", "cache directory", CACHE_DIR);
543 netdata_configured_varlib_dir = config_get("global", "lib directory", VARLIB_DIR);
544 netdata_configured_home_dir = config_get("global", "home directory", CACHE_DIR);
546 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(netdata_configured_config_dir), 1);
547 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(netdata_configured_plugins_dir), 1);
548 setenv("NETDATA_WEB_DIR" , verify_required_directory(netdata_configured_web_dir), 1);
549 setenv("NETDATA_CACHE_DIR" , verify_required_directory(netdata_configured_cache_dir), 1);
550 setenv("NETDATA_LIB_DIR" , verify_required_directory(netdata_configured_varlib_dir), 1);
551 setenv("NETDATA_LOG_DIR" , verify_required_directory(netdata_configured_log_dir), 1);
552 setenv("HOME" , verify_required_directory(netdata_configured_home_dir), 1);
554 netdata_configured_host_prefix = config_get("global", "host access prefix", "");
555 setenv("NETDATA_HOST_PREFIX", netdata_configured_host_prefix, 1);
557 // disable buffering for python plugins
558 setenv("PYTHONUNBUFFERED", "1", 1);
560 // avoid flood calls to stat(/etc/localtime)
561 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
562 setenv("TZ", ":/etc/localtime", 0);
564 // work while we are cd into config_dir
565 // to allow the plugins refer to their config
566 // files using relative filenames
567 if(chdir(netdata_configured_config_dir) == -1)
568 fatal("Cannot cd to '%s'", netdata_configured_config_dir);
570 char path[1024 + 1], *p = getenv("PATH");
571 if(!p) p = "/bin:/usr/bin";
572 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
573 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
575 p = getenv("PYTHONPATH");
577 setenv("PYTHONPATH", config_get("plugins", "PYTHONPATH environment variable", p), 1);
582 char *flags = config_get("global", "debug flags", "0x0000000000000000");
583 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
585 debug_flags = strtoull(flags, NULL, 0);
586 debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);
588 if(debug_flags != 0) {
589 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
590 if(setrlimit(RLIMIT_CORE, &rl) != 0)
591 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
593 #ifdef HAVE_SYS_PRCTL_H
594 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
598 // --------------------------------------------------------------------
600 #ifdef MADV_MERGEABLE
601 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
603 #warning "Kernel memory deduplication (KSM) is not available"
606 // --------------------------------------------------------------------
610 get_system_pid_max();
612 // --------------------------------------------------------------------
615 char filename[FILENAME_MAX + 1];
616 snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);
617 stdout_filename = config_get("global", "debug log", filename);
619 snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);
620 stderr_filename = config_get("global", "error log", filename);
622 snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);
623 stdaccess_filename = config_get("global", "access log", filename);
626 error_log_throttle_period_backup =
627 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
628 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
630 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
631 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
634 stdout_filename = stderr_filename = stdaccess_filename = "system";
635 error_log_throttle_period = 0;
636 error_log_errors_per_period = 0;
638 error_log_limit_unlimited();
640 // --------------------------------------------------------------------
642 default_localhost_rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(default_localhost_rrd_memory_mode)));
644 // --------------------------------------------------------------------
647 char hostnamebuf[HOSTNAME_MAX + 1];
648 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
649 error("WARNING: Cannot get machine hostname.");
650 hostname = config_get("global", "hostname", hostnamebuf);
651 debug(D_OPTIONS, "hostname set to '%s'", hostname);
652 setenv("NETDATA_HOSTNAME", hostname, 1);
655 // --------------------------------------------------------------------
657 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
658 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
659 error("Invalid history entries %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
660 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
663 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
666 // --------------------------------------------------------------------
668 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
669 if(rrd_update_every < 1 || rrd_update_every > 600) {
670 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
671 rrd_update_every = UPDATE_EVERY;
673 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
675 // let the plugins know the min update_every
678 snprintfz(buf, 15, "%d", rrd_update_every);
679 setenv("NETDATA_UPDATE_EVERY", buf, 1);
682 // --------------------------------------------------------------------
684 // block signals while initializing threads.
685 // this causes the threads to block signals.
688 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
689 error("Could not block signals for threads");
691 // Catch signals which we want to use
695 // ingore all signals while we run in a signal handler
696 sigfillset(&sa.sa_mask);
698 // INFO: If we add signals here we have to unblock them
699 // at popen.c when running a external plugin.
701 // Ignore SIGPIPE completely.
702 sa.sa_handler = SIG_IGN;
703 if(sigaction(SIGPIPE, &sa, NULL) == -1)
704 error("Failed to change signal handler for SIGPIPE");
706 sa.sa_handler = sig_handler_exit;
707 if(sigaction(SIGINT, &sa, NULL) == -1)
708 error("Failed to change signal handler for SIGINT");
710 sa.sa_handler = sig_handler_exit;
711 if(sigaction(SIGTERM, &sa, NULL) == -1)
712 error("Failed to change signal handler for SIGTERM");
714 sa.sa_handler = sig_handler_logrotate;
715 if(sigaction(SIGHUP, &sa, NULL) == -1)
716 error("Failed to change signal handler for SIGHUP");
718 // save database on SIGUSR1
719 sa.sa_handler = sig_handler_save;
720 if(sigaction(SIGUSR1, &sa, NULL) == -1)
721 error("Failed to change signal handler for SIGUSR1");
723 // reload health configuration on SIGUSR2
724 sa.sa_handler = sig_handler_reload_health;
725 if(sigaction(SIGUSR2, &sa, NULL) == -1)
726 error("Failed to change signal handler for SIGUSR2");
728 // --------------------------------------------------------------------
730 i = pthread_attr_init(&attr);
732 fatal("pthread_attr_init() failed with code %d.", i);
734 i = pthread_attr_getstacksize(&attr, &stacksize);
736 fatal("pthread_attr_getstacksize() failed with code %d.", i);
738 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
740 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
742 // --------------------------------------------------------------------
744 for (i = 0; static_threads[i].name != NULL ; i++) {
745 struct netdata_static_thread *st = &static_threads[i];
747 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
748 if(st->enabled && st->init_routine) st->init_routine();
751 // --------------------------------------------------------------------
753 // get the user we should run
754 // IMPORTANT: this is required before web_files_uid()
755 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
757 // IMPORTANT: these have to run once, while single threaded
758 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
761 // --------------------------------------------------------------------
764 create_listen_sockets();
767 // initialize the log files
768 open_all_log_files();
770 #ifdef NETDATA_INTERNAL_CHECKS
771 if(debug_flags != 0) {
772 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
773 if(setrlimit(RLIMIT_CORE, &rl) != 0)
774 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
775 #ifdef HAVE_SYS_PRCTL_H
776 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
779 #endif /* NETDATA_INTERNAL_CHECKS */
781 // fork, switch user, create pid file, set process priority
782 if(become_daemon(dont_fork, user) == -1)
783 fatal("Cannot daemonize myself.");
785 info("netdata started on pid %d.", getpid());
787 // ------------------------------------------------------------------------
788 // get default pthread stack size
790 if(stacksize < wanted_stacksize) {
791 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
793 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
795 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
798 // ------------------------------------------------------------------------
799 // initialize health monitoring
803 // ------------------------------------------------------------------------
804 // initialize the registry
808 // ------------------------------------------------------------------------
809 // initialize rrd host
816 // ------------------------------------------------------------------------
817 // enable log flood protection
819 error_log_limit_reset();
821 // ------------------------------------------------------------------------
824 web_server_threading_selection();
826 for (i = 0; static_threads[i].name != NULL ; i++) {
827 struct netdata_static_thread *st = &static_threads[i];
830 st->thread = mallocz(sizeof(pthread_t));
832 debug(D_SYSTEM, "Starting thread %s.", st->name);
834 if(pthread_create(st->thread, &attr, st->start_routine, st))
835 error("failed to create new thread for %s.", st->name);
837 else if(pthread_detach(*st->thread))
838 error("Cannot request detach of newly created %s thread.", st->name);
840 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
843 info("netdata initialization completed. Enjoy real-time performance monitoring!");
845 // ------------------------------------------------------------------------
846 // block signals while initializing threads.
850 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
851 error("Could not unblock signals for threads");
854 // Handle flags set in the signal handler.
858 debug(D_EXIT, "Exit main loop of netdata.");
859 netdata_cleanup_and_exit(0);