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()");
11 #ifdef NETDATA_INTERNAL_CHECKS
20 if(unlink(pidfile) != 0)
21 error("Cannot unlink pidfile '%s'.", pidfile);
24 info("NetData exiting. Bye bye...");
28 struct netdata_static_thread static_threads[] = {
29 #ifdef INTERNAL_PLUGIN_NFACCT
30 // nfacct requires root access
31 // so, we build it as an external plugin with setuid to root
32 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
35 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
36 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
37 #if defined(__FreeBSD__)
38 {"freebsd", "plugins", "freebsd", 1, NULL, NULL, freebsd_main},
39 #elif defined(__APPLE__)
40 {"macos", "plugins", "macos", 1, NULL, NULL, macos_main},
42 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
43 #endif /* __FreeBSD__, __APPLE__*/
44 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
45 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
46 {"backends", NULL, NULL, 1, NULL, NULL, backends_main},
47 {"health", NULL, NULL, 1, NULL, NULL, health_main},
48 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
49 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
50 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
51 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
54 void web_server_threading_selection(void) {
55 int threaded = config_get_boolean("global", "multi threaded web server", 1);
58 for(i = 0; static_threads[i].name ; i++) {
59 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
60 static_threads[i].enabled = threaded?1:0;
62 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
63 static_threads[i].enabled = threaded?0:1;
66 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
68 web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
70 #ifdef NETDATA_WITH_ZLIB
71 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
73 char *s = config_get("global", "web compression strategy", "default");
74 if(!strcmp(s, "default"))
75 web_gzip_strategy = Z_DEFAULT_STRATEGY;
76 else if(!strcmp(s, "filtered"))
77 web_gzip_strategy = Z_FILTERED;
78 else if(!strcmp(s, "huffman only"))
79 web_gzip_strategy = Z_HUFFMAN_ONLY;
80 else if(!strcmp(s, "rle"))
81 web_gzip_strategy = Z_RLE;
82 else if(!strcmp(s, "fixed"))
83 web_gzip_strategy = Z_FIXED;
85 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
86 web_gzip_strategy = Z_DEFAULT_STRATEGY;
89 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
90 if(web_gzip_level < 1) {
91 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
94 else if(web_gzip_level > 9) {
95 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
98 #endif /* NETDATA_WITH_ZLIB */
102 int killpid(pid_t pid, int sig)
105 debug(D_EXIT, "Request to kill pid %d", pid);
108 if(kill(pid, 0) == -1) {
111 error("Request to kill pid %d, but it is not running.", pid);
115 error("Request to kill pid %d, but I do not have enough permissions.", pid);
119 error("Request to kill pid %d, but I received an error.", pid);
125 ret = kill(pid, sig);
129 error("Cannot kill pid %d, but it is not running.", pid);
133 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
137 error("Cannot kill pid %d, but I received an error.", pid);
148 error_log_limit_unlimited();
152 struct web_client *w;
153 for(w = web_clients; w ; w = w->next) {
154 info("Stopping web client %s", w->client_ip);
155 pthread_cancel(w->thread);
157 // pthread_join(w->thread, NULL);
161 for (i = 0; static_threads[i].name != NULL ; i++) {
162 if(static_threads[i].enabled && static_threads[i].thread) {
163 info("Stopping %s thread", static_threads[i].name);
164 pthread_cancel(*static_threads[i].thread);
166 // pthread_join(*static_threads[i].thread, NULL);
168 static_threads[i].thread = NULL;
173 info("Killing tc-qos-helper process %d", tc_child_pid);
174 if(killpid(tc_child_pid, SIGTERM) != -1)
175 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
180 for(cd = pluginsd_root ; cd ; cd = cd->next) {
181 if(cd->enabled && !cd->obsolete) {
182 if(cd->thread != (pthread_t)NULL) {
183 info("Stopping %s plugin thread", cd->id);
184 pthread_cancel(cd->thread);
186 // pthread_join(cd->thread, NULL);
187 cd->thread = (pthread_t)NULL;
191 info("killing %s plugin child process pid %d", cd->id, cd->pid);
192 if(killpid(cd->pid, SIGTERM) != -1)
193 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
202 // if, for any reason there is any child exited
204 info("Cleaning up an other children");
205 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
207 info("All threads/childs stopped.");
210 struct option_def options[] = {
211 // opt description arg name default value
212 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
213 {'D', "Disable fork into background", NULL, NULL},
214 {'h', "Display help message", NULL, NULL},
215 {'P', "File to save a pid while running", "FILE", NULL},
216 {'i', "The IP address to listen to.", "address", "All addresses"},
217 {'k', "Check daemon configuration.", NULL, NULL},
218 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
219 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
220 {'t', "The frequency in seconds, for data collection. \
221 Same as 'update every' config file option.", "seconds", "1"},
222 {'u', "System username to run as.", "username", "netdata"},
223 {'v', "Version of the program", NULL, NULL},
224 {'W', "vendor options.", "stacksize=N|unittest|debug_flags=N", NULL},
227 void help(int exitcode) {
234 int num_opts = sizeof(options) / sizeof(struct option_def);
238 // Compute maximum argument length
239 for( i = 0; i < num_opts; i++ ) {
240 if(options[i].arg_name) {
241 int len_arg = (int)strlen(options[i].arg_name);
242 if(len_arg > max_len_arg) max_len_arg = len_arg;
246 fprintf(stream, "SYNOPSIS: netdata [options]\n");
247 fprintf(stream, "\n");
248 fprintf(stream, "Options:\n");
250 // Output options description.
251 for( i = 0; i < num_opts; i++ ) {
252 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
253 if(options[i].default_value) {
254 fprintf(stream, " Default: %s\n", options[i].default_value);
256 fprintf(stream, "\n");
264 // TODO: Remove this function with the nix major release.
265 void remove_option(int opt_index, int *argc, char **argv) {
267 // remove the options.
270 for(i = opt_index; i < *argc; i++) {
274 } while(argv[i][0] != '-' && opt_index >= *argc);
277 static const char *verify_required_directory(const char *dir) {
279 fatal("Cannot cd to directory '%s'", dir);
281 DIR *d = opendir(dir);
283 fatal("Cannot examine the contents of directory '%s'", dir);
289 int main(int argc, char **argv)
291 char *hostname = "localhost";
292 int i, check_config = 0;
293 int config_loaded = 0;
295 size_t wanted_stacksize = 0, stacksize = 0;
298 // set the name for logging
299 program_name = "netdata";
301 // parse depercated options
302 // TODO: Remove this block with the next major release.
306 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
307 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
308 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
309 remove_option(i, &argc, argv);
311 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
313 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
314 remove_option(i, &argc, argv);
316 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
317 config_set("global", "host access prefix", argv[i+1]);
318 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
319 remove_option(i, &argc, argv);
321 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
322 config_set("global", "history", argv[i+1]);
323 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
324 remove_option(i, &argc, argv);
332 int num_opts = sizeof(options) / sizeof(struct option_def);
333 char optstring[(num_opts * 2) + 1];
336 for( i = 0; i < num_opts; i++ ) {
337 optstring[string_i] = options[i].val;
339 if(options[i].arg_name) {
340 optstring[string_i] = ':';
346 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
349 if(load_config(optarg, 1) != 1) {
350 error("Cannot load configuration file %s.", optarg);
354 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
365 config_set("global", "bind to", optarg);
372 strncpy(pidfile, optarg, FILENAME_MAX);
373 pidfile[FILENAME_MAX] = '\0';
376 config_set("global", "default port", optarg);
379 config_set("global", "host access prefix", optarg);
382 config_set("global", "update every", optarg);
385 config_set("global", "run as user", optarg);
388 // TODO: Outsource version to makefile which can compute version from git.
389 printf("netdata %s\n", VERSION);
393 char* stacksize_string = "stacksize=";
394 char* debug_flags_string = "debug_flags=";
395 if(strcmp(optarg, "unittest") == 0) {
396 rrd_update_every = 1;
397 if(run_all_mockup_tests()) exit(1);
398 if(unit_test_storage()) exit(1);
399 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
401 } else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
402 optarg += strlen(stacksize_string);
403 config_set("global", "pthread stack size", optarg);
404 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
405 optarg += strlen(debug_flags_string);
406 config_set("global", "debug flags", optarg);
407 debug_flags = strtoull(optarg, NULL, 0);
419 load_config(NULL, 0);
422 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
424 setenv("MALLOC_ARENA_MAX", pmax, 1);
426 #if defined(HAVE_C_MALLOPT)
427 int i = config_get_number("global", "glibc malloc arena max for netdata", 1);
429 mallopt(M_ARENA_MAX, 1);
432 char *config_dir = config_get("global", "config directory", CONFIG_DIR);
434 // prepare configuration environment variables for the plugins
435 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(config_dir) , 1);
436 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(config_get("global", "plugins directory" , PLUGINS_DIR)), 1);
437 setenv("NETDATA_WEB_DIR" , verify_required_directory(config_get("global", "web files directory", WEB_DIR)) , 1);
438 setenv("NETDATA_CACHE_DIR" , verify_required_directory(config_get("global", "cache directory" , CACHE_DIR)) , 1);
439 setenv("NETDATA_LIB_DIR" , verify_required_directory(config_get("global", "lib directory" , VARLIB_DIR)) , 1);
440 setenv("NETDATA_LOG_DIR" , verify_required_directory(config_get("global", "log directory" , LOG_DIR)) , 1);
442 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
443 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
445 // disable buffering for python plugins
446 setenv("PYTHONUNBUFFERED", "1", 1);
448 // avoid flood calls to stat(/etc/localtime)
449 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
450 setenv("TZ", ":/etc/localtime", 0);
452 // work while we are cd into config_dir
453 // to allow the plugins refer to their config
454 // files using relative filenames
455 if(chdir(config_dir) == -1)
456 fatal("Cannot cd to '%s'", config_dir);
458 char path[1024 + 1], *p = getenv("PATH");
459 if(!p) p = "/bin:/usr/bin";
460 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
461 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
466 char *flags = config_get("global", "debug flags", "0x00000000");
467 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
469 debug_flags = strtoull(flags, NULL, 0);
470 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
472 if(debug_flags != 0) {
473 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
474 if(setrlimit(RLIMIT_CORE, &rl) != 0)
475 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
477 #if !(defined(__FreeBSD__) || defined(__APPLE__))
478 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
479 #endif /* __FreeBSD__ || __APPLE__*/
482 // --------------------------------------------------------------------
484 #ifdef MADV_MERGEABLE
485 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
487 #warning "Kernel memory deduplication (KSM) is not available"
490 // --------------------------------------------------------------------
492 global_host_prefix = config_get("global", "host access prefix", "");
493 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
497 get_system_pid_max();
499 // --------------------------------------------------------------------
501 stdout_filename = config_get("global", "debug log", LOG_DIR "/debug.log");
502 stderr_filename = config_get("global", "error log", LOG_DIR "/error.log");
503 stdaccess_filename = config_get("global", "access log", LOG_DIR "/access.log");
505 error_log_throttle_period_backup =
506 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
507 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
509 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
510 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
513 stdout_filename = stderr_filename = stdaccess_filename = "system";
514 error_log_throttle_period = 0;
515 error_log_errors_per_period = 0;
517 error_log_limit_unlimited();
519 // --------------------------------------------------------------------
521 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
523 // --------------------------------------------------------------------
526 char hostnamebuf[HOSTNAME_MAX + 1];
527 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
528 error("WARNING: Cannot get machine hostname.");
529 hostname = config_get("global", "hostname", hostnamebuf);
530 debug(D_OPTIONS, "hostname set to '%s'", hostname);
531 setenv("NETDATA_HOSTNAME", hostname, 1);
534 // --------------------------------------------------------------------
536 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
537 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
538 error("Invalid history entries %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
539 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
542 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
545 // --------------------------------------------------------------------
547 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
548 if(rrd_update_every < 1 || rrd_update_every > 600) {
549 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
550 rrd_update_every = UPDATE_EVERY;
552 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
554 // let the plugins know the min update_every
557 snprintfz(buf, 15, "%d", rrd_update_every);
558 setenv("NETDATA_UPDATE_EVERY", buf, 1);
561 // --------------------------------------------------------------------
563 // block signals while initializing threads.
564 // this causes the threads to block signals.
567 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
568 error("Could not block signals for threads");
570 // Catch signals which we want to use
574 // ingore all signals while we run in a signal handler
575 sigfillset(&sa.sa_mask);
577 // INFO: If we add signals here we have to unblock them
578 // at popen.c when running a external plugin.
580 // Ignore SIGPIPE completely.
581 sa.sa_handler = SIG_IGN;
582 if(sigaction(SIGPIPE, &sa, NULL) == -1)
583 error("Failed to change signal handler for SIGPIPE");
585 sa.sa_handler = sig_handler_exit;
586 if(sigaction(SIGINT, &sa, NULL) == -1)
587 error("Failed to change signal handler for SIGINT");
589 sa.sa_handler = sig_handler_exit;
590 if(sigaction(SIGTERM, &sa, NULL) == -1)
591 error("Failed to change signal handler for SIGTERM");
593 sa.sa_handler = sig_handler_logrotate;
594 if(sigaction(SIGHUP, &sa, NULL) == -1)
595 error("Failed to change signal handler for SIGHUP");
597 // save database on SIGUSR1
598 sa.sa_handler = sig_handler_save;
599 if(sigaction(SIGUSR1, &sa, NULL) == -1)
600 error("Failed to change signal handler for SIGUSR1");
602 // reload health configuration on SIGUSR2
603 sa.sa_handler = sig_handler_reload_health;
604 if(sigaction(SIGUSR2, &sa, NULL) == -1)
605 error("Failed to change signal handler for SIGUSR2");
607 // --------------------------------------------------------------------
609 i = pthread_attr_init(&attr);
611 fatal("pthread_attr_init() failed with code %d.", i);
613 i = pthread_attr_getstacksize(&attr, &stacksize);
615 fatal("pthread_attr_getstacksize() failed with code %d.", i);
617 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
619 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
621 // --------------------------------------------------------------------
623 for (i = 0; static_threads[i].name != NULL ; i++) {
624 struct netdata_static_thread *st = &static_threads[i];
626 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
627 if(st->enabled && st->init_routine) st->init_routine();
630 // --------------------------------------------------------------------
632 // get the user we should run
633 // IMPORTANT: this is required before web_files_uid()
634 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
636 // IMPORTANT: these have to run once, while single threaded
637 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
640 // --------------------------------------------------------------------
643 create_listen_sockets();
646 // initialize the log files
647 open_all_log_files();
649 #ifdef NETDATA_INTERNAL_CHECKS
650 if(debug_flags != 0) {
651 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
652 if(setrlimit(RLIMIT_CORE, &rl) != 0)
653 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
654 #if !(defined(__FreeBSD__) || defined(__APPLE__))
655 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
656 #endif /* __FreeBSD__ || __APPLE__*/
658 #endif /* NETDATA_INTERNAL_CHECKS */
660 // fork, switch user, create pid file, set process priority
661 if(become_daemon(dont_fork, user) == -1)
662 fatal("Cannot daemonize myself.");
664 info("NetData started on pid %d", getpid());
667 // ------------------------------------------------------------------------
668 // get default pthread stack size
670 if(stacksize < wanted_stacksize) {
671 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
673 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
675 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
678 // ------------------------------------------------------------------------
679 // initialize rrd host
681 rrdhost_init(hostname);
683 // ------------------------------------------------------------------------
684 // initialize the registry
688 // ------------------------------------------------------------------------
689 // initialize health monitoring
696 // ------------------------------------------------------------------------
697 // enable log flood protection
699 error_log_limit_reset();
701 // ------------------------------------------------------------------------
704 web_server_threading_selection();
706 for (i = 0; static_threads[i].name != NULL ; i++) {
707 struct netdata_static_thread *st = &static_threads[i];
710 st->thread = mallocz(sizeof(pthread_t));
712 debug(D_SYSTEM, "Starting thread %s.", st->name);
714 if(pthread_create(st->thread, &attr, st->start_routine, st))
715 error("failed to create new thread for %s.", st->name);
717 else if(pthread_detach(*st->thread))
718 error("Cannot request detach of newly created %s thread.", st->name);
720 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
723 // ------------------------------------------------------------------------
724 // block signals while initializing threads.
728 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
729 error("Could not unblock signals for threads");
732 // Handle flags set in the signal handler.
736 debug(D_EXIT, "Exit main loop of netdata.");
737 netdata_cleanup_and_exit(0);