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 {"central-netdata-push",NULL, NULL, 0, NULL, NULL, central_netdata_push_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;
65 int rrdpush_thread = 1;
66 int backends_thread = 1;
68 if(rrdpush_exclusive) {
70 info("Web servers and backends thread are disabled - use the central netdata.");
73 multi_threaded = config_get_boolean("global", "multi threaded web server", 1);
74 single_threaded = !multi_threaded;
78 for(i = 0; static_threads[i].name ; i++) {
79 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
80 static_threads[i].enabled = multi_threaded;
82 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
83 static_threads[i].enabled = single_threaded;
85 if(static_threads[i].start_routine == central_netdata_push_thread)
86 static_threads[i].enabled = rrdpush_thread;
88 if(static_threads[i].start_routine == backends_main)
89 static_threads[i].enabled = backends_thread;
95 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
97 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);
98 web_x_frame_options = config_get("global", "web x-frame-options header", "");
99 if(!*web_x_frame_options) web_x_frame_options = NULL;
101 #ifdef NETDATA_WITH_ZLIB
102 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
104 char *s = config_get("global", "web compression strategy", "default");
105 if(!strcmp(s, "default"))
106 web_gzip_strategy = Z_DEFAULT_STRATEGY;
107 else if(!strcmp(s, "filtered"))
108 web_gzip_strategy = Z_FILTERED;
109 else if(!strcmp(s, "huffman only"))
110 web_gzip_strategy = Z_HUFFMAN_ONLY;
111 else if(!strcmp(s, "rle"))
112 web_gzip_strategy = Z_RLE;
113 else if(!strcmp(s, "fixed"))
114 web_gzip_strategy = Z_FIXED;
116 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
117 web_gzip_strategy = Z_DEFAULT_STRATEGY;
120 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
121 if(web_gzip_level < 1) {
122 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
125 else if(web_gzip_level > 9) {
126 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
129 #endif /* NETDATA_WITH_ZLIB */
133 int killpid(pid_t pid, int sig)
136 debug(D_EXIT, "Request to kill pid %d", pid);
139 if(kill(pid, 0) == -1) {
142 error("Request to kill pid %d, but it is not running.", pid);
146 error("Request to kill pid %d, but I do not have enough permissions.", pid);
150 error("Request to kill pid %d, but I received an error.", pid);
156 ret = kill(pid, sig);
160 error("Cannot kill pid %d, but it is not running.", pid);
164 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
168 error("Cannot kill pid %d, but I received an error.", pid);
179 error_log_limit_unlimited();
183 struct web_client *w;
184 for(w = web_clients; w ; w = w->next) {
185 info("Stopping web client %s", w->client_ip);
186 pthread_cancel(w->thread);
188 // pthread_join(w->thread, NULL);
194 for (i = 0; static_threads[i].name != NULL ; i++) {
195 if(static_threads[i].enabled) {
196 info("Stopping %s thread", static_threads[i].name);
197 pthread_cancel(*static_threads[i].thread);
199 // pthread_join(*static_threads[i].thread, NULL);
201 static_threads[i].enabled = 0;
206 info("Killing tc-qos-helper process %d", tc_child_pid);
207 if(killpid(tc_child_pid, SIGTERM) != -1)
208 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
214 for(cd = pluginsd_root ; cd ; cd = cd->next) {
215 if(cd->enabled && !cd->obsolete) {
216 info("Stopping %s plugin thread", cd->id);
217 pthread_cancel(cd->thread);
220 info("killing %s plugin child process pid %d", cd->id, cd->pid);
221 if(killpid(cd->pid, SIGTERM) != -1)
222 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
231 // if, for any reason there is any child exited
233 info("Cleaning up an other children");
234 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
236 info("All threads/childs stopped.");
239 struct option_def options[] = {
240 // opt description arg name default value
241 { 'c', "Configuration file to load.", "filename", CONFIG_DIR "/" CONFIG_FILENAME},
242 { 'D', "Do not fork. Run in the foreground.", NULL, "run in the background"},
243 { 'h', "Display this help message.", NULL, NULL},
244 { 'P', "File to save a pid while running.", "filename", "do not save pid to a file"},
245 { 'i', "The IP address to listen to.", "IP", "all IP addresses IPv4 and IPv6"},
246 { 'k', "Check health configuration and exit.", NULL, NULL},
247 { 'p', "API/Web port to use.", "port", "19999"},
248 { 's', "Prefix for /proc and /sys (for containers).", "path", "no prefix"},
249 { 't', "The internal clock of netdata.", "seconds", "1"},
250 { 'u', "Run as user.", "username", "netdata"},
251 { 'v', "Print netdata version and exit.", NULL, NULL},
252 { 'W', "See Advanced options below.", "options", NULL},
255 void help(int exitcode) {
262 int num_opts = sizeof(options) / sizeof(struct option_def);
266 // Compute maximum argument length
267 for( i = 0; i < num_opts; i++ ) {
268 if(options[i].arg_name) {
269 int len_arg = (int)strlen(options[i].arg_name);
270 if(len_arg > max_len_arg) max_len_arg = len_arg;
274 if(max_len_arg > 30) max_len_arg = 30;
275 if(max_len_arg < 20) max_len_arg = 20;
277 fprintf(stream, "%s", "\n"
279 " |.-. .-. .-. .-. . netdata \n"
280 " | '-' '-' '-' '-' real-time performance monitoring, done right! \n"
281 " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
283 " Copyright (C) 2016-2017, Costa Tsaousis <costa@tsaousis.gr>\n"
284 " Released under GNU General Public License v3 or later.\n"
285 " All rights reserved.\n"
287 " Home Page : https://my-netdata.io\n"
288 " Source Code: https://github.com/firehol/netdata\n"
289 " Wiki / Docs: https://github.com/firehol/netdata/wiki\n"
290 " Support : https://github.com/firehol/netdata/issues\n"
291 " License : https://github.com/firehol/netdata/blob/master/LICENSE.md\n"
293 " Twitter : https://twitter.com/linuxnetdata\n"
294 " Facebook : https://www.facebook.com/linuxnetdata/\n"
296 " netdata is a https://firehol.org project.\n"
301 fprintf(stream, " SYNOPSIS: netdata [options]\n");
302 fprintf(stream, "\n");
303 fprintf(stream, " Options:\n\n");
305 // Output options description.
306 for( i = 0; i < num_opts; i++ ) {
307 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
308 if(options[i].default_value) {
309 fprintf(stream, "\n %c %-*s Default: %s\n", ' ', max_len_arg, "", options[i].default_value);
311 fprintf(stream, "\n");
313 fprintf(stream, "\n");
316 fprintf(stream, "\n Advanced options:\n\n"
317 " -W stacksize=N Set the stacksize (in bytes).\n\n"
318 " -W debug_flags=N Set runtime tracing to debug.log.\n\n"
319 " -W unittest Run internal unittests and exit.\n\n"
320 " -W simple-pattern pattern string\n"
321 " Check if string matches pattern and exit.\n\n"
324 fprintf(stream, "\n Signals netdata handles:\n\n"
325 " - HUP Close and reopen log files.\n"
326 " - USR1 Save internal DB to disk.\n"
327 " - USR2 Reload health configuration.\n"
335 // TODO: Remove this function with the nix major release.
336 void remove_option(int opt_index, int *argc, char **argv) {
338 // remove the options.
341 for(i = opt_index; i < *argc; i++) {
345 } while(argv[i][0] != '-' && opt_index >= *argc);
348 static const char *verify_required_directory(const char *dir) {
350 fatal("Cannot cd to directory '%s'", dir);
352 DIR *d = opendir(dir);
354 fatal("Cannot examine the contents of directory '%s'", dir);
360 static void get_netdata_configured_directories() {
361 netdata_configured_config_dir = config_get("global", "config directory", CONFIG_DIR);
362 netdata_configured_log_dir = config_get("global", "log directory", LOG_DIR);
363 netdata_configured_plugins_dir = config_get("global", "plugins directory", PLUGINS_DIR);
364 netdata_configured_web_dir = config_get("global", "web files directory", WEB_DIR);
365 netdata_configured_cache_dir = config_get("global", "cache directory", CACHE_DIR);
366 netdata_configured_varlib_dir = config_get("global", "lib directory", VARLIB_DIR);
367 netdata_configured_home_dir = config_get("global", "home directory", CACHE_DIR);
370 int main(int argc, char **argv) {
371 char *hostname = "localhost";
372 int i, check_config = 0;
373 int config_loaded = 0;
375 size_t wanted_stacksize = 0, stacksize = 0;
378 // set the name for logging
379 program_name = "netdata";
381 // parse depercated options
382 // TODO: Remove this block with the next major release.
386 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
387 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
388 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
389 remove_option(i, &argc, argv);
391 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
393 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
394 remove_option(i, &argc, argv);
396 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
397 config_set("global", "host access prefix", argv[i+1]);
398 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
399 remove_option(i, &argc, argv);
401 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
402 config_set("global", "history", argv[i+1]);
403 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
404 remove_option(i, &argc, argv);
412 int num_opts = sizeof(options) / sizeof(struct option_def);
413 char optstring[(num_opts * 2) + 1];
416 for( i = 0; i < num_opts; i++ ) {
417 optstring[string_i] = options[i].val;
419 if(options[i].arg_name) {
420 optstring[string_i] = ':';
424 // terminate optstring
425 optstring[string_i] ='\0';
426 optstring[(num_opts *2)] ='\0';
429 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
432 if(config_load(optarg, 1) != 1) {
433 error("Cannot load configuration file %s.", optarg);
437 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
448 config_set("global", "bind to", optarg);
455 strncpy(pidfile, optarg, FILENAME_MAX);
456 pidfile[FILENAME_MAX] = '\0';
459 config_set("global", "default port", optarg);
462 config_set("global", "host access prefix", optarg);
465 config_set("global", "update every", optarg);
468 config_set("global", "run as user", optarg);
471 printf("%s %s\n", program_name, program_version);
475 char* stacksize_string = "stacksize=";
476 char* debug_flags_string = "debug_flags=";
477 if(strcmp(optarg, "unittest") == 0) {
478 default_rrd_update_every = 1;
479 if(!config_loaded) config_load(NULL, 0);
480 get_netdata_configured_directories();
482 rrd_init("unittest");
483 if(run_all_mockup_tests()) exit(1);
484 if(unit_test_storage()) exit(1);
485 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
488 else if(strcmp(optarg, "simple-pattern") == 0) {
489 if(optind + 2 > argc) {
490 fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
491 " Checks if 'pattern' matches the given 'string'.\n"
492 " - 'pattern' can be one or more space separated words.\n"
493 " - each 'word' can contain one or more asterisks.\n"
494 " - words starting with '!' give negative matches.\n"
495 " - words are processed left to right\n"
499 " > match all veth interfaces, except veth0:\n"
501 " -W simple-pattern '!veth0 veth*' 'veth12'\n"
504 " > match all *.ext files directly in /path/:\n"
505 " (this will not match *.ext files in a subdir of /path/)\n"
507 " -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
513 const char *heystack = argv[optind];
514 const char *needle = argv[optind + 1];
516 SIMPLE_PATTERN *p = simple_pattern_create(heystack
517 , SIMPLE_PATTERN_EXACT);
518 int ret = simple_pattern_matches(p, needle);
519 simple_pattern_free(p);
522 fprintf(stdout, "RESULT: MATCHED - pattern '%s' matches '%s'\n", heystack, needle);
526 fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s'\n", heystack, needle);
530 else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
531 optarg += strlen(stacksize_string);
532 config_set("global", "pthread stack size", optarg);
534 else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
535 optarg += strlen(debug_flags_string);
536 config_set("global", "debug flags", optarg);
537 debug_flags = strtoull(optarg, NULL, 0);
549 // close all open file descriptors, except the standard ones
550 // the caller may have left open files (lxc-attach has this issue)
553 for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
554 if(fd_is_valid(fd)) close(fd);
559 config_load(NULL, 0);
562 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
564 setenv("MALLOC_ARENA_MAX", pmax, 1);
566 #if defined(HAVE_C_MALLOPT)
567 i = (int)config_get_number("global", "glibc malloc arena max for netdata", 1);
569 mallopt(M_ARENA_MAX, 1);
572 // prepare configuration environment variables for the plugins
574 get_netdata_configured_directories();
576 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(netdata_configured_config_dir), 1);
577 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(netdata_configured_plugins_dir), 1);
578 setenv("NETDATA_WEB_DIR" , verify_required_directory(netdata_configured_web_dir), 1);
579 setenv("NETDATA_CACHE_DIR" , verify_required_directory(netdata_configured_cache_dir), 1);
580 setenv("NETDATA_LIB_DIR" , verify_required_directory(netdata_configured_varlib_dir), 1);
581 setenv("NETDATA_LOG_DIR" , verify_required_directory(netdata_configured_log_dir), 1);
582 setenv("HOME" , verify_required_directory(netdata_configured_home_dir), 1);
584 netdata_configured_host_prefix = config_get("global", "host access prefix", "");
585 setenv("NETDATA_HOST_PREFIX", netdata_configured_host_prefix, 1);
587 // disable buffering for python plugins
588 setenv("PYTHONUNBUFFERED", "1", 1);
590 // avoid flood calls to stat(/etc/localtime)
591 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
592 setenv("TZ", ":/etc/localtime", 0);
594 // work while we are cd into config_dir
595 // to allow the plugins refer to their config
596 // files using relative filenames
597 if(chdir(netdata_configured_config_dir) == -1)
598 fatal("Cannot cd to '%s'", netdata_configured_config_dir);
600 char path[1024 + 1], *p = getenv("PATH");
601 if(!p) p = "/bin:/usr/bin";
602 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
603 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
605 p = getenv("PYTHONPATH");
607 setenv("PYTHONPATH", config_get("plugins", "PYTHONPATH environment variable", p), 1);
613 // --------------------------------------------------------------------
614 // get the debugging flags from the configuration file
616 char *flags = config_get("global", "debug flags", "0x0000000000000000");
617 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
619 debug_flags = strtoull(flags, NULL, 0);
620 debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);
622 if(debug_flags != 0) {
623 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
624 if(setrlimit(RLIMIT_CORE, &rl) != 0)
625 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
627 #ifdef HAVE_SYS_PRCTL_H
628 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
633 // --------------------------------------------------------------------
634 // get log filenames and settings
637 char filename[FILENAME_MAX + 1];
638 snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);
639 stdout_filename = config_get("global", "debug log", filename);
641 snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);
642 stderr_filename = config_get("global", "error log", filename);
644 snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);
645 stdaccess_filename = config_get("global", "access log", filename);
648 error_log_throttle_period_backup =
649 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
651 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
653 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", (long long int)error_log_errors_per_period);
654 setenv("NETDATA_ERRORS_PER_PERIOD", config_get("global", "errors to trigger flood protection", ""), 1);
657 stdout_filename = stderr_filename = stdaccess_filename = "system";
658 error_log_throttle_period = 0;
659 error_log_errors_per_period = 0;
661 error_log_limit_unlimited();
664 // --------------------------------------------------------------------
667 #ifdef MADV_MERGEABLE
668 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
670 #warning "Kernel memory deduplication (KSM) is not available"
673 // --------------------------------------------------------------------
674 // get various system parameters
678 get_system_pid_max();
681 // --------------------------------------------------------------------
682 // find the system hostname
685 char hostnamebuf[HOSTNAME_MAX + 1];
686 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
687 error("WARNING: Cannot get machine hostname.");
689 hostname = config_get("global", "hostname", hostnamebuf);
690 debug(D_OPTIONS, "hostname set to '%s'", hostname);
692 setenv("NETDATA_HOSTNAME", hostname, 1);
696 // --------------------------------------------------------------------
697 // find we need to send data to a central netdata
702 // --------------------------------------------------------------------
703 // get default memory mode for the database
705 if(rrdpush_exclusive) {
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(rrdpush_exclusive) {
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 && !rrdpush_exclusive) {
848 char filename[FILENAME_MAX + 1];
849 snprintfz(filename, FILENAME_MAX, "%s/aggregated_hosts.conf", netdata_configured_config_dir);
850 appconfig_load(&stream_config, filename, 0);
851 create_listen_sockets();
855 // initialize the log files
856 open_all_log_files();
858 #ifdef NETDATA_INTERNAL_CHECKS
859 if(debug_flags != 0) {
860 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
861 if(setrlimit(RLIMIT_CORE, &rl) != 0)
862 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
863 #ifdef HAVE_SYS_PRCTL_H
864 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
867 #endif /* NETDATA_INTERNAL_CHECKS */
870 // fork, switch user, create pid file, set process priority
871 if(become_daemon(dont_fork, user) == -1)
872 fatal("Cannot daemonize myself.");
874 info("netdata started on pid %d.", getpid());
877 // ------------------------------------------------------------------------
878 // set default pthread stack size - after we have forked
880 if(stacksize < wanted_stacksize) {
881 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
883 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
885 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
889 // ------------------------------------------------------------------------
890 // initialize health monitoring
895 // ------------------------------------------------------------------------
896 // initialize the registry
901 // ------------------------------------------------------------------------
902 // initialize rrd host
911 // ------------------------------------------------------------------------
912 // enable log flood protection
914 error_log_limit_reset();
917 // ------------------------------------------------------------------------
920 web_server_threading_selection();
922 for (i = 0; static_threads[i].name != NULL ; i++) {
923 struct netdata_static_thread *st = &static_threads[i];
926 st->thread = mallocz(sizeof(pthread_t));
928 debug(D_SYSTEM, "Starting thread %s.", st->name);
930 if(pthread_create(st->thread, &attr, st->start_routine, st))
931 error("failed to create new thread for %s.", st->name);
933 else if(pthread_detach(*st->thread))
934 error("Cannot request detach of newly created %s thread.", st->name);
936 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
939 info("netdata initialization completed. Enjoy real-time performance monitoring!");
942 // ------------------------------------------------------------------------
943 // block signals while initializing threads.
947 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
948 error("Could not unblock signals for threads");
951 // Handle flags set in the signal handler.
955 debug(D_EXIT, "Exit main loop of netdata.");
956 netdata_cleanup_and_exit(0);