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 #endif /* __FreeBSD__, __APPLE__*/
49 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
50 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
51 {"backends", NULL, NULL, 1, NULL, NULL, backends_main},
52 {"health", NULL, NULL, 1, NULL, NULL, health_main},
53 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
54 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
55 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
56 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
59 void web_server_threading_selection(void) {
60 int threaded = config_get_boolean("global", "multi threaded web server", 1);
63 for(i = 0; static_threads[i].name ; i++) {
64 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
65 static_threads[i].enabled = threaded?1:0;
67 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
68 static_threads[i].enabled = threaded?0:1;
71 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
73 web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
75 #ifdef NETDATA_WITH_ZLIB
76 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
78 char *s = config_get("global", "web compression strategy", "default");
79 if(!strcmp(s, "default"))
80 web_gzip_strategy = Z_DEFAULT_STRATEGY;
81 else if(!strcmp(s, "filtered"))
82 web_gzip_strategy = Z_FILTERED;
83 else if(!strcmp(s, "huffman only"))
84 web_gzip_strategy = Z_HUFFMAN_ONLY;
85 else if(!strcmp(s, "rle"))
86 web_gzip_strategy = Z_RLE;
87 else if(!strcmp(s, "fixed"))
88 web_gzip_strategy = Z_FIXED;
90 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
91 web_gzip_strategy = Z_DEFAULT_STRATEGY;
94 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
95 if(web_gzip_level < 1) {
96 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
99 else if(web_gzip_level > 9) {
100 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
103 #endif /* NETDATA_WITH_ZLIB */
107 int killpid(pid_t pid, int sig)
110 debug(D_EXIT, "Request to kill pid %d", pid);
113 if(kill(pid, 0) == -1) {
116 error("Request to kill pid %d, but it is not running.", pid);
120 error("Request to kill pid %d, but I do not have enough permissions.", pid);
124 error("Request to kill pid %d, but I received an error.", pid);
130 ret = kill(pid, sig);
134 error("Cannot kill pid %d, but it is not running.", pid);
138 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
142 error("Cannot kill pid %d, but I received an error.", pid);
153 error_log_limit_unlimited();
157 struct web_client *w;
158 for(w = web_clients; w ; w = w->next) {
159 info("Stopping web client %s", w->client_ip);
160 pthread_cancel(w->thread);
162 // pthread_join(w->thread, NULL);
166 for (i = 0; static_threads[i].name != NULL ; i++) {
167 if(static_threads[i].enabled && static_threads[i].thread) {
168 info("Stopping %s thread", static_threads[i].name);
169 pthread_cancel(*static_threads[i].thread);
171 // pthread_join(*static_threads[i].thread, NULL);
173 static_threads[i].thread = NULL;
178 info("Killing tc-qos-helper process %d", tc_child_pid);
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 if(cd->enabled && !cd->obsolete) {
187 if(cd->thread != (pthread_t)NULL) {
188 info("Stopping %s plugin thread", cd->id);
189 pthread_cancel(cd->thread);
191 // pthread_join(cd->thread, NULL);
192 cd->thread = (pthread_t)NULL;
196 info("killing %s plugin child process pid %d", cd->id, cd->pid);
197 if(killpid(cd->pid, SIGTERM) != -1)
198 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
207 // if, for any reason there is any child exited
209 info("Cleaning up an other children");
210 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
212 info("All threads/childs stopped.");
215 struct option_def options[] = {
216 // opt description arg name default value
217 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
218 {'D', "Disable fork into background", NULL, NULL},
219 {'h', "Display help message", NULL, NULL},
220 {'P', "File to save a pid while running", "FILE", NULL},
221 {'i', "The IP address to listen to.", "address", "All addresses"},
222 {'k', "Check daemon configuration.", NULL, NULL},
223 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
224 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
225 {'t', "The frequency in seconds, for data collection. \
226 Same as 'update every' config file option.", "seconds", "1"},
227 {'u', "System username to run as.", "username", "netdata"},
228 {'v', "Version of the program", NULL, NULL},
229 {'W', "vendor options.", "stacksize=N|unittest|debug_flags=N", NULL},
232 void help(int exitcode) {
239 int num_opts = sizeof(options) / sizeof(struct option_def);
243 // Compute maximum argument length
244 for( i = 0; i < num_opts; i++ ) {
245 if(options[i].arg_name) {
246 int len_arg = (int)strlen(options[i].arg_name);
247 if(len_arg > max_len_arg) max_len_arg = len_arg;
251 fprintf(stream, "SYNOPSIS: netdata [options]\n");
252 fprintf(stream, "\n");
253 fprintf(stream, "Options:\n");
255 // Output options description.
256 for( i = 0; i < num_opts; i++ ) {
257 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
258 if(options[i].default_value) {
259 fprintf(stream, " Default: %s\n", options[i].default_value);
261 fprintf(stream, "\n");
269 // TODO: Remove this function with the nix major release.
270 void remove_option(int opt_index, int *argc, char **argv) {
272 // remove the options.
275 for(i = opt_index; i < *argc; i++) {
279 } while(argv[i][0] != '-' && opt_index >= *argc);
282 static const char *verify_required_directory(const char *dir) {
284 fatal("Cannot cd to directory '%s'", dir);
286 DIR *d = opendir(dir);
288 fatal("Cannot examine the contents of directory '%s'", dir);
294 int main(int argc, char **argv)
296 char *hostname = "localhost";
297 int i, check_config = 0;
298 int config_loaded = 0;
300 size_t wanted_stacksize = 0, stacksize = 0;
303 // set the name for logging
304 program_name = "netdata";
306 // parse depercated options
307 // TODO: Remove this block with the next major release.
311 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
312 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
313 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
314 remove_option(i, &argc, argv);
316 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
318 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
319 remove_option(i, &argc, argv);
321 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
322 config_set("global", "host access prefix", argv[i+1]);
323 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
324 remove_option(i, &argc, argv);
326 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
327 config_set("global", "history", argv[i+1]);
328 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
329 remove_option(i, &argc, argv);
337 int num_opts = sizeof(options) / sizeof(struct option_def);
338 char optstring[(num_opts * 2) + 1];
341 for( i = 0; i < num_opts; i++ ) {
342 optstring[string_i] = options[i].val;
344 if(options[i].arg_name) {
345 optstring[string_i] = ':';
351 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
354 if(load_config(optarg, 1) != 1) {
355 error("Cannot load configuration file %s.", optarg);
359 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
370 config_set("global", "bind to", optarg);
377 strncpy(pidfile, optarg, FILENAME_MAX);
378 pidfile[FILENAME_MAX] = '\0';
381 config_set("global", "default port", optarg);
384 config_set("global", "host access prefix", optarg);
387 config_set("global", "update every", optarg);
390 config_set("global", "run as user", optarg);
393 // TODO: Outsource version to makefile which can compute version from git.
394 printf("netdata %s\n", VERSION);
398 char* stacksize_string = "stacksize=";
399 char* debug_flags_string = "debug_flags=";
400 if(strcmp(optarg, "unittest") == 0) {
401 rrd_update_every = 1;
402 if(run_all_mockup_tests()) exit(1);
403 if(unit_test_storage()) exit(1);
404 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
406 } else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
407 optarg += strlen(stacksize_string);
408 config_set("global", "pthread stack size", optarg);
409 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
410 optarg += strlen(debug_flags_string);
411 config_set("global", "debug flags", optarg);
412 debug_flags = strtoull(optarg, NULL, 0);
424 load_config(NULL, 0);
427 char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
429 setenv("MALLOC_ARENA_MAX", pmax, 1);
431 #if defined(HAVE_C_MALLOPT)
432 int i = config_get_number("global", "glibc malloc arena max for netdata", 1);
434 mallopt(M_ARENA_MAX, 1);
437 char *config_dir = config_get("global", "config directory", CONFIG_DIR);
439 // prepare configuration environment variables for the plugins
440 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(config_dir) , 1);
441 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(config_get("global", "plugins directory" , PLUGINS_DIR)), 1);
442 setenv("NETDATA_WEB_DIR" , verify_required_directory(config_get("global", "web files directory", WEB_DIR)) , 1);
443 setenv("NETDATA_CACHE_DIR" , verify_required_directory(config_get("global", "cache directory" , CACHE_DIR)) , 1);
444 setenv("NETDATA_LIB_DIR" , verify_required_directory(config_get("global", "lib directory" , VARLIB_DIR)) , 1);
445 setenv("NETDATA_LOG_DIR" , verify_required_directory(config_get("global", "log directory" , LOG_DIR)) , 1);
447 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
448 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
450 // disable buffering for python plugins
451 setenv("PYTHONUNBUFFERED", "1", 1);
453 // avoid flood calls to stat(/etc/localtime)
454 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
455 setenv("TZ", ":/etc/localtime", 0);
457 // work while we are cd into config_dir
458 // to allow the plugins refer to their config
459 // files using relative filenames
460 if(chdir(config_dir) == -1)
461 fatal("Cannot cd to '%s'", config_dir);
463 char path[1024 + 1], *p = getenv("PATH");
464 if(!p) p = "/bin:/usr/bin";
465 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
466 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
471 char *flags = config_get("global", "debug flags", "0x00000000");
472 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
474 debug_flags = strtoull(flags, NULL, 0);
475 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
477 if(debug_flags != 0) {
478 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
479 if(setrlimit(RLIMIT_CORE, &rl) != 0)
480 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
482 #if !(defined(__FreeBSD__) || defined(__APPLE__))
483 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
484 #endif /* __FreeBSD__ || __APPLE__*/
487 // --------------------------------------------------------------------
489 #ifdef MADV_MERGEABLE
490 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
492 #warning "Kernel memory deduplication (KSM) is not available"
495 // --------------------------------------------------------------------
497 global_host_prefix = config_get("global", "host access prefix", "");
498 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
502 get_system_pid_max();
504 // --------------------------------------------------------------------
506 stdout_filename = config_get("global", "debug log", LOG_DIR "/debug.log");
507 stderr_filename = config_get("global", "error log", LOG_DIR "/error.log");
508 stdaccess_filename = config_get("global", "access log", LOG_DIR "/access.log");
510 error_log_throttle_period_backup =
511 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
512 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
514 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
515 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
518 stdout_filename = stderr_filename = stdaccess_filename = "system";
519 error_log_throttle_period = 0;
520 error_log_errors_per_period = 0;
522 error_log_limit_unlimited();
524 // --------------------------------------------------------------------
526 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
528 // --------------------------------------------------------------------
531 char hostnamebuf[HOSTNAME_MAX + 1];
532 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
533 error("WARNING: Cannot get machine hostname.");
534 hostname = config_get("global", "hostname", hostnamebuf);
535 debug(D_OPTIONS, "hostname set to '%s'", hostname);
536 setenv("NETDATA_HOSTNAME", hostname, 1);
539 // --------------------------------------------------------------------
541 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
542 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
543 error("Invalid history entries %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
544 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
547 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
550 // --------------------------------------------------------------------
552 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
553 if(rrd_update_every < 1 || rrd_update_every > 600) {
554 error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
555 rrd_update_every = UPDATE_EVERY;
557 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
559 // let the plugins know the min update_every
562 snprintfz(buf, 15, "%d", rrd_update_every);
563 setenv("NETDATA_UPDATE_EVERY", buf, 1);
566 // --------------------------------------------------------------------
568 // block signals while initializing threads.
569 // this causes the threads to block signals.
572 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
573 error("Could not block signals for threads");
575 // Catch signals which we want to use
579 // ingore all signals while we run in a signal handler
580 sigfillset(&sa.sa_mask);
582 // INFO: If we add signals here we have to unblock them
583 // at popen.c when running a external plugin.
585 // Ignore SIGPIPE completely.
586 sa.sa_handler = SIG_IGN;
587 if(sigaction(SIGPIPE, &sa, NULL) == -1)
588 error("Failed to change signal handler for SIGPIPE");
590 sa.sa_handler = sig_handler_exit;
591 if(sigaction(SIGINT, &sa, NULL) == -1)
592 error("Failed to change signal handler for SIGINT");
594 sa.sa_handler = sig_handler_exit;
595 if(sigaction(SIGTERM, &sa, NULL) == -1)
596 error("Failed to change signal handler for SIGTERM");
598 sa.sa_handler = sig_handler_logrotate;
599 if(sigaction(SIGHUP, &sa, NULL) == -1)
600 error("Failed to change signal handler for SIGHUP");
602 // save database on SIGUSR1
603 sa.sa_handler = sig_handler_save;
604 if(sigaction(SIGUSR1, &sa, NULL) == -1)
605 error("Failed to change signal handler for SIGUSR1");
607 // reload health configuration on SIGUSR2
608 sa.sa_handler = sig_handler_reload_health;
609 if(sigaction(SIGUSR2, &sa, NULL) == -1)
610 error("Failed to change signal handler for SIGUSR2");
612 // --------------------------------------------------------------------
614 i = pthread_attr_init(&attr);
616 fatal("pthread_attr_init() failed with code %d.", i);
618 i = pthread_attr_getstacksize(&attr, &stacksize);
620 fatal("pthread_attr_getstacksize() failed with code %d.", i);
622 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
624 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
626 // --------------------------------------------------------------------
628 for (i = 0; static_threads[i].name != NULL ; i++) {
629 struct netdata_static_thread *st = &static_threads[i];
631 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
632 if(st->enabled && st->init_routine) st->init_routine();
635 // --------------------------------------------------------------------
637 // get the user we should run
638 // IMPORTANT: this is required before web_files_uid()
639 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
641 // IMPORTANT: these have to run once, while single threaded
642 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
645 // --------------------------------------------------------------------
648 create_listen_sockets();
651 // initialize the log files
652 open_all_log_files();
654 #ifdef NETDATA_INTERNAL_CHECKS
655 if(debug_flags != 0) {
656 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
657 if(setrlimit(RLIMIT_CORE, &rl) != 0)
658 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
659 #if !(defined(__FreeBSD__) || defined(__APPLE__))
660 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
661 #endif /* __FreeBSD__ || __APPLE__*/
663 #endif /* NETDATA_INTERNAL_CHECKS */
665 // fork, switch user, create pid file, set process priority
666 if(become_daemon(dont_fork, user) == -1)
667 fatal("Cannot daemonize myself.");
669 info("netdata started on pid %d.", getpid());
671 // ------------------------------------------------------------------------
672 // get default pthread stack size
674 if(stacksize < wanted_stacksize) {
675 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
677 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
679 debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
682 // ------------------------------------------------------------------------
683 // initialize rrd host
685 rrdhost_init(hostname);
687 // ------------------------------------------------------------------------
688 // initialize the registry
692 // ------------------------------------------------------------------------
693 // initialize health monitoring
700 // ------------------------------------------------------------------------
701 // enable log flood protection
703 error_log_limit_reset();
705 // ------------------------------------------------------------------------
708 web_server_threading_selection();
710 for (i = 0; static_threads[i].name != NULL ; i++) {
711 struct netdata_static_thread *st = &static_threads[i];
714 st->thread = mallocz(sizeof(pthread_t));
716 debug(D_SYSTEM, "Starting thread %s.", st->name);
718 if(pthread_create(st->thread, &attr, st->start_routine, st))
719 error("failed to create new thread for %s.", st->name);
721 else if(pthread_detach(*st->thread))
722 error("Cannot request detach of newly created %s thread.", st->name);
724 else debug(D_SYSTEM, "Not starting thread %s.", st->name);
727 info("netdata initialization completed. Enjoy real-time performance monitoring!");
729 // ------------------------------------------------------------------------
730 // block signals while initializing threads.
734 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
735 error("Could not unblock signals for threads");
738 // Handle flags set in the signal handler.
742 debug(D_EXIT, "Exit main loop of netdata.");
743 netdata_cleanup_and_exit(0);