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 int main(int argc, char **argv) {
359 char *hostname = "localhost";
360 int i, check_config = 0;
361 int config_loaded = 0;
363 size_t wanted_stacksize = 0, stacksize = 0;
366 // set the name for logging
367 program_name = "netdata";
369 // parse depercated options
370 // TODO: Remove this block with the next major release.
374 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
375 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
376 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
377 remove_option(i, &argc, argv);
379 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
381 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
382 remove_option(i, &argc, argv);
384 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
385 config_set("global", "host access prefix", argv[i+1]);
386 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
387 remove_option(i, &argc, argv);
389 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
390 config_set("global", "history", argv[i+1]);
391 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
392 remove_option(i, &argc, argv);
400 int num_opts = sizeof(options) / sizeof(struct option_def);
401 char optstring[(num_opts * 2) + 1];
404 for( i = 0; i < num_opts; i++ ) {
405 optstring[string_i] = options[i].val;
407 if(options[i].arg_name) {
408 optstring[string_i] = ':';
412 // terminate optstring
413 optstring[string_i] ='\0';
414 optstring[(num_opts *2)] ='\0';
417 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
420 if(load_config(optarg, 1) != 1) {
421 error("Cannot load configuration file %s.", optarg);
425 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
436 config_set("global", "bind to", optarg);
443 strncpy(pidfile, optarg, FILENAME_MAX);
444 pidfile[FILENAME_MAX] = '\0';
447 config_set("global", "default port", optarg);
450 config_set("global", "host access prefix", optarg);
453 config_set("global", "update every", optarg);
456 config_set("global", "run as user", optarg);
459 printf("%s %s\n", program_name, program_version);
463 char* stacksize_string = "stacksize=";
464 char* debug_flags_string = "debug_flags=";
465 if(strcmp(optarg, "unittest") == 0) {
466 default_rrd_update_every = 1;
467 if(run_all_mockup_tests()) exit(1);
468 if(unit_test_storage()) exit(1);
469 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
472 else if(strcmp(optarg, "simple-pattern") == 0) {
473 if(optind + 2 > argc) {
474 fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
475 " Checks if 'pattern' matches the given 'string'.\n"
476 " - 'pattern' can be one or more space separated words.\n"
477 " - each 'word' can contain one or more asterisks.\n"
478 " - words starting with '!' give negative matches.\n"
479 " - words are processed left to right\n"
483 " > match all veth interfaces, except veth0:\n"
485 " -W simple-pattern '!veth0 veth*' 'veth12'\n"
488 " > match all *.ext files directly in /path/:\n"
489 " (this will not match *.ext files in a subdir of /path/)\n"
491 " -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
497 const char *heystack = argv[optind];
498 const char *needle = argv[optind + 1];
500 SIMPLE_PATTERN *p = simple_pattern_create(heystack
501 , SIMPLE_PATTERN_EXACT);
502 int ret = simple_pattern_matches(p, needle);
503 simple_pattern_free(p);
506 fprintf(stdout, "RESULT: MATCHED - pattern '%s' matches '%s'\n", heystack, needle);
510 fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s'\n", heystack, needle);
514 else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
515 optarg += strlen(stacksize_string);
516 config_set("global", "pthread stack size", optarg);
518 else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
519 optarg += strlen(debug_flags_string);
520 config_set("global", "debug flags", optarg);
521 debug_flags = strtoull(optarg, NULL, 0);
533 // close all open file descriptors, except the standard ones
534 // the caller may have left open files (lxc-attach has this issue)
537 for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
538 if(fd_is_valid(fd)) close(fd);
543 load_config(NULL, 0);
546 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
548 setenv("MALLOC_ARENA_MAX", pmax, 1);
550 #if defined(HAVE_C_MALLOPT)
551 i = (int)config_get_number("global", "glibc malloc arena max for netdata", 1);
553 mallopt(M_ARENA_MAX, 1);
556 // prepare configuration environment variables for the plugins
558 netdata_configured_config_dir = config_get("global", "config directory", CONFIG_DIR);
559 netdata_configured_log_dir = config_get("global", "log directory", LOG_DIR);
560 netdata_configured_plugins_dir = config_get("global", "plugins directory", PLUGINS_DIR);
561 netdata_configured_web_dir = config_get("global", "web files directory", WEB_DIR);
562 netdata_configured_cache_dir = config_get("global", "cache directory", CACHE_DIR);
563 netdata_configured_varlib_dir = config_get("global", "lib directory", VARLIB_DIR);
564 netdata_configured_home_dir = config_get("global", "home directory", CACHE_DIR);
566 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(netdata_configured_config_dir), 1);
567 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(netdata_configured_plugins_dir), 1);
568 setenv("NETDATA_WEB_DIR" , verify_required_directory(netdata_configured_web_dir), 1);
569 setenv("NETDATA_CACHE_DIR" , verify_required_directory(netdata_configured_cache_dir), 1);
570 setenv("NETDATA_LIB_DIR" , verify_required_directory(netdata_configured_varlib_dir), 1);
571 setenv("NETDATA_LOG_DIR" , verify_required_directory(netdata_configured_log_dir), 1);
572 setenv("HOME" , verify_required_directory(netdata_configured_home_dir), 1);
574 netdata_configured_host_prefix = config_get("global", "host access prefix", "");
575 setenv("NETDATA_HOST_PREFIX", netdata_configured_host_prefix, 1);
577 // disable buffering for python plugins
578 setenv("PYTHONUNBUFFERED", "1", 1);
580 // avoid flood calls to stat(/etc/localtime)
581 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
582 setenv("TZ", ":/etc/localtime", 0);
584 // work while we are cd into config_dir
585 // to allow the plugins refer to their config
586 // files using relative filenames
587 if(chdir(netdata_configured_config_dir) == -1)
588 fatal("Cannot cd to '%s'", netdata_configured_config_dir);
590 char path[1024 + 1], *p = getenv("PATH");
591 if(!p) p = "/bin:/usr/bin";
592 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
593 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
595 p = getenv("PYTHONPATH");
597 setenv("PYTHONPATH", config_get("plugins", "PYTHONPATH environment variable", p), 1);
603 // --------------------------------------------------------------------
604 // get the debugging flags from the configuration file
606 char *flags = config_get("global", "debug flags", "0x0000000000000000");
607 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
609 debug_flags = strtoull(flags, NULL, 0);
610 debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);
612 if(debug_flags != 0) {
613 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
614 if(setrlimit(RLIMIT_CORE, &rl) != 0)
615 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
617 #ifdef HAVE_SYS_PRCTL_H
618 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
623 // --------------------------------------------------------------------
624 // get log filenames and settings
627 char filename[FILENAME_MAX + 1];
628 snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);
629 stdout_filename = config_get("global", "debug log", filename);
631 snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);
632 stderr_filename = config_get("global", "error log", filename);
634 snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);
635 stdaccess_filename = config_get("global", "access log", filename);
638 error_log_throttle_period_backup =
639 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
641 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
643 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", (long long int)error_log_errors_per_period);
644 setenv("NETDATA_ERRORS_PER_PERIOD", config_get("global", "errors to trigger flood protection", ""), 1);
647 stdout_filename = stderr_filename = stdaccess_filename = "system";
648 error_log_throttle_period = 0;
649 error_log_errors_per_period = 0;
651 error_log_limit_unlimited();
654 // --------------------------------------------------------------------
657 #ifdef MADV_MERGEABLE
658 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
660 #warning "Kernel memory deduplication (KSM) is not available"
663 // --------------------------------------------------------------------
664 // get various system parameters
668 get_system_pid_max();
671 // --------------------------------------------------------------------
672 // find the system hostname
675 char hostnamebuf[HOSTNAME_MAX + 1];
676 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
677 error("WARNING: Cannot get machine hostname.");
679 hostname = config_get("global", "hostname", hostnamebuf);
680 debug(D_OPTIONS, "hostname set to '%s'", hostname);
682 setenv("NETDATA_HOSTNAME", hostname, 1);
686 // --------------------------------------------------------------------
687 // find we need to send data to a central netdata
689 central_netdata_to_push_data = config_get("global", "central netdata to send all data", "");
690 if(central_netdata_to_push_data && !*central_netdata_to_push_data)
691 central_netdata_to_push_data = NULL;
694 // --------------------------------------------------------------------
695 // get default memory mode for the database
697 if(central_netdata_to_push_data) {
698 default_rrd_memory_mode = RRD_MEMORY_MODE_RAM;
699 config_set("global", "memory mode", rrd_memory_mode_name(default_rrd_memory_mode));
702 default_rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(default_rrd_memory_mode)));
705 // --------------------------------------------------------------------
706 // get default database size
708 if(central_netdata_to_push_data) {
709 default_rrd_history_entries = 10;
710 config_set_number("global", "history", default_rrd_history_entries);
713 default_rrd_history_entries = (int) config_get_number("global", "history", align_entries_to_pagesize(RRD_DEFAULT_HISTORY_ENTRIES));
715 long h = align_entries_to_pagesize(default_rrd_history_entries);
716 if(h != default_rrd_history_entries) {
717 config_set_number("global", "history", h);
718 default_rrd_history_entries = (int)h;
721 if(default_rrd_history_entries < 5 || default_rrd_history_entries > RRD_HISTORY_ENTRIES_MAX) {
722 error("Invalid history entries %d given. Defaulting to %d.", default_rrd_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
723 default_rrd_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
726 debug(D_OPTIONS, "save lines set to %d.", default_rrd_history_entries);
729 // --------------------------------------------------------------------
730 // get default database update frequency
732 default_rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
733 if(default_rrd_update_every < 1 || default_rrd_update_every > 600) {
734 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", default_rrd_update_every, UPDATE_EVERY_MAX);
735 default_rrd_update_every = UPDATE_EVERY;
737 else debug(D_OPTIONS, "update timer set to %d.", default_rrd_update_every);
739 // let the plugins know the min update_every
742 snprintfz(buf, 15, "%d", default_rrd_update_every);
743 setenv("NETDATA_UPDATE_EVERY", buf, 1);
747 // --------------------------------------------------------------------
748 // setup process signals
750 // block signals while initializing threads.
751 // this causes the threads to block signals.
754 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
755 error("Could not block signals for threads");
757 // Catch signals which we want to use
761 // ingore all signals while we run in a signal handler
762 sigfillset(&sa.sa_mask);
764 // INFO: If we add signals here we have to unblock them
765 // at popen.c when running a external plugin.
767 // Ignore SIGPIPE completely.
768 sa.sa_handler = SIG_IGN;
769 if(sigaction(SIGPIPE, &sa, NULL) == -1)
770 error("Failed to change signal handler for SIGPIPE");
772 sa.sa_handler = sig_handler_exit;
773 if(sigaction(SIGINT, &sa, NULL) == -1)
774 error("Failed to change signal handler for SIGINT");
776 sa.sa_handler = sig_handler_exit;
777 if(sigaction(SIGTERM, &sa, NULL) == -1)
778 error("Failed to change signal handler for SIGTERM");
780 sa.sa_handler = sig_handler_logrotate;
781 if(sigaction(SIGHUP, &sa, NULL) == -1)
782 error("Failed to change signal handler for SIGHUP");
784 // save database on SIGUSR1
785 sa.sa_handler = sig_handler_save;
786 if(sigaction(SIGUSR1, &sa, NULL) == -1)
787 error("Failed to change signal handler for SIGUSR1");
789 // reload health configuration on SIGUSR2
790 sa.sa_handler = sig_handler_reload_health;
791 if(sigaction(SIGUSR2, &sa, NULL) == -1)
792 error("Failed to change signal handler for SIGUSR2");
795 // --------------------------------------------------------------------
796 // get the required stack size of the threads of netdata
798 i = pthread_attr_init(&attr);
800 fatal("pthread_attr_init() failed with code %d.", i);
802 i = pthread_attr_getstacksize(&attr, &stacksize);
804 fatal("pthread_attr_getstacksize() failed with code %d.", i);
806 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
808 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
811 // --------------------------------------------------------------------
812 // check which threads are enabled and initialize them
814 for (i = 0; static_threads[i].name != NULL ; i++) {
815 struct netdata_static_thread *st = &static_threads[i];
818 st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
820 if(st->enabled && st->init_routine)
825 // --------------------------------------------------------------------
826 // get the user we should run
828 // IMPORTANT: this is required before web_files_uid()
829 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
831 // IMPORTANT: these have to run once, while single threaded
832 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
836 // --------------------------------------------------------------------
837 // create the listening sockets
839 if(!check_config && !central_netdata_to_push_data)
840 create_listen_sockets();
843 // initialize the log files
844 open_all_log_files();
846 #ifdef NETDATA_INTERNAL_CHECKS
847 if(debug_flags != 0) {
848 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
849 if(setrlimit(RLIMIT_CORE, &rl) != 0)
850 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
851 #ifdef HAVE_SYS_PRCTL_H
852 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
855 #endif /* NETDATA_INTERNAL_CHECKS */
858 // fork, switch user, create pid file, set process priority
859 if(become_daemon(dont_fork, user) == -1)
860 fatal("Cannot daemonize myself.");
862 info("netdata started on pid %d.", getpid());
865 // ------------------------------------------------------------------------
866 // set default pthread stack size - after we have forked
868 if(stacksize < wanted_stacksize) {
869 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
871 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
873 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
877 // ------------------------------------------------------------------------
878 // initialize health monitoring
883 // ------------------------------------------------------------------------
884 // initialize the registry
889 // ------------------------------------------------------------------------
890 // initialize rrd host
899 // ------------------------------------------------------------------------
900 // enable log flood protection
902 error_log_limit_reset();
905 // ------------------------------------------------------------------------
908 web_server_threading_selection();
910 for (i = 0; static_threads[i].name != NULL ; i++) {
911 struct netdata_static_thread *st = &static_threads[i];
914 st->thread = mallocz(sizeof(pthread_t));
916 debug(D_SYSTEM, "Starting thread %s.", st->name);
918 if(pthread_create(st->thread, &attr, st->start_routine, st))
919 error("failed to create new thread for %s.", st->name);
921 else if(pthread_detach(*st->thread))
922 error("Cannot request detach of newly created %s thread.", st->name);
924 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
927 info("netdata initialization completed. Enjoy real-time performance monitoring!");
930 // ------------------------------------------------------------------------
931 // block signals while initializing threads.
935 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
936 error("Could not unblock signals for threads");
939 // Handle flags set in the signal handler.
943 debug(D_EXIT, "Exit main loop of netdata.");
944 netdata_cleanup_and_exit(0);