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 {"push-metrics", NULL, NULL, 0, NULL, NULL, rrdpush_sender_thread},
59 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
62 void web_server_threading_selection(void) {
63 int multi_threaded = 0;
64 int single_threaded = 0;
66 if(default_rrdpush_exclusive) {
67 info("Web server is disabled - use the remote netdata.");
70 multi_threaded = config_get_boolean("global", "multi threaded web server", 1);
71 single_threaded = !multi_threaded;
75 for(i = 0; static_threads[i].name ; i++) {
76 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
77 static_threads[i].enabled = multi_threaded;
79 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
80 static_threads[i].enabled = single_threaded;
83 if(default_rrdpush_exclusive)
86 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
88 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);
89 web_x_frame_options = config_get("global", "web x-frame-options header", "");
90 if(!*web_x_frame_options) web_x_frame_options = NULL;
92 #ifdef NETDATA_WITH_ZLIB
93 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
95 char *s = config_get("global", "web compression strategy", "default");
96 if(!strcmp(s, "default"))
97 web_gzip_strategy = Z_DEFAULT_STRATEGY;
98 else if(!strcmp(s, "filtered"))
99 web_gzip_strategy = Z_FILTERED;
100 else if(!strcmp(s, "huffman only"))
101 web_gzip_strategy = Z_HUFFMAN_ONLY;
102 else if(!strcmp(s, "rle"))
103 web_gzip_strategy = Z_RLE;
104 else if(!strcmp(s, "fixed"))
105 web_gzip_strategy = Z_FIXED;
107 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
108 web_gzip_strategy = Z_DEFAULT_STRATEGY;
111 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
112 if(web_gzip_level < 1) {
113 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
116 else if(web_gzip_level > 9) {
117 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
120 #endif /* NETDATA_WITH_ZLIB */
124 int killpid(pid_t pid, int sig)
127 debug(D_EXIT, "Request to kill pid %d", pid);
130 if(kill(pid, 0) == -1) {
133 error("Request to kill pid %d, but it is not running.", pid);
137 error("Request to kill pid %d, but I do not have enough permissions.", pid);
141 error("Request to kill pid %d, but I received an error.", pid);
147 ret = kill(pid, sig);
151 error("Cannot kill pid %d, but it is not running.", pid);
155 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
159 error("Cannot kill pid %d, but I received an error.", pid);
170 error_log_limit_unlimited();
174 struct web_client *w;
175 for(w = web_clients; w ; w = w->next) {
176 info("Stopping web client %s", w->client_ip);
177 pthread_cancel(w->thread);
179 // pthread_join(w->thread, NULL);
185 for (i = 0; static_threads[i].name != NULL ; i++) {
186 if(static_threads[i].enabled) {
187 info("Stopping %s thread", static_threads[i].name);
188 pthread_cancel(*static_threads[i].thread);
190 // pthread_join(*static_threads[i].thread, NULL);
192 static_threads[i].enabled = 0;
197 info("Killing tc-qos-helper process %d", tc_child_pid);
198 if(killpid(tc_child_pid, SIGTERM) != -1)
199 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
205 for(cd = pluginsd_root ; cd ; cd = cd->next) {
206 if(cd->enabled && !cd->obsolete) {
207 info("Stopping %s plugin thread", cd->id);
208 pthread_cancel(cd->thread);
211 info("killing %s plugin child process pid %d", cd->id, cd->pid);
212 if(killpid(cd->pid, SIGTERM) != -1)
213 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
222 // if, for any reason there is any child exited
224 info("Cleaning up an other children");
225 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
227 info("All threads/childs stopped.");
230 struct option_def options[] = {
231 // opt description arg name default value
232 { 'c', "Configuration file to load.", "filename", CONFIG_DIR "/" CONFIG_FILENAME},
233 { 'D', "Do not fork. Run in the foreground.", NULL, "run in the background"},
234 { 'h', "Display this help message.", NULL, NULL},
235 { 'P', "File to save a pid while running.", "filename", "do not save pid to a file"},
236 { 'i', "The IP address to listen to.", "IP", "all IP addresses IPv4 and IPv6"},
237 { 'k', "Check health configuration and exit.", NULL, NULL},
238 { 'p', "API/Web port to use.", "port", "19999"},
239 { 's', "Prefix for /proc and /sys (for containers).", "path", "no prefix"},
240 { 't', "The internal clock of netdata.", "seconds", "1"},
241 { 'u', "Run as user.", "username", "netdata"},
242 { 'v', "Print netdata version and exit.", NULL, NULL},
243 { 'W', "See Advanced options below.", "options", NULL},
246 void help(int exitcode) {
253 int num_opts = sizeof(options) / sizeof(struct option_def);
257 // Compute maximum argument length
258 for( i = 0; i < num_opts; i++ ) {
259 if(options[i].arg_name) {
260 int len_arg = (int)strlen(options[i].arg_name);
261 if(len_arg > max_len_arg) max_len_arg = len_arg;
265 if(max_len_arg > 30) max_len_arg = 30;
266 if(max_len_arg < 20) max_len_arg = 20;
268 fprintf(stream, "%s", "\n"
270 " |.-. .-. .-. .-. . netdata \n"
271 " | '-' '-' '-' '-' real-time performance monitoring, done right! \n"
272 " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
274 " Copyright (C) 2016-2017, Costa Tsaousis <costa@tsaousis.gr>\n"
275 " Released under GNU General Public License v3 or later.\n"
276 " All rights reserved.\n"
278 " Home Page : https://my-netdata.io\n"
279 " Source Code: https://github.com/firehol/netdata\n"
280 " Wiki / Docs: https://github.com/firehol/netdata/wiki\n"
281 " Support : https://github.com/firehol/netdata/issues\n"
282 " License : https://github.com/firehol/netdata/blob/master/LICENSE.md\n"
284 " Twitter : https://twitter.com/linuxnetdata\n"
285 " Facebook : https://www.facebook.com/linuxnetdata/\n"
287 " netdata is a https://firehol.org project.\n"
292 fprintf(stream, " SYNOPSIS: netdata [options]\n");
293 fprintf(stream, "\n");
294 fprintf(stream, " Options:\n\n");
296 // Output options description.
297 for( i = 0; i < num_opts; i++ ) {
298 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
299 if(options[i].default_value) {
300 fprintf(stream, "\n %c %-*s Default: %s\n", ' ', max_len_arg, "", options[i].default_value);
302 fprintf(stream, "\n");
304 fprintf(stream, "\n");
307 fprintf(stream, "\n Advanced options:\n\n"
308 " -W stacksize=N Set the stacksize (in bytes).\n\n"
309 " -W debug_flags=N Set runtime tracing to debug.log.\n\n"
310 " -W unittest Run internal unittests and exit.\n\n"
311 " -W simple-pattern pattern string\n"
312 " Check if string matches pattern and exit.\n\n"
315 fprintf(stream, "\n Signals netdata handles:\n\n"
316 " - HUP Close and reopen log files.\n"
317 " - USR1 Save internal DB to disk.\n"
318 " - USR2 Reload health configuration.\n"
326 // TODO: Remove this function with the nix major release.
327 void remove_option(int opt_index, int *argc, char **argv) {
329 // remove the options.
332 for(i = opt_index; i < *argc; i++) {
336 } while(argv[i][0] != '-' && opt_index >= *argc);
339 static const char *verify_required_directory(const char *dir) {
341 fatal("Cannot cd to directory '%s'", dir);
343 DIR *d = opendir(dir);
345 fatal("Cannot examine the contents of directory '%s'", dir);
351 static void get_netdata_configured_directories() {
352 netdata_configured_config_dir = config_get("global", "config directory", CONFIG_DIR);
353 netdata_configured_log_dir = config_get("global", "log directory", LOG_DIR);
354 netdata_configured_plugins_dir = config_get("global", "plugins directory", PLUGINS_DIR);
355 netdata_configured_web_dir = config_get("global", "web files directory", WEB_DIR);
356 netdata_configured_cache_dir = config_get("global", "cache directory", CACHE_DIR);
357 netdata_configured_varlib_dir = config_get("global", "lib directory", VARLIB_DIR);
358 netdata_configured_home_dir = config_get("global", "home directory", CACHE_DIR);
361 int main(int argc, char **argv) {
362 char *hostname = "localhost";
363 int i, check_config = 0;
364 int config_loaded = 0;
366 size_t wanted_stacksize = 0, stacksize = 0;
369 // set the name for logging
370 program_name = "netdata";
372 // parse depercated options
373 // TODO: Remove this block with the next major release.
377 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
378 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
379 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
380 remove_option(i, &argc, argv);
382 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
384 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
385 remove_option(i, &argc, argv);
387 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
388 config_set("global", "host access prefix", argv[i+1]);
389 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
390 remove_option(i, &argc, argv);
392 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
393 config_set("global", "history", argv[i+1]);
394 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
395 remove_option(i, &argc, argv);
403 int num_opts = sizeof(options) / sizeof(struct option_def);
404 char optstring[(num_opts * 2) + 1];
407 for( i = 0; i < num_opts; i++ ) {
408 optstring[string_i] = options[i].val;
410 if(options[i].arg_name) {
411 optstring[string_i] = ':';
415 // terminate optstring
416 optstring[string_i] ='\0';
417 optstring[(num_opts *2)] ='\0';
420 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
423 if(config_load(optarg, 1) != 1) {
424 error("Cannot load configuration file %s.", optarg);
428 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
439 config_set("global", "bind to", optarg);
446 strncpy(pidfile, optarg, FILENAME_MAX);
447 pidfile[FILENAME_MAX] = '\0';
450 config_set("global", "default port", optarg);
453 config_set("global", "host access prefix", optarg);
456 config_set("global", "update every", optarg);
459 config_set("global", "run as user", optarg);
462 printf("%s %s\n", program_name, program_version);
466 char* stacksize_string = "stacksize=";
467 char* debug_flags_string = "debug_flags=";
468 if(strcmp(optarg, "unittest") == 0) {
469 default_rrd_update_every = 1;
470 if(!config_loaded) config_load(NULL, 0);
471 get_netdata_configured_directories();
473 rrd_init("unittest");
474 if(run_all_mockup_tests()) exit(1);
475 if(unit_test_storage()) exit(1);
476 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
479 else if(strcmp(optarg, "simple-pattern") == 0) {
480 if(optind + 2 > argc) {
481 fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
482 " Checks if 'pattern' matches the given 'string'.\n"
483 " - 'pattern' can be one or more space separated words.\n"
484 " - each 'word' can contain one or more asterisks.\n"
485 " - words starting with '!' give negative matches.\n"
486 " - words are processed left to right\n"
490 " > match all veth interfaces, except veth0:\n"
492 " -W simple-pattern '!veth0 veth*' 'veth12'\n"
495 " > match all *.ext files directly in /path/:\n"
496 " (this will not match *.ext files in a subdir of /path/)\n"
498 " -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
504 const char *heystack = argv[optind];
505 const char *needle = argv[optind + 1];
507 SIMPLE_PATTERN *p = simple_pattern_create(heystack
508 , SIMPLE_PATTERN_EXACT);
509 int ret = simple_pattern_matches(p, needle);
510 simple_pattern_free(p);
513 fprintf(stdout, "RESULT: MATCHED - pattern '%s' matches '%s'\n", heystack, needle);
517 fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s'\n", heystack, needle);
521 else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
522 optarg += strlen(stacksize_string);
523 config_set("global", "pthread stack size", optarg);
525 else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
526 optarg += strlen(debug_flags_string);
527 config_set("global", "debug flags", optarg);
528 debug_flags = strtoull(optarg, NULL, 0);
540 // close all open file descriptors, except the standard ones
541 // the caller may have left open files (lxc-attach has this issue)
544 for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
545 if(fd_is_valid(fd)) close(fd);
550 config_load(NULL, 0);
553 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
555 setenv("MALLOC_ARENA_MAX", pmax, 1);
557 #if defined(HAVE_C_MALLOPT)
558 i = (int)config_get_number("global", "glibc malloc arena max for netdata", 1);
560 mallopt(M_ARENA_MAX, 1);
563 // prepare configuration environment variables for the plugins
565 get_netdata_configured_directories();
567 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(netdata_configured_config_dir), 1);
568 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(netdata_configured_plugins_dir), 1);
569 setenv("NETDATA_WEB_DIR" , verify_required_directory(netdata_configured_web_dir), 1);
570 setenv("NETDATA_CACHE_DIR" , verify_required_directory(netdata_configured_cache_dir), 1);
571 setenv("NETDATA_LIB_DIR" , verify_required_directory(netdata_configured_varlib_dir), 1);
572 setenv("NETDATA_LOG_DIR" , verify_required_directory(netdata_configured_log_dir), 1);
573 setenv("HOME" , verify_required_directory(netdata_configured_home_dir), 1);
575 netdata_configured_host_prefix = config_get("global", "host access prefix", "");
576 setenv("NETDATA_HOST_PREFIX", netdata_configured_host_prefix, 1);
578 // disable buffering for python plugins
579 setenv("PYTHONUNBUFFERED", "1", 1);
581 // avoid flood calls to stat(/etc/localtime)
582 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
583 setenv("TZ", ":/etc/localtime", 0);
585 // work while we are cd into config_dir
586 // to allow the plugins refer to their config
587 // files using relative filenames
588 if(chdir(netdata_configured_config_dir) == -1)
589 fatal("Cannot cd to '%s'", netdata_configured_config_dir);
591 char path[1024 + 1], *p = getenv("PATH");
592 if(!p) p = "/bin:/usr/bin";
593 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
594 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
596 p = getenv("PYTHONPATH");
598 setenv("PYTHONPATH", config_get("plugins", "PYTHONPATH environment variable", p), 1);
604 // --------------------------------------------------------------------
605 // get the debugging flags from the configuration file
607 char *flags = config_get("global", "debug flags", "0x0000000000000000");
608 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
610 debug_flags = strtoull(flags, NULL, 0);
611 debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);
613 if(debug_flags != 0) {
614 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
615 if(setrlimit(RLIMIT_CORE, &rl) != 0)
616 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
618 #ifdef HAVE_SYS_PRCTL_H
619 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
624 // --------------------------------------------------------------------
625 // get log filenames and settings
628 char filename[FILENAME_MAX + 1];
629 snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);
630 stdout_filename = config_get("global", "debug log", filename);
632 snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);
633 stderr_filename = config_get("global", "error log", filename);
635 snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);
636 stdaccess_filename = config_get("global", "access log", filename);
639 error_log_throttle_period_backup =
640 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
642 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
644 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", (long long int)error_log_errors_per_period);
645 setenv("NETDATA_ERRORS_PER_PERIOD", config_get("global", "errors to trigger flood protection", ""), 1);
648 stdout_filename = stderr_filename = stdaccess_filename = "system";
649 error_log_throttle_period = 0;
650 error_log_errors_per_period = 0;
652 error_log_limit_unlimited();
655 // --------------------------------------------------------------------
658 #ifdef MADV_MERGEABLE
659 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
661 #warning "Kernel memory deduplication (KSM) is not available"
664 // --------------------------------------------------------------------
665 // get various system parameters
669 get_system_pid_max();
672 // --------------------------------------------------------------------
673 // find the system hostname
676 char hostnamebuf[HOSTNAME_MAX + 1];
677 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
678 error("WARNING: Cannot get machine hostname.");
680 hostname = config_get("global", "hostname", hostnamebuf);
681 debug(D_OPTIONS, "hostname set to '%s'", hostname);
683 setenv("NETDATA_HOSTNAME", hostname, 1);
687 // --------------------------------------------------------------------
688 // find we need to send data to another netdata
693 // --------------------------------------------------------------------
694 // get default memory mode for the database
696 if(default_rrdpush_exclusive) {
697 default_rrd_memory_mode = RRD_MEMORY_MODE_NONE;
698 config_set("global", "memory mode", rrd_memory_mode_name(default_rrd_memory_mode));
701 default_rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(default_rrd_memory_mode)));
704 // --------------------------------------------------------------------
705 // get default database size
707 if(default_rrdpush_exclusive) {
708 default_rrd_history_entries = 10;
709 config_set_number("global", "history", default_rrd_history_entries);
712 default_rrd_history_entries = (int) config_get_number("global", "history", align_entries_to_pagesize(default_rrd_memory_mode, RRD_DEFAULT_HISTORY_ENTRIES));
714 long h = align_entries_to_pagesize(default_rrd_memory_mode, default_rrd_history_entries);
715 if(h != default_rrd_history_entries) {
716 config_set_number("global", "history", h);
717 default_rrd_history_entries = (int)h;
720 if(default_rrd_history_entries < 5 || default_rrd_history_entries > RRD_HISTORY_ENTRIES_MAX) {
721 error("Invalid history entries %d given. Defaulting to %d.", default_rrd_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
722 default_rrd_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
725 debug(D_OPTIONS, "save lines set to %d.", default_rrd_history_entries);
728 // --------------------------------------------------------------------
729 // get default database update frequency
731 default_rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
732 if(default_rrd_update_every < 1 || default_rrd_update_every > 600) {
733 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", default_rrd_update_every, UPDATE_EVERY_MAX);
734 default_rrd_update_every = UPDATE_EVERY;
736 else debug(D_OPTIONS, "update timer set to %d.", default_rrd_update_every);
738 // let the plugins know the min update_every
741 snprintfz(buf, 15, "%d", default_rrd_update_every);
742 setenv("NETDATA_UPDATE_EVERY", buf, 1);
746 // --------------------------------------------------------------------
747 // setup process signals
749 // block signals while initializing threads.
750 // this causes the threads to block signals.
753 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
754 error("Could not block signals for threads");
756 // Catch signals which we want to use
760 // ingore all signals while we run in a signal handler
761 sigfillset(&sa.sa_mask);
763 // INFO: If we add signals here we have to unblock them
764 // at popen.c when running a external plugin.
766 // Ignore SIGPIPE completely.
767 sa.sa_handler = SIG_IGN;
768 if(sigaction(SIGPIPE, &sa, NULL) == -1)
769 error("Failed to change signal handler for SIGPIPE");
771 sa.sa_handler = sig_handler_exit;
772 if(sigaction(SIGINT, &sa, NULL) == -1)
773 error("Failed to change signal handler for SIGINT");
775 sa.sa_handler = sig_handler_exit;
776 if(sigaction(SIGTERM, &sa, NULL) == -1)
777 error("Failed to change signal handler for SIGTERM");
779 sa.sa_handler = sig_handler_logrotate;
780 if(sigaction(SIGHUP, &sa, NULL) == -1)
781 error("Failed to change signal handler for SIGHUP");
783 // save database on SIGUSR1
784 sa.sa_handler = sig_handler_save;
785 if(sigaction(SIGUSR1, &sa, NULL) == -1)
786 error("Failed to change signal handler for SIGUSR1");
788 // reload health configuration on SIGUSR2
789 sa.sa_handler = sig_handler_reload_health;
790 if(sigaction(SIGUSR2, &sa, NULL) == -1)
791 error("Failed to change signal handler for SIGUSR2");
794 // --------------------------------------------------------------------
795 // get the required stack size of the threads of netdata
797 i = pthread_attr_init(&attr);
799 fatal("pthread_attr_init() failed with code %d.", i);
801 i = pthread_attr_getstacksize(&attr, &stacksize);
803 fatal("pthread_attr_getstacksize() failed with code %d.", i);
805 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
807 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
810 // --------------------------------------------------------------------
811 // check which threads are enabled and initialize them
813 for (i = 0; static_threads[i].name != NULL ; i++) {
814 struct netdata_static_thread *st = &static_threads[i];
817 st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
819 if(st->enabled && st->init_routine)
824 // --------------------------------------------------------------------
825 // get the user we should run
827 // IMPORTANT: this is required before web_files_uid()
828 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
830 // IMPORTANT: these have to run once, while single threaded
831 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
835 // --------------------------------------------------------------------
836 // create the listening sockets
838 if(!check_config && !default_rrdpush_exclusive)
839 create_listen_sockets();
842 // --------------------------------------------------------------------
843 // load the aggregated host configuration file
845 char filename[FILENAME_MAX + 1];
846 snprintfz(filename, FILENAME_MAX, "%s/aggregated_hosts.conf", netdata_configured_config_dir);
847 appconfig_load(&stream_config, filename, 0);
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);