3 extern void *cgroups_main(void *ptr);
5 char *central_netdata_to_push_data = NULL;
7 void netdata_cleanup_and_exit(int ret) {
10 error_log_limit_unlimited();
12 debug(D_EXIT, "Called: netdata_cleanup_and_exit()");
19 if(unlink(pidfile) != 0)
20 error("Cannot unlink pidfile '%s'.", pidfile);
23 #ifdef NETDATA_INTERNAL_CHECKS
32 info("netdata exiting. Bye bye...");
36 struct netdata_static_thread static_threads[] = {
37 #ifdef INTERNAL_PLUGIN_NFACCT
38 // nfacct requires root access
39 // so, we build it as an external plugin with setuid to root
40 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
43 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
44 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
45 #if defined(__FreeBSD__)
46 {"freebsd", "plugins", "freebsd", 1, NULL, NULL, freebsd_main},
47 #elif defined(__APPLE__)
48 {"macos", "plugins", "macos", 1, NULL, NULL, macos_main},
50 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
51 {"diskspace", "plugins", "diskspace", 1, NULL, NULL, proc_diskspace_main},
52 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
53 #endif /* __FreeBSD__, __APPLE__*/
54 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
55 {"backends", NULL, NULL, 1, NULL, NULL, backends_main},
56 {"health", NULL, NULL, 1, NULL, NULL, health_main},
57 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
58 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
59 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
60 {"central-netdata-push",NULL, NULL, 0, NULL, NULL, central_netdata_push_thread},
61 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
64 void web_server_threading_selection(void) {
65 int multi_threaded = 0;
66 int single_threaded = 0;
67 int central_thread = 0;
69 if(!central_netdata_to_push_data) {
70 multi_threaded = config_get_boolean("global", "multi threaded web server", 1);
71 single_threaded = !multi_threaded;
75 info("Web servers are disabled - use the central netdata.");
79 for(i = 0; static_threads[i].name ; i++) {
80 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
81 static_threads[i].enabled = multi_threaded;
83 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
84 static_threads[i].enabled = single_threaded;
86 if(static_threads[i].start_routine == central_netdata_push_thread)
87 static_threads[i].enabled = central_thread;
90 if(central_netdata_to_push_data)
93 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
95 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);
96 web_x_frame_options = config_get("global", "web x-frame-options header", "");
97 if(!*web_x_frame_options) web_x_frame_options = NULL;
99 #ifdef NETDATA_WITH_ZLIB
100 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
102 char *s = config_get("global", "web compression strategy", "default");
103 if(!strcmp(s, "default"))
104 web_gzip_strategy = Z_DEFAULT_STRATEGY;
105 else if(!strcmp(s, "filtered"))
106 web_gzip_strategy = Z_FILTERED;
107 else if(!strcmp(s, "huffman only"))
108 web_gzip_strategy = Z_HUFFMAN_ONLY;
109 else if(!strcmp(s, "rle"))
110 web_gzip_strategy = Z_RLE;
111 else if(!strcmp(s, "fixed"))
112 web_gzip_strategy = Z_FIXED;
114 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
115 web_gzip_strategy = Z_DEFAULT_STRATEGY;
118 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
119 if(web_gzip_level < 1) {
120 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
123 else if(web_gzip_level > 9) {
124 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
127 #endif /* NETDATA_WITH_ZLIB */
131 int killpid(pid_t pid, int sig)
134 debug(D_EXIT, "Request to kill pid %d", pid);
137 if(kill(pid, 0) == -1) {
140 error("Request to kill pid %d, but it is not running.", pid);
144 error("Request to kill pid %d, but I do not have enough permissions.", pid);
148 error("Request to kill pid %d, but I received an error.", pid);
154 ret = kill(pid, sig);
158 error("Cannot kill pid %d, but it is not running.", pid);
162 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
166 error("Cannot kill pid %d, but I received an error.", pid);
177 error_log_limit_unlimited();
181 struct web_client *w;
182 for(w = web_clients; w ; w = w->next) {
183 info("Stopping web client %s", w->client_ip);
184 pthread_cancel(w->thread);
186 // pthread_join(w->thread, NULL);
192 for (i = 0; static_threads[i].name != NULL ; i++) {
193 if(static_threads[i].enabled) {
194 info("Stopping %s thread", static_threads[i].name);
195 pthread_cancel(*static_threads[i].thread);
197 // pthread_join(*static_threads[i].thread, NULL);
199 static_threads[i].enabled = 0;
204 info("Killing tc-qos-helper process %d", tc_child_pid);
205 if(killpid(tc_child_pid, SIGTERM) != -1)
206 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
212 for(cd = pluginsd_root ; cd ; cd = cd->next) {
213 if(cd->enabled && !cd->obsolete) {
214 info("Stopping %s plugin thread", cd->id);
215 pthread_cancel(cd->thread);
218 info("killing %s plugin child process pid %d", cd->id, cd->pid);
219 if(killpid(cd->pid, SIGTERM) != -1)
220 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
229 // if, for any reason there is any child exited
231 info("Cleaning up an other children");
232 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
234 info("All threads/childs stopped.");
237 struct option_def options[] = {
238 // opt description arg name default value
239 { 'c', "Configuration file to load.", "filename", CONFIG_DIR "/" CONFIG_FILENAME},
240 { 'D', "Do not fork. Run in the foreground.", NULL, "run in the background"},
241 { 'h', "Display this help message.", NULL, NULL},
242 { 'P', "File to save a pid while running.", "filename", "do not save pid to a file"},
243 { 'i', "The IP address to listen to.", "IP", "all IP addresses IPv4 and IPv6"},
244 { 'k', "Check health configuration and exit.", NULL, NULL},
245 { 'p', "API/Web port to use.", "port", "19999"},
246 { 's', "Prefix for /proc and /sys (for containers).", "path", "no prefix"},
247 { 't', "The internal clock of netdata.", "seconds", "1"},
248 { 'u', "Run as user.", "username", "netdata"},
249 { 'v', "Print netdata version and exit.", NULL, NULL},
250 { 'W', "See Advanced options below.", "options", NULL},
253 void help(int exitcode) {
260 int num_opts = sizeof(options) / sizeof(struct option_def);
264 // Compute maximum argument length
265 for( i = 0; i < num_opts; i++ ) {
266 if(options[i].arg_name) {
267 int len_arg = (int)strlen(options[i].arg_name);
268 if(len_arg > max_len_arg) max_len_arg = len_arg;
272 if(max_len_arg > 30) max_len_arg = 30;
273 if(max_len_arg < 20) max_len_arg = 20;
275 fprintf(stream, "%s", "\n"
277 " |.-. .-. .-. .-. . netdata \n"
278 " | '-' '-' '-' '-' real-time performance monitoring, done right! \n"
279 " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
281 " Copyright (C) 2016-2017, Costa Tsaousis <costa@tsaousis.gr>\n"
282 " Released under GNU General Public License v3 or later.\n"
283 " All rights reserved.\n"
285 " Home Page : https://my-netdata.io\n"
286 " Source Code: https://github.com/firehol/netdata\n"
287 " Wiki / Docs: https://github.com/firehol/netdata/wiki\n"
288 " Support : https://github.com/firehol/netdata/issues\n"
289 " License : https://github.com/firehol/netdata/blob/master/LICENSE.md\n"
291 " Twitter : https://twitter.com/linuxnetdata\n"
292 " Facebook : https://www.facebook.com/linuxnetdata/\n"
294 " netdata is a https://firehol.org project.\n"
299 fprintf(stream, " SYNOPSIS: netdata [options]\n");
300 fprintf(stream, "\n");
301 fprintf(stream, " Options:\n\n");
303 // Output options description.
304 for( i = 0; i < num_opts; i++ ) {
305 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
306 if(options[i].default_value) {
307 fprintf(stream, "\n %c %-*s Default: %s\n", ' ', max_len_arg, "", options[i].default_value);
309 fprintf(stream, "\n");
311 fprintf(stream, "\n");
314 fprintf(stream, "\n Advanced options:\n\n"
315 " -W stacksize=N Set the stacksize (in bytes).\n\n"
316 " -W debug_flags=N Set runtime tracing to debug.log.\n\n"
317 " -W unittest Run internal unittests and exit.\n\n"
318 " -W simple-pattern pattern string\n"
319 " Check if string matches pattern and exit.\n\n"
322 fprintf(stream, "\n Signals netdata handles:\n\n"
323 " - HUP Close and reopen log files.\n"
324 " - USR1 Save internal DB to disk.\n"
325 " - USR2 Reload health configuration.\n"
333 // TODO: Remove this function with the nix major release.
334 void remove_option(int opt_index, int *argc, char **argv) {
336 // remove the options.
339 for(i = opt_index; i < *argc; i++) {
343 } while(argv[i][0] != '-' && opt_index >= *argc);
346 static const char *verify_required_directory(const char *dir) {
348 fatal("Cannot cd to directory '%s'", dir);
350 DIR *d = opendir(dir);
352 fatal("Cannot examine the contents of directory '%s'", dir);
358 static void get_netdata_configured_directories() {
359 netdata_configured_config_dir = config_get("global", "config directory", CONFIG_DIR);
360 netdata_configured_log_dir = config_get("global", "log directory", LOG_DIR);
361 netdata_configured_plugins_dir = config_get("global", "plugins directory", PLUGINS_DIR);
362 netdata_configured_web_dir = config_get("global", "web files directory", WEB_DIR);
363 netdata_configured_cache_dir = config_get("global", "cache directory", CACHE_DIR);
364 netdata_configured_varlib_dir = config_get("global", "lib directory", VARLIB_DIR);
365 netdata_configured_home_dir = config_get("global", "home directory", CACHE_DIR);
368 int main(int argc, char **argv) {
369 char *hostname = "localhost";
370 int i, check_config = 0;
371 int config_loaded = 0;
373 size_t wanted_stacksize = 0, stacksize = 0;
376 // set the name for logging
377 program_name = "netdata";
379 // parse depercated options
380 // TODO: Remove this block with the next major release.
384 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
385 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
386 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
387 remove_option(i, &argc, argv);
389 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
391 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
392 remove_option(i, &argc, argv);
394 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
395 config_set("global", "host access prefix", argv[i+1]);
396 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
397 remove_option(i, &argc, argv);
399 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
400 config_set("global", "history", argv[i+1]);
401 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
402 remove_option(i, &argc, argv);
410 int num_opts = sizeof(options) / sizeof(struct option_def);
411 char optstring[(num_opts * 2) + 1];
414 for( i = 0; i < num_opts; i++ ) {
415 optstring[string_i] = options[i].val;
417 if(options[i].arg_name) {
418 optstring[string_i] = ':';
422 // terminate optstring
423 optstring[string_i] ='\0';
424 optstring[(num_opts *2)] ='\0';
427 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
430 if(load_config(optarg, 1) != 1) {
431 error("Cannot load configuration file %s.", optarg);
435 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
446 config_set("global", "bind to", optarg);
453 strncpy(pidfile, optarg, FILENAME_MAX);
454 pidfile[FILENAME_MAX] = '\0';
457 config_set("global", "default port", optarg);
460 config_set("global", "host access prefix", optarg);
463 config_set("global", "update every", optarg);
466 config_set("global", "run as user", optarg);
469 printf("%s %s\n", program_name, program_version);
473 char* stacksize_string = "stacksize=";
474 char* debug_flags_string = "debug_flags=";
475 if(strcmp(optarg, "unittest") == 0) {
476 default_rrd_update_every = 1;
477 if(!config_loaded) load_config(NULL, 0);
478 get_netdata_configured_directories();
480 rrd_init("unittest");
481 if(run_all_mockup_tests()) exit(1);
482 if(unit_test_storage()) exit(1);
483 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
486 else if(strcmp(optarg, "simple-pattern") == 0) {
487 if(optind + 2 > argc) {
488 fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
489 " Checks if 'pattern' matches the given 'string'.\n"
490 " - 'pattern' can be one or more space separated words.\n"
491 " - each 'word' can contain one or more asterisks.\n"
492 " - words starting with '!' give negative matches.\n"
493 " - words are processed left to right\n"
497 " > match all veth interfaces, except veth0:\n"
499 " -W simple-pattern '!veth0 veth*' 'veth12'\n"
502 " > match all *.ext files directly in /path/:\n"
503 " (this will not match *.ext files in a subdir of /path/)\n"
505 " -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
511 const char *heystack = argv[optind];
512 const char *needle = argv[optind + 1];
514 SIMPLE_PATTERN *p = simple_pattern_create(heystack
515 , SIMPLE_PATTERN_EXACT);
516 int ret = simple_pattern_matches(p, needle);
517 simple_pattern_free(p);
520 fprintf(stdout, "RESULT: MATCHED - pattern '%s' matches '%s'\n", heystack, needle);
524 fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s'\n", heystack, needle);
528 else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
529 optarg += strlen(stacksize_string);
530 config_set("global", "pthread stack size", optarg);
532 else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
533 optarg += strlen(debug_flags_string);
534 config_set("global", "debug flags", optarg);
535 debug_flags = strtoull(optarg, NULL, 0);
547 // close all open file descriptors, except the standard ones
548 // the caller may have left open files (lxc-attach has this issue)
551 for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
552 if(fd_is_valid(fd)) close(fd);
557 load_config(NULL, 0);
560 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
562 setenv("MALLOC_ARENA_MAX", pmax, 1);
564 #if defined(HAVE_C_MALLOPT)
565 i = (int)config_get_number("global", "glibc malloc arena max for netdata", 1);
567 mallopt(M_ARENA_MAX, 1);
570 // prepare configuration environment variables for the plugins
572 get_netdata_configured_directories();
574 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(netdata_configured_config_dir), 1);
575 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(netdata_configured_plugins_dir), 1);
576 setenv("NETDATA_WEB_DIR" , verify_required_directory(netdata_configured_web_dir), 1);
577 setenv("NETDATA_CACHE_DIR" , verify_required_directory(netdata_configured_cache_dir), 1);
578 setenv("NETDATA_LIB_DIR" , verify_required_directory(netdata_configured_varlib_dir), 1);
579 setenv("NETDATA_LOG_DIR" , verify_required_directory(netdata_configured_log_dir), 1);
580 setenv("HOME" , verify_required_directory(netdata_configured_home_dir), 1);
582 netdata_configured_host_prefix = config_get("global", "host access prefix", "");
583 setenv("NETDATA_HOST_PREFIX", netdata_configured_host_prefix, 1);
585 // disable buffering for python plugins
586 setenv("PYTHONUNBUFFERED", "1", 1);
588 // avoid flood calls to stat(/etc/localtime)
589 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
590 setenv("TZ", ":/etc/localtime", 0);
592 // work while we are cd into config_dir
593 // to allow the plugins refer to their config
594 // files using relative filenames
595 if(chdir(netdata_configured_config_dir) == -1)
596 fatal("Cannot cd to '%s'", netdata_configured_config_dir);
598 char path[1024 + 1], *p = getenv("PATH");
599 if(!p) p = "/bin:/usr/bin";
600 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
601 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
603 p = getenv("PYTHONPATH");
605 setenv("PYTHONPATH", config_get("plugins", "PYTHONPATH environment variable", p), 1);
611 // --------------------------------------------------------------------
612 // get the debugging flags from the configuration file
614 char *flags = config_get("global", "debug flags", "0x0000000000000000");
615 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
617 debug_flags = strtoull(flags, NULL, 0);
618 debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);
620 if(debug_flags != 0) {
621 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
622 if(setrlimit(RLIMIT_CORE, &rl) != 0)
623 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
625 #ifdef HAVE_SYS_PRCTL_H
626 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
631 // --------------------------------------------------------------------
632 // get log filenames and settings
635 char filename[FILENAME_MAX + 1];
636 snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);
637 stdout_filename = config_get("global", "debug log", filename);
639 snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);
640 stderr_filename = config_get("global", "error log", filename);
642 snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);
643 stdaccess_filename = config_get("global", "access log", filename);
646 error_log_throttle_period_backup =
647 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
649 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
651 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", (long long int)error_log_errors_per_period);
652 setenv("NETDATA_ERRORS_PER_PERIOD", config_get("global", "errors to trigger flood protection", ""), 1);
655 stdout_filename = stderr_filename = stdaccess_filename = "system";
656 error_log_throttle_period = 0;
657 error_log_errors_per_period = 0;
659 error_log_limit_unlimited();
662 // --------------------------------------------------------------------
665 #ifdef MADV_MERGEABLE
666 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
668 #warning "Kernel memory deduplication (KSM) is not available"
671 // --------------------------------------------------------------------
672 // get various system parameters
676 get_system_pid_max();
679 // --------------------------------------------------------------------
680 // find the system hostname
683 char hostnamebuf[HOSTNAME_MAX + 1];
684 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
685 error("WARNING: Cannot get machine hostname.");
687 hostname = config_get("global", "hostname", hostnamebuf);
688 debug(D_OPTIONS, "hostname set to '%s'", hostname);
690 setenv("NETDATA_HOSTNAME", hostname, 1);
694 // --------------------------------------------------------------------
695 // find we need to send data to a central netdata
697 central_netdata_to_push_data = config_get("global", "central netdata to send all data", "");
698 if(central_netdata_to_push_data && !*central_netdata_to_push_data)
699 central_netdata_to_push_data = NULL;
702 // --------------------------------------------------------------------
703 // get default memory mode for the database
705 if(central_netdata_to_push_data) {
706 default_rrd_memory_mode = RRD_MEMORY_MODE_RAM;
707 config_set("global", "memory mode", rrd_memory_mode_name(default_rrd_memory_mode));
710 default_rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(default_rrd_memory_mode)));
713 // --------------------------------------------------------------------
714 // get default database size
716 if(central_netdata_to_push_data) {
717 default_rrd_history_entries = 10;
718 config_set_number("global", "history", default_rrd_history_entries);
721 default_rrd_history_entries = (int) config_get_number("global", "history", align_entries_to_pagesize(RRD_DEFAULT_HISTORY_ENTRIES));
723 long h = align_entries_to_pagesize(default_rrd_history_entries);
724 if(h != default_rrd_history_entries) {
725 config_set_number("global", "history", h);
726 default_rrd_history_entries = (int)h;
729 if(default_rrd_history_entries < 5 || default_rrd_history_entries > RRD_HISTORY_ENTRIES_MAX) {
730 error("Invalid history entries %d given. Defaulting to %d.", default_rrd_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
731 default_rrd_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
734 debug(D_OPTIONS, "save lines set to %d.", default_rrd_history_entries);
737 // --------------------------------------------------------------------
738 // get default database update frequency
740 default_rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
741 if(default_rrd_update_every < 1 || default_rrd_update_every > 600) {
742 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", default_rrd_update_every, UPDATE_EVERY_MAX);
743 default_rrd_update_every = UPDATE_EVERY;
745 else debug(D_OPTIONS, "update timer set to %d.", default_rrd_update_every);
747 // let the plugins know the min update_every
750 snprintfz(buf, 15, "%d", default_rrd_update_every);
751 setenv("NETDATA_UPDATE_EVERY", buf, 1);
755 // --------------------------------------------------------------------
756 // setup process signals
758 // block signals while initializing threads.
759 // this causes the threads to block signals.
762 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
763 error("Could not block signals for threads");
765 // Catch signals which we want to use
769 // ingore all signals while we run in a signal handler
770 sigfillset(&sa.sa_mask);
772 // INFO: If we add signals here we have to unblock them
773 // at popen.c when running a external plugin.
775 // Ignore SIGPIPE completely.
776 sa.sa_handler = SIG_IGN;
777 if(sigaction(SIGPIPE, &sa, NULL) == -1)
778 error("Failed to change signal handler for SIGPIPE");
780 sa.sa_handler = sig_handler_exit;
781 if(sigaction(SIGINT, &sa, NULL) == -1)
782 error("Failed to change signal handler for SIGINT");
784 sa.sa_handler = sig_handler_exit;
785 if(sigaction(SIGTERM, &sa, NULL) == -1)
786 error("Failed to change signal handler for SIGTERM");
788 sa.sa_handler = sig_handler_logrotate;
789 if(sigaction(SIGHUP, &sa, NULL) == -1)
790 error("Failed to change signal handler for SIGHUP");
792 // save database on SIGUSR1
793 sa.sa_handler = sig_handler_save;
794 if(sigaction(SIGUSR1, &sa, NULL) == -1)
795 error("Failed to change signal handler for SIGUSR1");
797 // reload health configuration on SIGUSR2
798 sa.sa_handler = sig_handler_reload_health;
799 if(sigaction(SIGUSR2, &sa, NULL) == -1)
800 error("Failed to change signal handler for SIGUSR2");
803 // --------------------------------------------------------------------
804 // get the required stack size of the threads of netdata
806 i = pthread_attr_init(&attr);
808 fatal("pthread_attr_init() failed with code %d.", i);
810 i = pthread_attr_getstacksize(&attr, &stacksize);
812 fatal("pthread_attr_getstacksize() failed with code %d.", i);
814 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
816 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
819 // --------------------------------------------------------------------
820 // check which threads are enabled and initialize them
822 for (i = 0; static_threads[i].name != NULL ; i++) {
823 struct netdata_static_thread *st = &static_threads[i];
826 st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
828 if(st->enabled && st->init_routine)
833 // --------------------------------------------------------------------
834 // get the user we should run
836 // IMPORTANT: this is required before web_files_uid()
837 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
839 // IMPORTANT: these have to run once, while single threaded
840 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
844 // --------------------------------------------------------------------
845 // create the listening sockets
847 if(!check_config && !central_netdata_to_push_data)
848 create_listen_sockets();
851 // initialize the log files
852 open_all_log_files();
854 #ifdef NETDATA_INTERNAL_CHECKS
855 if(debug_flags != 0) {
856 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
857 if(setrlimit(RLIMIT_CORE, &rl) != 0)
858 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
859 #ifdef HAVE_SYS_PRCTL_H
860 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
863 #endif /* NETDATA_INTERNAL_CHECKS */
866 // fork, switch user, create pid file, set process priority
867 if(become_daemon(dont_fork, user) == -1)
868 fatal("Cannot daemonize myself.");
870 info("netdata started on pid %d.", getpid());
873 // ------------------------------------------------------------------------
874 // set default pthread stack size - after we have forked
876 if(stacksize < wanted_stacksize) {
877 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
879 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
881 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
885 // ------------------------------------------------------------------------
886 // initialize health monitoring
891 // ------------------------------------------------------------------------
892 // initialize the registry
897 // ------------------------------------------------------------------------
898 // initialize rrd host
907 // ------------------------------------------------------------------------
908 // enable log flood protection
910 error_log_limit_reset();
913 // ------------------------------------------------------------------------
916 web_server_threading_selection();
918 for (i = 0; static_threads[i].name != NULL ; i++) {
919 struct netdata_static_thread *st = &static_threads[i];
922 st->thread = mallocz(sizeof(pthread_t));
924 debug(D_SYSTEM, "Starting thread %s.", st->name);
926 if(pthread_create(st->thread, &attr, st->start_routine, st))
927 error("failed to create new thread for %s.", st->name);
929 else if(pthread_detach(*st->thread))
930 error("Cannot request detach of newly created %s thread.", st->name);
932 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
935 info("netdata initialization completed. Enjoy real-time performance monitoring!");
938 // ------------------------------------------------------------------------
939 // block signals while initializing threads.
943 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
944 error("Could not unblock signals for threads");
947 // Handle flags set in the signal handler.
951 debug(D_EXIT, "Exit main loop of netdata.");
952 netdata_cleanup_and_exit(0);