3 extern void *cgroups_main(void *ptr);
5 void netdata_cleanup_and_exit(int ret) {
8 error_log_limit_unlimited();
10 info("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},
48 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
49 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
50 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
51 {"health", NULL, NULL, 1, NULL, NULL, health_main},
52 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
53 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
54 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
55 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
58 void web_server_threading_selection(void) {
59 int threaded = config_get_boolean("global", "multi threaded web server", 1);
62 for(i = 0; static_threads[i].name ; i++) {
63 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
64 static_threads[i].enabled = threaded?1:0;
66 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
67 static_threads[i].enabled = threaded?0:1;
70 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
72 web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
74 #ifdef NETDATA_WITH_ZLIB
75 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
77 char *s = config_get("global", "web compression strategy", "default");
78 if(!strcmp(s, "default"))
79 web_gzip_strategy = Z_DEFAULT_STRATEGY;
80 else if(!strcmp(s, "filtered"))
81 web_gzip_strategy = Z_FILTERED;
82 else if(!strcmp(s, "huffman only"))
83 web_gzip_strategy = Z_HUFFMAN_ONLY;
84 else if(!strcmp(s, "rle"))
85 web_gzip_strategy = Z_RLE;
86 else if(!strcmp(s, "fixed"))
87 web_gzip_strategy = Z_FIXED;
89 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
90 web_gzip_strategy = Z_DEFAULT_STRATEGY;
93 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
94 if(web_gzip_level < 1) {
95 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
98 else if(web_gzip_level > 9) {
99 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
102 #endif /* NETDATA_WITH_ZLIB */
106 int killpid(pid_t pid, int sig)
109 debug(D_EXIT, "Request to kill pid %d", pid);
112 if(kill(pid, 0) == -1) {
115 error("Request to kill pid %d, but it is not running.", pid);
119 error("Request to kill pid %d, but I do not have enough permissions.", pid);
123 error("Request to kill pid %d, but I received an error.", pid);
129 ret = kill(pid, sig);
133 error("Cannot kill pid %d, but it is not running.", pid);
137 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
141 error("Cannot kill pid %d, but I received an error.", pid);
154 struct web_client *w;
155 for(w = web_clients; w ; w = w->next) {
156 debug(D_EXIT, "Stopping web client %s", w->client_ip);
157 pthread_cancel(w->thread);
158 pthread_join(w->thread, NULL);
162 for (i = 0; static_threads[i].name != NULL ; i++) {
163 if(static_threads[i].thread) {
164 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
165 pthread_cancel(*static_threads[i].thread);
166 pthread_join(*static_threads[i].thread, NULL);
167 static_threads[i].thread = NULL;
172 info("Killing tc-qos-helper procees");
173 if(killpid(tc_child_pid, SIGTERM) != -1)
174 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
179 for(cd = pluginsd_root ; cd ; cd = cd->next) {
180 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
181 pthread_cancel(cd->thread);
182 pthread_join(cd->thread, NULL);
184 if(cd->pid && !cd->obsolete) {
185 debug(D_EXIT, "killing %s plugin process", cd->id);
186 if(killpid(cd->pid, SIGTERM) != -1)
187 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
191 // if, for any reason there is any child exited
193 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
195 debug(D_EXIT, "All threads/childs stopped.");
198 struct option_def options[] = {
199 // opt description arg name default value
200 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
201 {'D', "Disable fork into background", NULL, NULL},
202 {'h', "Display help message", NULL, NULL},
203 {'P', "File to save a pid while running", "FILE", NULL},
204 {'i', "The IP address to listen to.", "address", "All addresses"},
205 {'k', "Check daemon configuration.", NULL, NULL},
206 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
207 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
208 {'t', "The frequency in seconds, for data collection. \
209 Same as 'update every' config file option.", "seconds", "1"},
210 {'u', "System username to run as.", "username", "netdata"},
211 {'v', "Version of the program", NULL, NULL},
212 {'W', "vendor options.", "stacksize=N|unittest|debug_flags=N", NULL},
215 void help(int exitcode) {
222 int num_opts = sizeof(options) / sizeof(struct option_def);
226 // Compute maximum argument length
227 for( i = 0; i < num_opts; i++ ) {
228 if(options[i].arg_name) {
229 int len_arg = (int)strlen(options[i].arg_name);
230 if(len_arg > max_len_arg) max_len_arg = len_arg;
234 fprintf(stream, "SYNOPSIS: netdata [options]\n");
235 fprintf(stream, "\n");
236 fprintf(stream, "Options:\n");
238 // Output options description.
239 for( i = 0; i < num_opts; i++ ) {
240 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
241 if(options[i].default_value) {
242 fprintf(stream, " Default: %s\n", options[i].default_value);
244 fprintf(stream, "\n");
252 // TODO: Remove this function with the nix major release.
253 void remove_option(int opt_index, int *argc, char **argv) {
255 // remove the options.
258 for(i = opt_index; i < *argc; i++) {
262 } while(argv[i][0] != '-' && opt_index >= *argc);
265 static const char *verify_required_directory(const char *dir) {
267 fatal("Cannot cd to directory '%s'", dir);
269 DIR *d = opendir(dir);
271 fatal("Cannot examine the contents of directory '%s'", dir);
277 int main(int argc, char **argv)
279 char *hostname = "localhost";
280 int i, check_config = 0;
281 int config_loaded = 0;
283 size_t wanted_stacksize = 0, stacksize = 0;
286 // set the name for logging
287 program_name = "netdata";
289 // parse command line.
291 // parse depercated options
292 // TODO: Remove this block with the next major release.
296 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
297 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
298 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
299 remove_option(i, &argc, argv);
301 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
303 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
304 remove_option(i, &argc, argv);
306 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
307 config_set("global", "host access prefix", argv[i+1]);
308 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
309 remove_option(i, &argc, argv);
311 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
312 config_set("global", "history", argv[i+1]);
313 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
314 remove_option(i, &argc, argv);
322 int num_opts = sizeof(options) / sizeof(struct option_def);
323 char optstring[(num_opts * 2) + 1];
326 for( i = 0; i < num_opts; i++ ) {
327 optstring[string_i] = options[i].val;
329 if(options[i].arg_name) {
330 optstring[string_i] = ':';
336 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
339 if(load_config(optarg, 1) != 1) {
340 error("Cannot load configuration file %s.", optarg);
344 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
355 config_set("global", "bind to", optarg);
362 strncpy(pidfile, optarg, FILENAME_MAX);
363 pidfile[FILENAME_MAX] = '\0';
366 config_set("global", "default port", optarg);
369 config_set("global", "host access prefix", optarg);
372 config_set("global", "update every", optarg);
375 config_set("global", "run as user", optarg);
378 // TODO: Outsource version to makefile which can compute version from git.
379 printf("netdata 1.3.1_master\n");
383 char* stacksize_string = "stacksize=";
384 char* debug_flags_string = "debug_flags=";
385 if(strcmp(optarg, "unittest") == 0) {
386 rrd_update_every = 1;
387 if(run_all_mockup_tests()) exit(1);
388 if(unit_test_storage()) exit(1);
389 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
391 } else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
392 optarg += strlen(stacksize_string);
393 config_set("global", "pthread stack size", optarg);
394 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
395 optarg += strlen(debug_flags_string);
396 config_set("global", "debug flags", optarg);
397 debug_flags = strtoull(optarg, NULL, 0);
409 load_config(NULL, 0);
412 char *config_dir = config_get("global", "config directory", CONFIG_DIR);
414 // prepare configuration environment variables for the plugins
415 setenv("NETDATA_CONFIG_DIR" , verify_required_directory(config_dir) , 1);
416 setenv("NETDATA_PLUGINS_DIR", verify_required_directory(config_get("global", "plugins directory" , PLUGINS_DIR)), 1);
417 setenv("NETDATA_WEB_DIR" , verify_required_directory(config_get("global", "web files directory", WEB_DIR)) , 1);
418 setenv("NETDATA_CACHE_DIR" , verify_required_directory(config_get("global", "cache directory" , CACHE_DIR)) , 1);
419 setenv("NETDATA_LIB_DIR" , verify_required_directory(config_get("global", "lib directory" , VARLIB_DIR)) , 1);
420 setenv("NETDATA_LOG_DIR" , verify_required_directory(config_get("global", "log directory" , LOG_DIR)) , 1);
422 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
423 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
425 // disable buffering for python plugins
426 setenv("PYTHONUNBUFFERED", "1", 1);
428 // avoid flood calls to stat(/etc/localtime)
429 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
430 setenv("TZ", ":/etc/localtime", 0);
432 // work while we are cd into config_dir
433 // to allow the plugins refer to their config
434 // files using relative filenames
435 if(chdir(config_dir) == -1)
436 fatal("Cannot cd to '%s'", config_dir);
438 char path[1024 + 1], *p = getenv("PATH");
439 if(!p) p = "/bin:/usr/bin";
440 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
441 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
446 char *flags = config_get("global", "debug flags", "0x00000000");
447 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
449 debug_flags = strtoull(flags, NULL, 0);
450 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
452 if(debug_flags != 0) {
453 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
454 if(setrlimit(RLIMIT_CORE, &rl) != 0)
455 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
456 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
459 // --------------------------------------------------------------------
461 #ifdef MADV_MERGEABLE
462 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
464 #warning "Kernel memory deduplication (KSM) is not available"
467 // --------------------------------------------------------------------
469 global_host_prefix = config_get("global", "host access prefix", "");
470 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
474 get_system_pid_max();
476 // --------------------------------------------------------------------
478 stdout_filename = config_get("global", "debug log", LOG_DIR "/debug.log");
479 stderr_filename = config_get("global", "error log", LOG_DIR "/error.log");
480 stdaccess_filename = config_get("global", "access log", LOG_DIR "/access.log");
482 error_log_throttle_period_backup =
483 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
484 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
486 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
487 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
490 stdout_filename = stderr_filename = stdaccess_filename = "system";
491 error_log_throttle_period = 0;
492 error_log_errors_per_period = 0;
494 error_log_limit_unlimited();
496 // --------------------------------------------------------------------
498 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
500 // --------------------------------------------------------------------
503 char hostnamebuf[HOSTNAME_MAX + 1];
504 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
505 error("WARNING: Cannot get machine hostname.");
506 hostname = config_get("global", "hostname", hostnamebuf);
507 debug(D_OPTIONS, "hostname set to '%s'", hostname);
508 setenv("NETDATA_HOSTNAME", hostname, 1);
511 // --------------------------------------------------------------------
513 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
514 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
515 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
516 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
519 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
522 // --------------------------------------------------------------------
524 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
525 if(rrd_update_every < 1 || rrd_update_every > 600) {
526 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
527 rrd_update_every = UPDATE_EVERY;
529 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
531 // let the plugins know the min update_every
534 snprintfz(buf, 15, "%d", rrd_update_every);
535 setenv("NETDATA_UPDATE_EVERY", buf, 1);
538 // --------------------------------------------------------------------
540 // block signals while initializing threads.
541 // this causes the threads to block signals.
544 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
545 error("Could not block signals for threads");
547 // Catch signals which we want to use
551 // ingore all signals while we run in a signal handler
552 sigfillset(&sa.sa_mask);
554 // INFO: If we add signals here we have to unblock them
555 // at popen.c when running a external plugin.
557 // Ignore SIGPIPE completely.
558 sa.sa_handler = SIG_IGN;
559 if(sigaction(SIGPIPE, &sa, NULL) == -1)
560 error("Failed to change signal handler for SIGPIPE");
562 sa.sa_handler = sig_handler_exit;
563 if(sigaction(SIGINT, &sa, NULL) == -1)
564 error("Failed to change signal handler for SIGINT");
566 sa.sa_handler = sig_handler_exit;
567 if(sigaction(SIGTERM, &sa, NULL) == -1)
568 error("Failed to change signal handler for SIGTERM");
570 sa.sa_handler = sig_handler_logrotate;
571 if(sigaction(SIGHUP, &sa, NULL) == -1)
572 error("Failed to change signal handler for SIGHUP");
574 // save database on SIGUSR1
575 sa.sa_handler = sig_handler_save;
576 if(sigaction(SIGUSR1, &sa, NULL) == -1)
577 error("Failed to change signal handler for SIGUSR1");
579 // reload health configuration on SIGUSR2
580 sa.sa_handler = sig_handler_reload_health;
581 if(sigaction(SIGUSR2, &sa, NULL) == -1)
582 error("Failed to change signal handler for SIGUSR2");
584 // --------------------------------------------------------------------
586 i = pthread_attr_init(&attr);
588 fatal("pthread_attr_init() failed with code %d.", i);
590 i = pthread_attr_getstacksize(&attr, &stacksize);
592 fatal("pthread_attr_getstacksize() failed with code %d.", i);
594 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
596 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
598 // --------------------------------------------------------------------
600 for (i = 0; static_threads[i].name != NULL ; i++) {
601 struct netdata_static_thread *st = &static_threads[i];
603 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
604 if(st->enabled && st->init_routine) st->init_routine();
607 // --------------------------------------------------------------------
609 // get the user we should run
610 // IMPORTANT: this is required before web_files_uid()
611 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
613 // IMPORTANT: these have to run once, while single threaded
614 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
617 // --------------------------------------------------------------------
620 create_listen_sockets();
623 // initialize the log files
624 open_all_log_files();
626 #ifdef NETDATA_INTERNAL_CHECKS
627 if(debug_flags != 0) {
628 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
629 if(setrlimit(RLIMIT_CORE, &rl) != 0)
630 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
631 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
633 #endif /* NETDATA_INTERNAL_CHECKS */
635 // fork, switch user, create pid file, set process priority
636 if(become_daemon(dont_fork, user) == -1)
637 fatal("Cannot demonize myself.");
639 info("NetData started on pid %d", getpid());
642 // ------------------------------------------------------------------------
643 // get default pthread stack size
645 if(stacksize < wanted_stacksize) {
646 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
648 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
650 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
653 // ------------------------------------------------------------------------
654 // initialize rrd host
656 rrdhost_init(hostname);
658 // ------------------------------------------------------------------------
659 // initialize the registry
663 // ------------------------------------------------------------------------
664 // initialize health monitoring
671 // ------------------------------------------------------------------------
672 // enable log flood protection
674 error_log_limit_reset();
676 // ------------------------------------------------------------------------
679 web_server_threading_selection();
681 for (i = 0; static_threads[i].name != NULL ; i++) {
682 struct netdata_static_thread *st = &static_threads[i];
685 st->thread = mallocz(sizeof(pthread_t));
687 info("Starting thread %s.", st->name);
689 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
690 error("failed to create new thread for %s.", st->name);
692 else if(pthread_detach(*st->thread))
693 error("Cannot request detach of newly created %s thread.", st->name);
695 else info("Not starting thread %s.", st->name);
698 // ------------------------------------------------------------------------
699 // block signals while initializing threads.
703 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
704 error("Could not unblock signals for threads");
707 // Handle flags set in the signal handler.
711 info("Exit main loop of netdata.");
712 netdata_cleanup_and_exit(0);