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
19 if(unlink(pidfile) != 0)
20 error("Cannot unlink pidfile '%s'.", pidfile);
23 info("NetData exiting. Bye bye...");
27 struct netdata_static_thread {
37 void (*init_routine) (void);
38 void *(*start_routine) (void *);
39 } static_threads[] = {
40 #ifdef INTERNAL_PLUGIN_NFACCT
41 // nfacct requires root access
42 // so, we build it as an external plugin with setuid to root
43 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
46 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
47 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
49 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
51 {"freebsd", "plugins", "freebsd", 1, NULL, NULL, freebsd_main},
52 #endif /* __FreeBSD__ */
54 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
55 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
56 {"backends", NULL, NULL, 1, NULL, NULL, backends_main},
57 {"health", NULL, NULL, 1, NULL, NULL, health_main},
58 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
59 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
60 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
61 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
64 void web_server_threading_selection(void) {
65 int threaded = config_get_boolean("global", "multi threaded web server", 1);
68 for(i = 0; static_threads[i].name ; i++) {
69 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
70 static_threads[i].enabled = threaded?1:0;
72 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
73 static_threads[i].enabled = threaded?0:1;
76 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
78 web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
80 #ifdef NETDATA_WITH_ZLIB
81 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
83 char *s = config_get("global", "web compression strategy", "default");
84 if(!strcmp(s, "default"))
85 web_gzip_strategy = Z_DEFAULT_STRATEGY;
86 else if(!strcmp(s, "filtered"))
87 web_gzip_strategy = Z_FILTERED;
88 else if(!strcmp(s, "huffman only"))
89 web_gzip_strategy = Z_HUFFMAN_ONLY;
90 else if(!strcmp(s, "rle"))
91 web_gzip_strategy = Z_RLE;
92 else if(!strcmp(s, "fixed"))
93 web_gzip_strategy = Z_FIXED;
95 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
96 web_gzip_strategy = Z_DEFAULT_STRATEGY;
99 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
100 if(web_gzip_level < 1) {
101 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
104 else if(web_gzip_level > 9) {
105 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
108 #endif /* NETDATA_WITH_ZLIB */
112 int killpid(pid_t pid, int sig)
115 debug(D_EXIT, "Request to kill pid %d", pid);
118 if(kill(pid, 0) == -1) {
121 error("Request to kill pid %d, but it is not running.", pid);
125 error("Request to kill pid %d, but I do not have enough permissions.", pid);
129 error("Request to kill pid %d, but I received an error.", pid);
135 ret = kill(pid, sig);
139 error("Cannot kill pid %d, but it is not running.", pid);
143 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
147 error("Cannot kill pid %d, but I received an error.", pid);
160 struct web_client *w;
161 for(w = web_clients; w ; w = w->next) {
162 debug(D_EXIT, "Stopping web client %s", w->client_ip);
163 pthread_cancel(w->thread);
164 pthread_join(w->thread, NULL);
168 for (i = 0; static_threads[i].name != NULL ; i++) {
169 if(static_threads[i].thread) {
170 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
171 pthread_cancel(*static_threads[i].thread);
172 pthread_join(*static_threads[i].thread, NULL);
173 static_threads[i].thread = NULL;
178 debug(D_EXIT, "Killing tc-qos-helper procees");
179 if(killpid(tc_child_pid, SIGTERM) != -1)
180 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
185 for(cd = pluginsd_root ; cd ; cd = cd->next) {
186 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
187 pthread_cancel(cd->thread);
188 pthread_join(cd->thread, NULL);
190 if(cd->pid && !cd->obsolete) {
191 debug(D_EXIT, "killing %s plugin process", cd->id);
192 if(killpid(cd->pid, SIGTERM) != -1)
193 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
197 // if, for any reason there is any child exited
199 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
201 debug(D_EXIT, "All threads/childs stopped.");
204 struct option_def options[] = {
205 // opt description arg name default value
206 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
207 {'D', "Disable fork into background", NULL, NULL},
208 {'h', "Display help message", NULL, NULL},
209 {'P', "File to save a pid while running", "FILE", NULL},
210 {'i', "The IP address to listen to.", "address", "All addresses"},
211 {'k', "Check daemon configuration.", NULL, NULL},
212 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
213 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
214 {'t', "The frequency in seconds, for data collection. \
215 Same as 'update every' config file option.", "seconds", "1"},
216 {'u', "System username to run as.", "username", "netdata"},
217 {'v', "Version of the program", NULL, NULL},
218 {'W', "vendor options.", "stacksize=N|unittest|debug_flags=N", NULL},
221 void help(int exitcode) {
228 int num_opts = sizeof(options) / sizeof(struct option_def);
232 // Compute maximum argument length
233 for( i = 0; i < num_opts; i++ ) {
234 if(options[i].arg_name) {
235 int len_arg = (int)strlen(options[i].arg_name);
236 if(len_arg > max_len_arg) max_len_arg = len_arg;
240 fprintf(stream, "SYNOPSIS: netdata [options]\n");
241 fprintf(stream, "\n");
242 fprintf(stream, "Options:\n");
244 // Output options description.
245 for( i = 0; i < num_opts; i++ ) {
246 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
247 if(options[i].default_value) {
248 fprintf(stream, " Default: %s\n", options[i].default_value);
250 fprintf(stream, "\n");
258 // TODO: Remove this function with the nix major release.
259 void remove_option(int opt_index, int *argc, char **argv) {
261 // remove the options.
264 for(i = opt_index; i < *argc; i++) {
268 } while(argv[i][0] != '-' && opt_index >= *argc);
271 static const char *verify_required_directory(const char *dir) {
273 fatal("Cannot cd to directory '%s'", dir);
275 DIR *d = opendir(dir);
277 fatal("Cannot examine the contents of directory '%s'", dir);
283 int main(int argc, char **argv)
285 char *hostname = "localhost";
286 int i, check_config = 0;
287 int config_loaded = 0;
289 size_t wanted_stacksize = 0, stacksize = 0;
292 // set the name for logging
293 program_name = "netdata";
295 // parse depercated options
296 // TODO: Remove this block with the next major release.
300 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
301 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
302 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
303 remove_option(i, &argc, argv);
305 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
307 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
308 remove_option(i, &argc, argv);
310 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
311 config_set("global", "host access prefix", argv[i+1]);
312 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
313 remove_option(i, &argc, argv);
315 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
316 config_set("global", "history", argv[i+1]);
317 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
318 remove_option(i, &argc, argv);
326 int num_opts = sizeof(options) / sizeof(struct option_def);
327 char optstring[(num_opts * 2) + 1];
330 for( i = 0; i < num_opts; i++ ) {
331 optstring[string_i] = options[i].val;
333 if(options[i].arg_name) {
334 optstring[string_i] = ':';
340 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
343 if(load_config(optarg, 1) != 1) {
344 error("Cannot load configuration file %s.", optarg);
348 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
359 config_set("global", "bind to", optarg);
366 strncpy(pidfile, optarg, FILENAME_MAX);
367 pidfile[FILENAME_MAX] = '\0';
370 config_set("global", "default port", optarg);
373 config_set("global", "host access prefix", optarg);
376 config_set("global", "update every", optarg);
379 config_set("global", "run as user", optarg);
382 // TODO: Outsource version to makefile which can compute version from git.
383 printf("netdata %s\n", VERSION);
387 char* stacksize_string = "stacksize=";
388 char* debug_flags_string = "debug_flags=";
389 if(strcmp(optarg, "unittest") == 0) {
390 rrd_update_every = 1;
391 if(run_all_mockup_tests()) exit(1);
392 if(unit_test_storage()) exit(1);
393 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
395 } else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
396 optarg += strlen(stacksize_string);
397 config_set("global", "pthread stack size", optarg);
398 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
399 optarg += strlen(debug_flags_string);
400 config_set("global", "debug flags", optarg);
401 debug_flags = strtoull(optarg, NULL, 0);
413 load_config(NULL, 0);
416 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
418 setenv("MALLOC_ARENA_MAX", pmax, 1);
420 #if defined(HAVE_C_MALLOPT)
421 int i = config_get_number("global", "glibc malloc arena max for netdata", 1);
423 mallopt(M_ARENA_MAX, 1);
426 char *config_dir = config_get("global", "config directory", CONFIG_DIR);
428 // prepare configuration environment variables for the plugins
429 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(config_dir) , 1);
430 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(config_get("global", "plugins directory" , PLUGINS_DIR)), 1);
431 setenv("NETDATA_WEB_DIR" , verify_required_directory(config_get("global", "web files directory", WEB_DIR)) , 1);
432 setenv("NETDATA_CACHE_DIR" , verify_required_directory(config_get("global", "cache directory" , CACHE_DIR)) , 1);
433 setenv("NETDATA_LIB_DIR" , verify_required_directory(config_get("global", "lib directory" , VARLIB_DIR)) , 1);
434 setenv("NETDATA_LOG_DIR" , verify_required_directory(config_get("global", "log directory" , LOG_DIR)) , 1);
436 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
437 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
439 // disable buffering for python plugins
440 setenv("PYTHONUNBUFFERED", "1", 1);
442 // avoid flood calls to stat(/etc/localtime)
443 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
444 setenv("TZ", ":/etc/localtime", 0);
446 // work while we are cd into config_dir
447 // to allow the plugins refer to their config
448 // files using relative filenames
449 if(chdir(config_dir) == -1)
450 fatal("Cannot cd to '%s'", config_dir);
452 char path[1024 + 1], *p = getenv("PATH");
453 if(!p) p = "/bin:/usr/bin";
454 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
455 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
460 char *flags = config_get("global", "debug flags", "0x00000000");
461 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
463 debug_flags = strtoull(flags, NULL, 0);
464 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
467 if(debug_flags != 0) {
468 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
469 if(setrlimit(RLIMIT_CORE, &rl) != 0)
470 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
472 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
474 #endif /* __FreeBSD__ */
476 // --------------------------------------------------------------------
478 #ifdef MADV_MERGEABLE
479 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
481 #warning "Kernel memory deduplication (KSM) is not available"
484 // --------------------------------------------------------------------
486 global_host_prefix = config_get("global", "host access prefix", "");
487 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
491 get_system_pid_max();
493 // --------------------------------------------------------------------
495 stdout_filename = config_get("global", "debug log", LOG_DIR "/debug.log");
496 stderr_filename = config_get("global", "error log", LOG_DIR "/error.log");
497 stdaccess_filename = config_get("global", "access log", LOG_DIR "/access.log");
499 error_log_throttle_period_backup =
500 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
501 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
503 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
504 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
507 stdout_filename = stderr_filename = stdaccess_filename = "system";
508 error_log_throttle_period = 0;
509 error_log_errors_per_period = 0;
511 error_log_limit_unlimited();
513 // --------------------------------------------------------------------
515 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
517 // --------------------------------------------------------------------
520 char hostnamebuf[HOSTNAME_MAX + 1];
521 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
522 error("WARNING: Cannot get machine hostname.");
523 hostname = config_get("global", "hostname", hostnamebuf);
524 debug(D_OPTIONS, "hostname set to '%s'", hostname);
525 setenv("NETDATA_HOSTNAME", hostname, 1);
528 // --------------------------------------------------------------------
530 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
531 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
532 error("Invalid history entries %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
533 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
536 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
539 // --------------------------------------------------------------------
541 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
542 if(rrd_update_every < 1 || rrd_update_every > 600) {
543 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
544 rrd_update_every = UPDATE_EVERY;
546 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
548 // let the plugins know the min update_every
551 snprintfz(buf, 15, "%d", rrd_update_every);
552 setenv("NETDATA_UPDATE_EVERY", buf, 1);
555 // --------------------------------------------------------------------
557 // block signals while initializing threads.
558 // this causes the threads to block signals.
561 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
562 error("Could not block signals for threads");
564 // Catch signals which we want to use
568 // ingore all signals while we run in a signal handler
569 sigfillset(&sa.sa_mask);
571 // INFO: If we add signals here we have to unblock them
572 // at popen.c when running a external plugin.
574 // Ignore SIGPIPE completely.
575 sa.sa_handler = SIG_IGN;
576 if(sigaction(SIGPIPE, &sa, NULL) == -1)
577 error("Failed to change signal handler for SIGPIPE");
579 sa.sa_handler = sig_handler_exit;
580 if(sigaction(SIGINT, &sa, NULL) == -1)
581 error("Failed to change signal handler for SIGINT");
583 sa.sa_handler = sig_handler_exit;
584 if(sigaction(SIGTERM, &sa, NULL) == -1)
585 error("Failed to change signal handler for SIGTERM");
587 sa.sa_handler = sig_handler_logrotate;
588 if(sigaction(SIGHUP, &sa, NULL) == -1)
589 error("Failed to change signal handler for SIGHUP");
591 // save database on SIGUSR1
592 sa.sa_handler = sig_handler_save;
593 if(sigaction(SIGUSR1, &sa, NULL) == -1)
594 error("Failed to change signal handler for SIGUSR1");
596 // reload health configuration on SIGUSR2
597 sa.sa_handler = sig_handler_reload_health;
598 if(sigaction(SIGUSR2, &sa, NULL) == -1)
599 error("Failed to change signal handler for SIGUSR2");
601 // --------------------------------------------------------------------
603 i = pthread_attr_init(&attr);
605 fatal("pthread_attr_init() failed with code %d.", i);
607 i = pthread_attr_getstacksize(&attr, &stacksize);
609 fatal("pthread_attr_getstacksize() failed with code %d.", i);
611 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
613 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
615 // --------------------------------------------------------------------
617 for (i = 0; static_threads[i].name != NULL ; i++) {
618 struct netdata_static_thread *st = &static_threads[i];
620 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
621 if(st->enabled && st->init_routine) st->init_routine();
624 // --------------------------------------------------------------------
626 // get the user we should run
627 // IMPORTANT: this is required before web_files_uid()
628 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
630 // IMPORTANT: these have to run once, while single threaded
631 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
634 // --------------------------------------------------------------------
637 create_listen_sockets();
640 // initialize the log files
641 open_all_log_files();
644 #ifdef NETDATA_INTERNAL_CHECKS
645 if(debug_flags != 0) {
646 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
647 if(setrlimit(RLIMIT_CORE, &rl) != 0)
648 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
649 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
651 #endif /* NETDATA_INTERNAL_CHECKS */
652 #endif /* __FreeBSD__ */
654 // fork, switch user, create pid file, set process priority
655 if(become_daemon(dont_fork, user) == -1)
656 fatal("Cannot daemonize myself.");
658 info("NetData started on pid %d", getpid());
661 // ------------------------------------------------------------------------
662 // get default pthread stack size
664 if(stacksize < wanted_stacksize) {
665 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
667 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
669 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
672 // ------------------------------------------------------------------------
673 // initialize rrd host
675 rrdhost_init(hostname);
677 // ------------------------------------------------------------------------
678 // initialize the registry
682 // ------------------------------------------------------------------------
683 // initialize health monitoring
690 // ------------------------------------------------------------------------
691 // enable log flood protection
693 error_log_limit_reset();
695 // ------------------------------------------------------------------------
698 web_server_threading_selection();
700 for (i = 0; static_threads[i].name != NULL ; i++) {
701 struct netdata_static_thread *st = &static_threads[i];
704 st->thread = mallocz(sizeof(pthread_t));
706 debug(D_SYSTEM, "Starting thread %s.", st->name);
708 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
709 error("failed to create new thread for %s.", st->name);
711 else if(pthread_detach(*st->thread))
712 error("Cannot request detach of newly created %s thread.", st->name);
714 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
717 // ------------------------------------------------------------------------
718 // block signals while initializing threads.
722 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
723 error("Could not unblock signals for threads");
726 // Handle flags set in the signal handler.
730 debug(D_EXIT, "Exit main loop of netdata.");
731 netdata_cleanup_and_exit(0);