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'.");
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).");
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).");
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 socket to IP", optarg);
381 strncpy(pidfile, optarg, FILENAME_MAX);
382 pidfile[FILENAME_MAX] = '\0';
385 config_set("global", "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.1.0\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 // avoid extended to stat(/etc/localtime)
441 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
442 setenv("TZ", ":/etc/localtime", 0);
444 // cd to /tmp to avoid any plugins writing files at random places
445 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
447 char *input_log_file = NULL;
448 char *output_log_file = NULL;
449 char *error_log_file = NULL;
450 char *access_log_file = NULL;
455 // --------------------------------------------------------------------
457 sprintf(buffer, "0x%08llx", 0ULL);
458 char *flags = config_get("global", "debug flags", buffer);
459 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
461 debug_flags = strtoull(flags, NULL, 0);
462 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
464 if(debug_flags != 0) {
465 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
466 if(setrlimit(RLIMIT_CORE, &rl) != 0)
467 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
468 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
471 // --------------------------------------------------------------------
473 #ifdef MADV_MERGEABLE
474 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
476 #warning "Kernel memory deduplication (KSM) is not available"
479 // --------------------------------------------------------------------
482 global_host_prefix = config_get("global", "host access prefix", "");
483 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
485 // --------------------------------------------------------------------
487 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
488 if(strcmp(output_log_file, "syslog") == 0) {
489 output_log_syslog = 1;
490 output_log_file = NULL;
492 else if(strcmp(output_log_file, "none") == 0) {
493 output_log_syslog = 0;
494 output_log_file = NULL;
496 else output_log_syslog = 0;
498 // --------------------------------------------------------------------
500 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
501 if(strcmp(error_log_file, "syslog") == 0) {
502 error_log_syslog = 1;
503 error_log_file = NULL;
505 else if(strcmp(error_log_file, "none") == 0) {
506 error_log_syslog = 0;
507 error_log_file = NULL;
508 // optimization - do not even generate debug log entries
510 else error_log_syslog = 0;
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);
518 // --------------------------------------------------------------------
520 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
521 if(strcmp(access_log_file, "syslog") == 0) {
522 access_log_syslog = 1;
523 access_log_file = NULL;
525 else if(strcmp(access_log_file, "none") == 0) {
526 access_log_syslog = 0;
527 access_log_file = NULL;
529 else access_log_syslog = 0;
531 // --------------------------------------------------------------------
533 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
535 // --------------------------------------------------------------------
537 if(gethostname(buffer, HOSTNAME_MAX) == -1)
538 error("WARNING: Cannot get machine hostname.");
539 hostname = config_get("global", "hostname", buffer);
540 debug(D_OPTIONS, "hostname set to '%s'", hostname);
542 // --------------------------------------------------------------------
544 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
545 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
546 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
547 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
550 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
553 // --------------------------------------------------------------------
555 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
556 if(rrd_update_every < 1 || rrd_update_every > 600) {
557 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
558 rrd_update_every = UPDATE_EVERY;
560 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
562 // let the plugins know the min update_every
565 snprintfz(buf, 50, "%d", rrd_update_every);
566 setenv("NETDATA_UPDATE_EVERY", buf, 1);
569 // --------------------------------------------------------------------
571 // block signals while initializing threads.
572 // this causes the threads to block signals.
576 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
577 error("Could not block signals for threads");
580 // Catch signals which we want to use to quit savely
582 sigemptyset(&sa.sa_mask);
583 sigaddset(&sa.sa_mask, SIGHUP);
584 sigaddset(&sa.sa_mask, SIGINT);
585 sigaddset(&sa.sa_mask, SIGTERM);
586 sa.sa_handler = sig_handler;
588 if(sigaction(SIGHUP, &sa, NULL) == -1) {
589 error("Failed to change signal handler for SIGHUP");
591 if(sigaction(SIGINT, &sa, NULL) == -1) {
592 error("Failed to change signal handler for SIGINT");
594 if(sigaction(SIGTERM, &sa, NULL) == -1) {
595 error("Failed to change signal handler for SIGTERM");
597 // Ignore SIGPIPE completely.
598 // INFO: If we add signals here we have to unblock them
599 // at popen.c when running a external plugin.
600 sa.sa_handler = SIG_IGN;
601 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
602 error("Failed to change signal handler for SIGTERM");
605 // --------------------------------------------------------------------
607 i = pthread_attr_init(&attr);
609 fatal("pthread_attr_init() failed with code %d.", i);
611 i = pthread_attr_getstacksize(&attr, &stacksize);
613 fatal("pthread_attr_getstacksize() failed with code %d.", i);
615 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
617 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
619 // --------------------------------------------------------------------
621 for (i = 0; static_threads[i].name != NULL ; i++) {
622 struct netdata_static_thread *st = &static_threads[i];
624 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
625 if(st->enabled && st->init_routine) st->init_routine();
628 // --------------------------------------------------------------------
630 // get the user we should run
631 // IMPORTANT: this is required before web_files_uid()
632 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
634 // IMPORTANT: these have to run once, while single threaded
635 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
638 // --------------------------------------------------------------------
640 listen_fd = create_listen_socket();
641 if(listen_fd < 0) fatal("Cannot listen socket.");
644 // never become a problem
645 if(nice(20) == -1) error("Cannot lower my CPU priority.");
647 if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
648 fatal("Cannot demonize myself.");
650 #ifdef NETDATA_INTERNAL_CHECKS
651 if(debug_flags != 0) {
652 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
653 if(setrlimit(RLIMIT_CORE, &rl) != 0)
654 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
655 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
657 #endif /* NETDATA_INTERNAL_CHECKS */
659 if(output_log_syslog || error_log_syslog || access_log_syslog)
660 openlog("netdata", LOG_PID, LOG_DAEMON);
662 info("NetData started on pid %d", getpid());
665 // ------------------------------------------------------------------------
666 // get default pthread stack size
668 if(stacksize < wanted_stacksize) {
669 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
671 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
673 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
676 // --------------------------------------------------------------------
677 // initialize the registry
681 // ------------------------------------------------------------------------
684 web_server_threading_selection();
686 for (i = 0; static_threads[i].name != NULL ; i++) {
687 struct netdata_static_thread *st = &static_threads[i];
690 st->thread = malloc(sizeof(pthread_t));
692 fatal("Cannot allocate pthread_t memory");
694 info("Starting thread %s.", st->name);
696 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
697 error("failed to create new thread for %s.", st->name);
699 else if(pthread_detach(*st->thread))
700 error("Cannot request detach of newly created %s thread.", st->name);
702 else info("Not starting thread %s.", st->name);
705 // ------------------------------------------------------------------------
706 // block signals while initializing threads.
710 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
711 error("Could not unblock signals for threads");
714 // Handle flags set in the signal handler.
718 info("Exit main loop of netdata.");
719 netdata_cleanup_and_exit(0);