12 #include <sys/prctl.h>
17 #include "appconfig.h"
24 #include "web_client.h"
25 #include "web_server.h"
27 #include "unit_test.h"
29 #include "plugin_checks.h"
30 #include "plugin_idlejitter.h"
31 #include "plugin_nfacct.h"
33 #include "plugin_proc.h"
34 #include "plugin_tc.h"
35 #include "plugins_d.h"
39 extern void *cgroups_main(void *ptr);
41 volatile sig_atomic_t netdata_exit = 0;
43 void netdata_cleanup_and_exit(int ret) {
46 error_log_limit_unlimited();
48 info("Called: netdata_cleanup_and_exit()");
53 if(unlink(pidfile) != 0)
54 error("Cannot unlink pidfile '%s'.", pidfile);
57 info("NetData exiting. Bye bye...");
61 struct netdata_static_thread {
71 void (*init_routine) (void);
72 void *(*start_routine) (void *);
73 } static_threads[] = {
74 #ifdef INTERNAL_PLUGIN_NFACCT
75 // nfacct requires root access
76 // so, we build it as an external plugin with setuid to root
77 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
80 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
81 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
82 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
83 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
84 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
85 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
86 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
87 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
88 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
91 void web_server_threading_selection(void) {
92 int threaded = config_get_boolean("global", "multi threaded web server", 1);
95 for(i = 0; static_threads[i].name ; i++) {
96 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
97 static_threads[i].enabled = threaded?1:0;
99 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
100 static_threads[i].enabled = threaded?0:1;
103 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
105 web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
107 #ifdef NETDATA_WITH_ZLIB
108 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
110 char *s = config_get("global", "web compression strategy", "default");
111 if(!strcmp(s, "default"))
112 web_gzip_strategy = Z_DEFAULT_STRATEGY;
113 else if(!strcmp(s, "filtered"))
114 web_gzip_strategy = Z_FILTERED;
115 else if(!strcmp(s, "huffman only"))
116 web_gzip_strategy = Z_HUFFMAN_ONLY;
117 else if(!strcmp(s, "rle"))
118 web_gzip_strategy = Z_RLE;
119 else if(!strcmp(s, "fixed"))
120 web_gzip_strategy = Z_FIXED;
122 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
123 web_gzip_strategy = Z_DEFAULT_STRATEGY;
126 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
127 if(web_gzip_level < 1) {
128 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
131 else if(web_gzip_level > 9) {
132 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
135 #endif /* NETDATA_WITH_ZLIB */
139 int killpid(pid_t pid, int sig)
142 debug(D_EXIT, "Request to kill pid %d", pid);
145 if(kill(pid, 0) == -1) {
148 error("Request to kill pid %d, but it is not running.", pid);
152 error("Request to kill pid %d, but I do not have enough permissions.", pid);
156 error("Request to kill pid %d, but I received an error.", pid);
162 ret = kill(pid, sig);
166 error("Cannot kill pid %d, but it is not running.", pid);
170 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
174 error("Cannot kill pid %d, but I received an error.", pid);
187 struct web_client *w;
188 for(w = web_clients; w ; w = w->next) {
189 debug(D_EXIT, "Stopping web client %s", w->client_ip);
190 pthread_cancel(w->thread);
191 pthread_join(w->thread, NULL);
195 for (i = 0; static_threads[i].name != NULL ; i++) {
196 if(static_threads[i].thread) {
197 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
198 pthread_cancel(*static_threads[i].thread);
199 pthread_join(*static_threads[i].thread, NULL);
200 static_threads[i].thread = NULL;
205 info("Killing tc-qos-helper procees");
206 if(killpid(tc_child_pid, SIGTERM) != -1)
207 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
212 for(cd = pluginsd_root ; cd ; cd = cd->next) {
213 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
214 pthread_cancel(cd->thread);
215 pthread_join(cd->thread, NULL);
217 if(cd->pid && !cd->obsolete) {
218 debug(D_EXIT, "killing %s plugin process", cd->id);
219 if(killpid(cd->pid, SIGTERM) != -1)
220 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
224 // if, for any reason there is any child exited
226 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
228 debug(D_EXIT, "All threads/childs stopped.");
231 struct option_def options[] = {
232 // opt description arg name default value
233 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
234 {'D', "Disable fork into background", NULL, NULL},
235 {'h', "Display help message", NULL, NULL},
236 {'P', "File to save a pid while running", "FILE", NULL},
237 {'i', "The IP address to listen to.", "address", "All addresses"},
238 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
239 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
240 {'t', "The frequency in seconds, for data collection. \
241 Same as 'update every' config file option.", "seconds", "1"},
242 {'u', "System username to run as.", "username", "netdata"},
243 {'v', "Version of the program", NULL, NULL},
244 {'W', "vendor options.", "stacksize=<size>|unittest|debug_flag", NULL},
247 void help(int exitcode) {
254 int num_opts = sizeof(options) / sizeof(struct option_def);
258 // Compute maximum argument length
259 for( i = 0; i < num_opts; i++ ) {
260 if(options[i].arg_name) {
261 int len_arg = strlen(options[i].arg_name);
262 if(len_arg > max_len_arg) max_len_arg = len_arg;
266 fprintf(stream, "SYNOPSIS: netdata [options]\n");
267 fprintf(stream, "\n");
268 fprintf(stream, "Options:\n");
270 // Output options description.
271 for( i = 0; i < num_opts; i++ ) {
272 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
273 if(options[i].default_value) {
274 fprintf(stream, " Default: %s\n", options[i].default_value);
276 fprintf(stream, "\n");
284 // TODO: Remove this function with the nix major release.
285 void remove_option(int opt_index, int *argc, char **argv) {
287 // remove the options.
290 for(i = opt_index; i < *argc; i++) {
294 } while(argv[i][0] != '-' && opt_index >= *argc);
298 int main(int argc, char **argv)
301 int config_loaded = 0;
303 size_t wanted_stacksize = 0, stacksize = 0;
306 // global initialization
309 // set the name for logging
310 program_name = "netdata";
312 // parse command line.
314 // parse depercated options
315 // TODO: Remove this block with the next major release.
319 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
320 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
321 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
322 remove_option(i, &argc, argv);
324 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
326 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
327 remove_option(i, &argc, argv);
329 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
330 config_set("global", "host access prefix", argv[i+1]);
331 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
332 remove_option(i, &argc, argv);
334 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
335 config_set("global", "history", argv[i+1]);
336 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
337 remove_option(i, &argc, argv);
345 int num_opts = sizeof(options) / sizeof(struct option_def);
346 char optstring[(num_opts * 2) + 1];
349 for( i = 0; i < num_opts; i++ ) {
350 optstring[string_i] = options[i].val;
352 if(options[i].arg_name) {
353 optstring[string_i] = ':';
359 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
362 if(load_config(optarg, 1) != 1) {
363 error("Cannot load configuration file %s.", optarg);
367 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
378 config_set("global", "bind to", optarg);
381 strncpy(pidfile, optarg, FILENAME_MAX);
382 pidfile[FILENAME_MAX] = '\0';
385 config_set("global", "default port", optarg);
388 config_set("global", "host access prefix", optarg);
391 config_set("global", "update every", optarg);
394 config_set("global", "run as user", optarg);
397 // TODO: Outsource version to makefile which can compute version from git.
398 printf("netdata 1.2.1_master\n");
403 char* stacksize = "stacksize=";
404 char* debug_flags_string = "debug_flags=";
405 if(strcmp(optarg, "unittest") == 0) {
406 rrd_update_every = 1;
407 if(run_all_mockup_tests()) exit(1);
408 if(unit_test_storage()) exit(1);
409 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
411 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
412 optarg += strlen(stacksize);
413 config_set("global", "pthread stack size", optarg);
414 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
415 optarg += strlen(debug_flags_string);
416 config_set("global", "debug flags", optarg);
417 debug_flags = strtoull(optarg, NULL, 0);
428 if(!config_loaded) load_config(NULL, 0);
430 // prepare configuration environment variables for the plugins
431 setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1);
432 setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1);
433 setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1);
434 setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1);
435 setenv("NETDATA_LIB_DIR" , config_get("global", "lib directory" , VARLIB_DIR) , 1);
436 setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1);
437 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
438 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
440 // disable buffering for python plugins
441 setenv("PYTHONUNBUFFERED", "1", 1);
443 // avoid flood calls to stat(/etc/localtime)
444 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
445 setenv("TZ", ":/etc/localtime", 0);
448 char path[1024 + 1], *p = getenv("PATH");
449 if(!p) p = "/bin:/usr/bin";
450 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
451 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
454 // cd to /tmp to avoid any plugins writing files at random places
455 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
457 char *input_log_file = NULL;
458 char *output_log_file = NULL;
459 char *error_log_file = NULL;
460 char *access_log_file = NULL;
463 char *flags = config_get("global", "debug flags", "0x00000000");
464 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
466 debug_flags = strtoull(flags, NULL, 0);
467 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
469 if(debug_flags != 0) {
470 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
471 if(setrlimit(RLIMIT_CORE, &rl) != 0)
472 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
473 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
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 // --------------------------------------------------------------------
487 global_host_prefix = config_get("global", "host access prefix", "");
488 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
490 // --------------------------------------------------------------------
492 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
493 if(strcmp(output_log_file, "syslog") == 0) {
494 output_log_syslog = 1;
495 output_log_file = NULL;
497 else if(strcmp(output_log_file, "none") == 0) {
498 output_log_syslog = 0;
499 output_log_file = NULL;
501 else output_log_syslog = 0;
503 // --------------------------------------------------------------------
505 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
506 if(strcmp(error_log_file, "syslog") == 0) {
507 error_log_syslog = 1;
508 error_log_file = NULL;
510 else if(strcmp(error_log_file, "none") == 0) {
511 error_log_syslog = 0;
512 error_log_file = NULL;
513 // optimization - do not even generate debug log entries
515 else error_log_syslog = 0;
517 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
518 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
520 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
521 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
523 // --------------------------------------------------------------------
525 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
526 if(strcmp(access_log_file, "syslog") == 0) {
527 access_log_syslog = 1;
528 access_log_file = NULL;
530 else if(strcmp(access_log_file, "none") == 0) {
531 access_log_syslog = 0;
532 access_log_file = NULL;
534 else access_log_syslog = 0;
536 // --------------------------------------------------------------------
538 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
540 // --------------------------------------------------------------------
543 char hostnamebuf[HOSTNAME_MAX + 1];
544 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
545 error("WARNING: Cannot get machine hostname.");
546 hostname = config_get("global", "hostname", hostnamebuf);
547 debug(D_OPTIONS, "hostname set to '%s'", hostname);
550 // --------------------------------------------------------------------
552 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
553 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
554 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
555 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
558 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
561 // --------------------------------------------------------------------
563 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
564 if(rrd_update_every < 1 || rrd_update_every > 600) {
565 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
566 rrd_update_every = UPDATE_EVERY;
568 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
570 // let the plugins know the min update_every
573 snprintfz(buf, 15, "%d", rrd_update_every);
574 setenv("NETDATA_UPDATE_EVERY", buf, 1);
577 // --------------------------------------------------------------------
579 // block signals while initializing threads.
580 // this causes the threads to block signals.
584 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
585 error("Could not block signals for threads");
588 // Catch signals which we want to use to quit savely
590 sigemptyset(&sa.sa_mask);
591 sigaddset(&sa.sa_mask, SIGHUP);
592 sigaddset(&sa.sa_mask, SIGINT);
593 sigaddset(&sa.sa_mask, SIGTERM);
594 sa.sa_handler = sig_handler_exit;
596 if(sigaction(SIGHUP, &sa, NULL) == -1) {
597 error("Failed to change signal handler for SIGHUP");
599 if(sigaction(SIGINT, &sa, NULL) == -1) {
600 error("Failed to change signal handler for SIGINT");
602 if(sigaction(SIGTERM, &sa, NULL) == -1) {
603 error("Failed to change signal handler for SIGTERM");
606 // save database on SIGUSR1
607 sa.sa_handler = sig_handler_save;
608 if(sigaction(SIGUSR1, &sa, NULL) == -1) {
609 error("Failed to change signal handler for SIGUSR1");
612 // Ignore SIGPIPE completely.
613 // INFO: If we add signals here we have to unblock them
614 // at popen.c when running a external plugin.
615 sa.sa_handler = SIG_IGN;
616 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
617 error("Failed to change signal handler for SIGPIPE");
620 // --------------------------------------------------------------------
622 i = pthread_attr_init(&attr);
624 fatal("pthread_attr_init() failed with code %d.", i);
626 i = pthread_attr_getstacksize(&attr, &stacksize);
628 fatal("pthread_attr_getstacksize() failed with code %d.", i);
630 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
632 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
634 // --------------------------------------------------------------------
636 for (i = 0; static_threads[i].name != NULL ; i++) {
637 struct netdata_static_thread *st = &static_threads[i];
639 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
640 if(st->enabled && st->init_routine) st->init_routine();
643 // --------------------------------------------------------------------
645 // get the user we should run
646 // IMPORTANT: this is required before web_files_uid()
647 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
649 // IMPORTANT: these have to run once, while single threaded
650 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
653 // --------------------------------------------------------------------
655 create_listen_sockets();
658 // never become a problem
659 if(nice(20) == -1) error("Cannot lower my CPU priority.");
661 if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
662 fatal("Cannot demonize myself.");
664 #ifdef NETDATA_INTERNAL_CHECKS
665 if(debug_flags != 0) {
666 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
667 if(setrlimit(RLIMIT_CORE, &rl) != 0)
668 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
669 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
671 #endif /* NETDATA_INTERNAL_CHECKS */
673 if(output_log_syslog || error_log_syslog || access_log_syslog)
674 openlog("netdata", LOG_PID, LOG_DAEMON);
676 info("NetData started on pid %d", getpid());
679 // ------------------------------------------------------------------------
680 // get default pthread stack size
682 if(stacksize < wanted_stacksize) {
683 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
685 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
687 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
690 // --------------------------------------------------------------------
691 // initialize the registry
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 = malloc(sizeof(pthread_t));
706 fatal("Cannot allocate pthread_t memory");
708 info("Starting thread %s.", st->name);
710 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
711 error("failed to create new thread for %s.", st->name);
713 else if(pthread_detach(*st->thread))
714 error("Cannot request detach of newly created %s thread.", st->name);
716 else info("Not starting thread %s.", st->name);
719 // ------------------------------------------------------------------------
720 // block signals while initializing threads.
724 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
725 error("Could not unblock signals for threads");
728 // Handle flags set in the signal handler.
732 info("Exit main loop of netdata.");
733 netdata_cleanup_and_exit(0);