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) {
183 info("Stopping %s plugin thread", cd->id);
184 pthread_cancel(cd->thread);
186 // pthread_join(cd->thread, NULL);
190 info("killing %s plugin child process pid %d", cd->id, cd->pid);
191 if(killpid(cd->pid, SIGTERM) != -1)
192 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
201 // if, for any reason there is any child exited
203 info("Cleaning up an other children");
204 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
206 info("All threads/childs stopped.");
209 struct option_def options[] = {
210 // opt description arg name default value
211 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
212 {'D', "Disable fork into background", NULL, NULL},
213 {'h', "Display help message", NULL, NULL},
214 {'P', "File to save a pid while running", "FILE", NULL},
215 {'i', "The IP address to listen to.", "address", "All addresses"},
216 {'k', "Check daemon configuration.", NULL, NULL},
217 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
218 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
219 {'t', "The frequency in seconds, for data collection. \
220 Same as 'update every' config file option.", "seconds", "1"},
221 {'u', "System username to run as.", "username", "netdata"},
222 {'v', "Version of the program", NULL, NULL},
223 {'W', "vendor options.", "stacksize=N|unittest|debug_flags=N", NULL},
226 void help(int exitcode) {
233 int num_opts = sizeof(options) / sizeof(struct option_def);
237 // Compute maximum argument length
238 for( i = 0; i < num_opts; i++ ) {
239 if(options[i].arg_name) {
240 int len_arg = (int)strlen(options[i].arg_name);
241 if(len_arg > max_len_arg) max_len_arg = len_arg;
245 fprintf(stream, "SYNOPSIS: netdata [options]\n");
246 fprintf(stream, "\n");
247 fprintf(stream, "Options:\n");
249 // Output options description.
250 for( i = 0; i < num_opts; i++ ) {
251 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
252 if(options[i].default_value) {
253 fprintf(stream, " Default: %s\n", options[i].default_value);
255 fprintf(stream, "\n");
263 // TODO: Remove this function with the nix major release.
264 void remove_option(int opt_index, int *argc, char **argv) {
266 // remove the options.
269 for(i = opt_index; i < *argc; i++) {
273 } while(argv[i][0] != '-' && opt_index >= *argc);
276 static const char *verify_required_directory(const char *dir) {
278 fatal("Cannot cd to directory '%s'", dir);
280 DIR *d = opendir(dir);
282 fatal("Cannot examine the contents of directory '%s'", dir);
288 int main(int argc, char **argv)
290 char *hostname = "localhost";
291 int i, check_config = 0;
292 int config_loaded = 0;
294 size_t wanted_stacksize = 0, stacksize = 0;
297 // set the name for logging
298 program_name = "netdata";
300 // parse depercated options
301 // TODO: Remove this block with the next major release.
305 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
306 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
307 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
308 remove_option(i, &argc, argv);
310 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
312 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
313 remove_option(i, &argc, argv);
315 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
316 config_set("global", "host access prefix", argv[i+1]);
317 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
318 remove_option(i, &argc, argv);
320 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
321 config_set("global", "history", argv[i+1]);
322 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
323 remove_option(i, &argc, argv);
331 int num_opts = sizeof(options) / sizeof(struct option_def);
332 char optstring[(num_opts * 2) + 1];
335 for( i = 0; i < num_opts; i++ ) {
336 optstring[string_i] = options[i].val;
338 if(options[i].arg_name) {
339 optstring[string_i] = ':';
345 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
348 if(load_config(optarg, 1) != 1) {
349 error("Cannot load configuration file %s.", optarg);
353 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
364 config_set("global", "bind to", optarg);
371 strncpy(pidfile, optarg, FILENAME_MAX);
372 pidfile[FILENAME_MAX] = '\0';
375 config_set("global", "default port", optarg);
378 config_set("global", "host access prefix", optarg);
381 config_set("global", "update every", optarg);
384 config_set("global", "run as user", optarg);
387 // TODO: Outsource version to makefile which can compute version from git.
388 printf("netdata %s\n", VERSION);
392 char* stacksize_string = "stacksize=";
393 char* debug_flags_string = "debug_flags=";
394 if(strcmp(optarg, "unittest") == 0) {
395 rrd_update_every = 1;
396 if(run_all_mockup_tests()) exit(1);
397 if(unit_test_storage()) exit(1);
398 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
400 } else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
401 optarg += strlen(stacksize_string);
402 config_set("global", "pthread stack size", optarg);
403 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
404 optarg += strlen(debug_flags_string);
405 config_set("global", "debug flags", optarg);
406 debug_flags = strtoull(optarg, NULL, 0);
418 load_config(NULL, 0);
421 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
423 setenv("MALLOC_ARENA_MAX", pmax, 1);
425 #if defined(HAVE_C_MALLOPT)
426 int i = config_get_number("global", "glibc malloc arena max for netdata", 1);
428 mallopt(M_ARENA_MAX, 1);
431 char *config_dir = config_get("global", "config directory", CONFIG_DIR);
433 // prepare configuration environment variables for the plugins
434 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(config_dir) , 1);
435 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(config_get("global", "plugins directory" , PLUGINS_DIR)), 1);
436 setenv("NETDATA_WEB_DIR" , verify_required_directory(config_get("global", "web files directory", WEB_DIR)) , 1);
437 setenv("NETDATA_CACHE_DIR" , verify_required_directory(config_get("global", "cache directory" , CACHE_DIR)) , 1);
438 setenv("NETDATA_LIB_DIR" , verify_required_directory(config_get("global", "lib directory" , VARLIB_DIR)) , 1);
439 setenv("NETDATA_LOG_DIR" , verify_required_directory(config_get("global", "log directory" , LOG_DIR)) , 1);
441 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
442 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
444 // disable buffering for python plugins
445 setenv("PYTHONUNBUFFERED", "1", 1);
447 // avoid flood calls to stat(/etc/localtime)
448 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
449 setenv("TZ", ":/etc/localtime", 0);
451 // work while we are cd into config_dir
452 // to allow the plugins refer to their config
453 // files using relative filenames
454 if(chdir(config_dir) == -1)
455 fatal("Cannot cd to '%s'", config_dir);
457 char path[1024 + 1], *p = getenv("PATH");
458 if(!p) p = "/bin:/usr/bin";
459 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
460 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
465 char *flags = config_get("global", "debug flags", "0x00000000");
466 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
468 debug_flags = strtoull(flags, NULL, 0);
469 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
471 if(debug_flags != 0) {
472 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
473 if(setrlimit(RLIMIT_CORE, &rl) != 0)
474 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
476 #if !(defined(__FreeBSD__) || defined(__APPLE__))
477 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
478 #endif /* __FreeBSD__ || __APPLE__*/
481 // --------------------------------------------------------------------
483 #ifdef MADV_MERGEABLE
484 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
486 #warning "Kernel memory deduplication (KSM) is not available"
489 // --------------------------------------------------------------------
491 global_host_prefix = config_get("global", "host access prefix", "");
492 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
496 get_system_pid_max();
498 // --------------------------------------------------------------------
500 stdout_filename = config_get("global", "debug log", LOG_DIR "/debug.log");
501 stderr_filename = config_get("global", "error log", LOG_DIR "/error.log");
502 stdaccess_filename = config_get("global", "access log", LOG_DIR "/access.log");
504 error_log_throttle_period_backup =
505 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
506 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
508 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
509 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
512 stdout_filename = stderr_filename = stdaccess_filename = "system";
513 error_log_throttle_period = 0;
514 error_log_errors_per_period = 0;
516 error_log_limit_unlimited();
518 // --------------------------------------------------------------------
520 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
522 // --------------------------------------------------------------------
525 char hostnamebuf[HOSTNAME_MAX + 1];
526 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
527 error("WARNING: Cannot get machine hostname.");
528 hostname = config_get("global", "hostname", hostnamebuf);
529 debug(D_OPTIONS, "hostname set to '%s'", hostname);
530 setenv("NETDATA_HOSTNAME", hostname, 1);
533 // --------------------------------------------------------------------
535 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
536 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
537 error("Invalid history entries %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
538 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
541 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
544 // --------------------------------------------------------------------
546 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
547 if(rrd_update_every < 1 || rrd_update_every > 600) {
548 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
549 rrd_update_every = UPDATE_EVERY;
551 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
553 // let the plugins know the min update_every
556 snprintfz(buf, 15, "%d", rrd_update_every);
557 setenv("NETDATA_UPDATE_EVERY", buf, 1);
560 // --------------------------------------------------------------------
562 // block signals while initializing threads.
563 // this causes the threads to block signals.
566 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
567 error("Could not block signals for threads");
569 // Catch signals which we want to use
573 // ingore all signals while we run in a signal handler
574 sigfillset(&sa.sa_mask);
576 // INFO: If we add signals here we have to unblock them
577 // at popen.c when running a external plugin.
579 // Ignore SIGPIPE completely.
580 sa.sa_handler = SIG_IGN;
581 if(sigaction(SIGPIPE, &sa, NULL) == -1)
582 error("Failed to change signal handler for SIGPIPE");
584 sa.sa_handler = sig_handler_exit;
585 if(sigaction(SIGINT, &sa, NULL) == -1)
586 error("Failed to change signal handler for SIGINT");
588 sa.sa_handler = sig_handler_exit;
589 if(sigaction(SIGTERM, &sa, NULL) == -1)
590 error("Failed to change signal handler for SIGTERM");
592 sa.sa_handler = sig_handler_logrotate;
593 if(sigaction(SIGHUP, &sa, NULL) == -1)
594 error("Failed to change signal handler for SIGHUP");
596 // save database on SIGUSR1
597 sa.sa_handler = sig_handler_save;
598 if(sigaction(SIGUSR1, &sa, NULL) == -1)
599 error("Failed to change signal handler for SIGUSR1");
601 // reload health configuration on SIGUSR2
602 sa.sa_handler = sig_handler_reload_health;
603 if(sigaction(SIGUSR2, &sa, NULL) == -1)
604 error("Failed to change signal handler for SIGUSR2");
606 // --------------------------------------------------------------------
608 i = pthread_attr_init(&attr);
610 fatal("pthread_attr_init() failed with code %d.", i);
612 i = pthread_attr_getstacksize(&attr, &stacksize);
614 fatal("pthread_attr_getstacksize() failed with code %d.", i);
616 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
618 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
620 // --------------------------------------------------------------------
622 for (i = 0; static_threads[i].name != NULL ; i++) {
623 struct netdata_static_thread *st = &static_threads[i];
625 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
626 if(st->enabled && st->init_routine) st->init_routine();
629 // --------------------------------------------------------------------
631 // get the user we should run
632 // IMPORTANT: this is required before web_files_uid()
633 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
635 // IMPORTANT: these have to run once, while single threaded
636 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
639 // --------------------------------------------------------------------
642 create_listen_sockets();
645 // initialize the log files
646 open_all_log_files();
648 #ifdef NETDATA_INTERNAL_CHECKS
649 if(debug_flags != 0) {
650 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
651 if(setrlimit(RLIMIT_CORE, &rl) != 0)
652 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
653 #if !(defined(__FreeBSD__) || defined(__APPLE__))
654 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
655 #endif /* __FreeBSD__ || __APPLE__*/
657 #endif /* NETDATA_INTERNAL_CHECKS */
659 // fork, switch user, create pid file, set process priority
660 if(become_daemon(dont_fork, user) == -1)
661 fatal("Cannot daemonize myself.");
663 info("NetData started on pid %d", getpid());
666 // ------------------------------------------------------------------------
667 // get default pthread stack size
669 if(stacksize < wanted_stacksize) {
670 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
672 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
674 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
677 // ------------------------------------------------------------------------
678 // initialize rrd host
680 rrdhost_init(hostname);
682 // ------------------------------------------------------------------------
683 // initialize the registry
687 // ------------------------------------------------------------------------
688 // initialize health monitoring
695 // ------------------------------------------------------------------------
696 // enable log flood protection
698 error_log_limit_reset();
700 // ------------------------------------------------------------------------
703 web_server_threading_selection();
705 for (i = 0; static_threads[i].name != NULL ; i++) {
706 struct netdata_static_thread *st = &static_threads[i];
709 st->thread = mallocz(sizeof(pthread_t));
711 debug(D_SYSTEM, "Starting thread %s.", st->name);
713 if(pthread_create(st->thread, &attr, st->start_routine, st))
714 error("failed to create new thread for %s.", st->name);
716 else if(pthread_detach(*st->thread))
717 error("Cannot request detach of newly created %s thread.", st->name);
719 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
722 // ------------------------------------------------------------------------
723 // block signals while initializing threads.
727 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
728 error("Could not unblock signals for threads");
731 // Handle flags set in the signal handler.
735 debug(D_EXIT, "Exit main loop of netdata.");
736 netdata_cleanup_and_exit(0);