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
29 info("netdata exiting. Bye bye...");
33 struct netdata_static_thread static_threads[] = {
34 #ifdef INTERNAL_PLUGIN_NFACCT
35 // nfacct requires root access
36 // so, we build it as an external plugin with setuid to root
37 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
40 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
41 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
42 #if defined(__FreeBSD__)
43 {"freebsd", "plugins", "freebsd", 1, NULL, NULL, freebsd_main},
44 #elif defined(__APPLE__)
45 {"macos", "plugins", "macos", 1, NULL, NULL, macos_main},
47 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
48 {"diskspace", "plugins", "diskspace", 1, NULL, NULL, proc_diskspace_main},
49 #endif /* __FreeBSD__, __APPLE__*/
50 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
51 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
52 {"backends", NULL, NULL, 1, NULL, NULL, backends_main},
53 {"health", NULL, NULL, 1, NULL, NULL, health_main},
54 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
55 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
56 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
57 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
60 void web_server_threading_selection(void) {
61 int threaded = config_get_boolean("global", "multi threaded web server", 1);
64 for(i = 0; static_threads[i].name ; i++) {
65 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
66 static_threads[i].enabled = threaded?1:0;
68 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
69 static_threads[i].enabled = threaded?0:1;
72 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
74 web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
76 #ifdef NETDATA_WITH_ZLIB
77 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
79 char *s = config_get("global", "web compression strategy", "default");
80 if(!strcmp(s, "default"))
81 web_gzip_strategy = Z_DEFAULT_STRATEGY;
82 else if(!strcmp(s, "filtered"))
83 web_gzip_strategy = Z_FILTERED;
84 else if(!strcmp(s, "huffman only"))
85 web_gzip_strategy = Z_HUFFMAN_ONLY;
86 else if(!strcmp(s, "rle"))
87 web_gzip_strategy = Z_RLE;
88 else if(!strcmp(s, "fixed"))
89 web_gzip_strategy = Z_FIXED;
91 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
92 web_gzip_strategy = Z_DEFAULT_STRATEGY;
95 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
96 if(web_gzip_level < 1) {
97 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
100 else if(web_gzip_level > 9) {
101 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
104 #endif /* NETDATA_WITH_ZLIB */
108 int killpid(pid_t pid, int sig)
111 debug(D_EXIT, "Request to kill pid %d", pid);
114 if(kill(pid, 0) == -1) {
117 error("Request to kill pid %d, but it is not running.", pid);
121 error("Request to kill pid %d, but I do not have enough permissions.", pid);
125 error("Request to kill pid %d, but I received an error.", pid);
131 ret = kill(pid, sig);
135 error("Cannot kill pid %d, but it is not running.", pid);
139 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
143 error("Cannot kill pid %d, but I received an error.", pid);
154 error_log_limit_unlimited();
158 struct web_client *w;
159 for(w = web_clients; w ; w = w->next) {
160 info("Stopping web client %s", w->client_ip);
161 pthread_cancel(w->thread);
163 // pthread_join(w->thread, NULL);
167 for (i = 0; static_threads[i].name != NULL ; i++) {
168 if(static_threads[i].enabled && static_threads[i].thread) {
169 info("Stopping %s thread", static_threads[i].name);
170 pthread_cancel(*static_threads[i].thread);
172 // pthread_join(*static_threads[i].thread, NULL);
174 static_threads[i].thread = NULL;
179 info("Killing tc-qos-helper process %d", tc_child_pid);
180 if(killpid(tc_child_pid, SIGTERM) != -1)
181 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
186 for(cd = pluginsd_root ; cd ; cd = cd->next) {
187 if(cd->enabled && !cd->obsolete) {
188 if(cd->thread != (pthread_t)NULL) {
189 info("Stopping %s plugin thread", cd->id);
190 pthread_cancel(cd->thread);
192 // pthread_join(cd->thread, NULL);
193 cd->thread = (pthread_t)NULL;
197 info("killing %s plugin child process pid %d", cd->id, cd->pid);
198 if(killpid(cd->pid, SIGTERM) != -1)
199 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
208 // if, for any reason there is any child exited
210 info("Cleaning up an other children");
211 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
213 info("All threads/childs stopped.");
216 struct option_def options[] = {
217 // opt description arg name default value
218 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
219 {'D', "Disable fork into background", NULL, NULL},
220 {'h', "Display help message", NULL, NULL},
221 {'P', "File to save a pid while running", "FILE", NULL},
222 {'i', "The IP address to listen to.", "address", "All addresses"},
223 {'k', "Check daemon configuration.", NULL, NULL},
224 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
225 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
226 {'t', "The frequency in seconds, for data collection. \
227 Same as 'update every' config file option.", "seconds", "1"},
228 {'u', "System username to run as.", "username", "netdata"},
229 {'v', "Version of the program", NULL, NULL},
230 {'W', "vendor options.", "stacksize=N|unittest|debug_flags=N", NULL},
233 void help(int exitcode) {
240 int num_opts = sizeof(options) / sizeof(struct option_def);
244 // Compute maximum argument length
245 for( i = 0; i < num_opts; i++ ) {
246 if(options[i].arg_name) {
247 int len_arg = (int)strlen(options[i].arg_name);
248 if(len_arg > max_len_arg) max_len_arg = len_arg;
252 fprintf(stream, "SYNOPSIS: netdata [options]\n");
253 fprintf(stream, "\n");
254 fprintf(stream, "Options:\n");
256 // Output options description.
257 for( i = 0; i < num_opts; i++ ) {
258 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
259 if(options[i].default_value) {
260 fprintf(stream, " Default: %s\n", options[i].default_value);
262 fprintf(stream, "\n");
270 // TODO: Remove this function with the nix major release.
271 void remove_option(int opt_index, int *argc, char **argv) {
273 // remove the options.
276 for(i = opt_index; i < *argc; i++) {
280 } while(argv[i][0] != '-' && opt_index >= *argc);
283 static const char *verify_required_directory(const char *dir) {
285 fatal("Cannot cd to directory '%s'", dir);
287 DIR *d = opendir(dir);
289 fatal("Cannot examine the contents of directory '%s'", dir);
295 int main(int argc, char **argv)
297 char *hostname = "localhost";
298 int i, check_config = 0;
299 int config_loaded = 0;
301 size_t wanted_stacksize = 0, stacksize = 0;
304 // set the name for logging
305 program_name = "netdata";
307 // parse depercated options
308 // TODO: Remove this block with the next major release.
312 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
313 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
314 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
315 remove_option(i, &argc, argv);
317 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
319 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
320 remove_option(i, &argc, argv);
322 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
323 config_set("global", "host access prefix", argv[i+1]);
324 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
325 remove_option(i, &argc, argv);
327 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
328 config_set("global", "history", argv[i+1]);
329 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
330 remove_option(i, &argc, argv);
338 int num_opts = sizeof(options) / sizeof(struct option_def);
339 char optstring[(num_opts * 2) + 1];
342 for( i = 0; i < num_opts; i++ ) {
343 optstring[string_i] = options[i].val;
345 if(options[i].arg_name) {
346 optstring[string_i] = ':';
352 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
355 if(load_config(optarg, 1) != 1) {
356 error("Cannot load configuration file %s.", optarg);
360 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
371 config_set("global", "bind to", optarg);
378 strncpy(pidfile, optarg, FILENAME_MAX);
379 pidfile[FILENAME_MAX] = '\0';
382 config_set("global", "default port", optarg);
385 config_set("global", "host access prefix", optarg);
388 config_set("global", "update every", optarg);
391 config_set("global", "run as user", optarg);
394 // TODO: Outsource version to makefile which can compute version from git.
395 printf("netdata %s\n", VERSION);
399 char* stacksize_string = "stacksize=";
400 char* debug_flags_string = "debug_flags=";
401 if(strcmp(optarg, "unittest") == 0) {
402 rrd_update_every = 1;
403 if(run_all_mockup_tests()) exit(1);
404 if(unit_test_storage()) exit(1);
405 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
407 } else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
408 optarg += strlen(stacksize_string);
409 config_set("global", "pthread stack size", optarg);
410 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
411 optarg += strlen(debug_flags_string);
412 config_set("global", "debug flags", optarg);
413 debug_flags = strtoull(optarg, NULL, 0);
425 load_config(NULL, 0);
428 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
430 setenv("MALLOC_ARENA_MAX", pmax, 1);
432 #if defined(HAVE_C_MALLOPT)
433 int i = config_get_number("global", "glibc malloc arena max for netdata", 1);
435 mallopt(M_ARENA_MAX, 1);
438 char *config_dir = config_get("global", "config directory", CONFIG_DIR);
440 // prepare configuration environment variables for the plugins
441 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(config_dir) , 1);
442 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(config_get("global", "plugins directory" , PLUGINS_DIR)), 1);
443 setenv("NETDATA_WEB_DIR" , verify_required_directory(config_get("global", "web files directory", WEB_DIR)) , 1);
444 setenv("NETDATA_CACHE_DIR" , verify_required_directory(config_get("global", "cache directory" , CACHE_DIR)) , 1);
445 setenv("NETDATA_LIB_DIR" , verify_required_directory(config_get("global", "lib directory" , VARLIB_DIR)) , 1);
446 setenv("NETDATA_LOG_DIR" , verify_required_directory(config_get("global", "log directory" , LOG_DIR)) , 1);
448 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
449 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
451 // disable buffering for python plugins
452 setenv("PYTHONUNBUFFERED", "1", 1);
454 // avoid flood calls to stat(/etc/localtime)
455 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
456 setenv("TZ", ":/etc/localtime", 0);
458 // work while we are cd into config_dir
459 // to allow the plugins refer to their config
460 // files using relative filenames
461 if(chdir(config_dir) == -1)
462 fatal("Cannot cd to '%s'", config_dir);
464 char path[1024 + 1], *p = getenv("PATH");
465 if(!p) p = "/bin:/usr/bin";
466 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
467 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
472 char *flags = config_get("global", "debug flags", "0x00000000");
473 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
475 debug_flags = strtoull(flags, NULL, 0);
476 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
478 if(debug_flags != 0) {
479 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
480 if(setrlimit(RLIMIT_CORE, &rl) != 0)
481 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
483 #if !(defined(__FreeBSD__) || defined(__APPLE__))
484 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
485 #endif /* __FreeBSD__ || __APPLE__*/
488 // --------------------------------------------------------------------
490 #ifdef MADV_MERGEABLE
491 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
493 #warning "Kernel memory deduplication (KSM) is not available"
496 // --------------------------------------------------------------------
498 global_host_prefix = config_get("global", "host access prefix", "");
499 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
503 get_system_pid_max();
505 // --------------------------------------------------------------------
507 stdout_filename = config_get("global", "debug log", LOG_DIR "/debug.log");
508 stderr_filename = config_get("global", "error log", LOG_DIR "/error.log");
509 stdaccess_filename = config_get("global", "access log", LOG_DIR "/access.log");
511 error_log_throttle_period_backup =
512 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
513 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
515 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
516 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
519 stdout_filename = stderr_filename = stdaccess_filename = "system";
520 error_log_throttle_period = 0;
521 error_log_errors_per_period = 0;
523 error_log_limit_unlimited();
525 // --------------------------------------------------------------------
527 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
529 // --------------------------------------------------------------------
532 char hostnamebuf[HOSTNAME_MAX + 1];
533 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
534 error("WARNING: Cannot get machine hostname.");
535 hostname = config_get("global", "hostname", hostnamebuf);
536 debug(D_OPTIONS, "hostname set to '%s'", hostname);
537 setenv("NETDATA_HOSTNAME", hostname, 1);
540 // --------------------------------------------------------------------
542 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
543 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
544 error("Invalid history entries %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
545 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
548 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
551 // --------------------------------------------------------------------
553 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
554 if(rrd_update_every < 1 || rrd_update_every > 600) {
555 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
556 rrd_update_every = UPDATE_EVERY;
558 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
560 // let the plugins know the min update_every
563 snprintfz(buf, 15, "%d", rrd_update_every);
564 setenv("NETDATA_UPDATE_EVERY", buf, 1);
567 // --------------------------------------------------------------------
569 // block signals while initializing threads.
570 // this causes the threads to block signals.
573 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
574 error("Could not block signals for threads");
576 // Catch signals which we want to use
580 // ingore all signals while we run in a signal handler
581 sigfillset(&sa.sa_mask);
583 // INFO: If we add signals here we have to unblock them
584 // at popen.c when running a external plugin.
586 // Ignore SIGPIPE completely.
587 sa.sa_handler = SIG_IGN;
588 if(sigaction(SIGPIPE, &sa, NULL) == -1)
589 error("Failed to change signal handler for SIGPIPE");
591 sa.sa_handler = sig_handler_exit;
592 if(sigaction(SIGINT, &sa, NULL) == -1)
593 error("Failed to change signal handler for SIGINT");
595 sa.sa_handler = sig_handler_exit;
596 if(sigaction(SIGTERM, &sa, NULL) == -1)
597 error("Failed to change signal handler for SIGTERM");
599 sa.sa_handler = sig_handler_logrotate;
600 if(sigaction(SIGHUP, &sa, NULL) == -1)
601 error("Failed to change signal handler for SIGHUP");
603 // save database on SIGUSR1
604 sa.sa_handler = sig_handler_save;
605 if(sigaction(SIGUSR1, &sa, NULL) == -1)
606 error("Failed to change signal handler for SIGUSR1");
608 // reload health configuration on SIGUSR2
609 sa.sa_handler = sig_handler_reload_health;
610 if(sigaction(SIGUSR2, &sa, NULL) == -1)
611 error("Failed to change signal handler for SIGUSR2");
613 // --------------------------------------------------------------------
615 i = pthread_attr_init(&attr);
617 fatal("pthread_attr_init() failed with code %d.", i);
619 i = pthread_attr_getstacksize(&attr, &stacksize);
621 fatal("pthread_attr_getstacksize() failed with code %d.", i);
623 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
625 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
627 // --------------------------------------------------------------------
629 for (i = 0; static_threads[i].name != NULL ; i++) {
630 struct netdata_static_thread *st = &static_threads[i];
632 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
633 if(st->enabled && st->init_routine) st->init_routine();
636 // --------------------------------------------------------------------
638 // get the user we should run
639 // IMPORTANT: this is required before web_files_uid()
640 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
642 // IMPORTANT: these have to run once, while single threaded
643 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
646 // --------------------------------------------------------------------
649 create_listen_sockets();
652 // initialize the log files
653 open_all_log_files();
655 #ifdef NETDATA_INTERNAL_CHECKS
656 if(debug_flags != 0) {
657 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
658 if(setrlimit(RLIMIT_CORE, &rl) != 0)
659 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
660 #if !(defined(__FreeBSD__) || defined(__APPLE__))
661 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
662 #endif /* __FreeBSD__ || __APPLE__*/
664 #endif /* NETDATA_INTERNAL_CHECKS */
666 // fork, switch user, create pid file, set process priority
667 if(become_daemon(dont_fork, user) == -1)
668 fatal("Cannot daemonize myself.");
670 info("netdata started on pid %d.", getpid());
672 // ------------------------------------------------------------------------
673 // get default pthread stack size
675 if(stacksize < wanted_stacksize) {
676 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
678 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
680 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
683 // ------------------------------------------------------------------------
684 // initialize rrd host
686 rrdhost_init(hostname);
688 // ------------------------------------------------------------------------
689 // initialize the registry
693 // ------------------------------------------------------------------------
694 // initialize health monitoring
701 // ------------------------------------------------------------------------
702 // enable log flood protection
704 error_log_limit_reset();
706 // ------------------------------------------------------------------------
709 web_server_threading_selection();
711 for (i = 0; static_threads[i].name != NULL ; i++) {
712 struct netdata_static_thread *st = &static_threads[i];
715 st->thread = mallocz(sizeof(pthread_t));
717 debug(D_SYSTEM, "Starting thread %s.", st->name);
719 if(pthread_create(st->thread, &attr, st->start_routine, st))
720 error("failed to create new thread for %s.", st->name);
722 else if(pthread_detach(*st->thread))
723 error("Cannot request detach of newly created %s thread.", st->name);
725 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
728 info("netdata initialization completed. Enjoy real-time performance monitoring!");
730 // ------------------------------------------------------------------------
731 // block signals while initializing threads.
735 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
736 error("Could not unblock signals for threads");
739 // Handle flags set in the signal handler.
743 debug(D_EXIT, "Exit main loop of netdata.");
744 netdata_cleanup_and_exit(0);