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)
49 // let it log a few more error messages
50 error_log_limit_reset();
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 *);
75 struct netdata_static_thread static_threads[] = {
76 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
77 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
78 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
79 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
81 #ifdef INTERNAL_PLUGIN_NFACCT
82 // nfacct requires root access
83 // so, we build it as an external plugin with setuid to root
84 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
87 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
88 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
89 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main},
90 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
93 int killpid(pid_t pid, int sig)
96 debug(D_EXIT, "Request to kill pid %d", pid);
99 if(kill(pid, 0) == -1) {
102 error("Request to kill pid %d, but it is not running.", pid);
106 error("Request to kill pid %d, but I do not have enough permissions.", pid);
110 error("Request to kill pid %d, but I received an error.", pid);
116 ret = kill(pid, sig);
120 error("Cannot kill pid %d, but it is not running.", pid);
124 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
128 error("Cannot kill pid %d, but I received an error.", pid);
141 struct web_client *w;
142 for(w = web_clients; w ; w = w->next) {
143 debug(D_EXIT, "Stopping web client %s", w->client_ip);
144 pthread_cancel(w->thread);
145 pthread_join(w->thread, NULL);
149 for (i = 0; static_threads[i].name != NULL ; i++) {
150 if(static_threads[i].thread) {
151 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
152 pthread_cancel(*static_threads[i].thread);
153 pthread_join(*static_threads[i].thread, NULL);
154 static_threads[i].thread = NULL;
159 info("Killing tc-qos-helper procees");
160 if(killpid(tc_child_pid, SIGTERM) != -1)
161 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
166 for(cd = pluginsd_root ; cd ; cd = cd->next) {
167 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
168 pthread_cancel(cd->thread);
169 pthread_join(cd->thread, NULL);
171 if(cd->pid && !cd->obsolete) {
172 debug(D_EXIT, "killing %s plugin process", cd->id);
173 if(killpid(cd->pid, SIGTERM) != -1)
174 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
178 // if, for any reason there is any child exited
180 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
182 debug(D_EXIT, "All threads/childs stopped.");
185 struct option_def options[] = {
186 // opt description arg name default value
187 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
188 {'D', "Disable fork into background", NULL, NULL},
189 {'h', "Display help message", NULL, NULL},
190 {'P', "File to save a pid while running", "FILE", NULL},
191 {'i', "The IP address to listen to.", "address", "All addresses"},
192 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
193 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
194 {'t', "The frequency in seconds, for data collection. \
195 Same as 'update every' config file option.", "seconds", "1"},
196 {'u', "System username to run as.", "username", "netdata"},
197 {'v', "Version of the program", NULL, NULL},
198 {'W', "vendor options.", "stacksize=<size>|unittest|debug_flag", NULL},
201 void help(int exitcode) {
208 int num_opts = sizeof(options) / sizeof(struct option_def);
212 // Compute maximum argument length
213 for( i = 0; i < num_opts; i++ ) {
214 if(options[i].arg_name) {
215 int len_arg = strlen(options[i].arg_name);
216 if(len_arg > max_len_arg) max_len_arg = len_arg;
220 fprintf(stream, "SYNOPSIS: netdata [options]\n");
221 fprintf(stream, "\n");
222 fprintf(stream, "Options:\n");
224 // Output options description.
225 for( i = 0; i < num_opts; i++ ) {
226 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
227 if(options[i].default_value) {
228 fprintf(stream, " Default: %s\n", options[i].default_value);
230 fprintf(stream, "\n");
238 // TODO: Remove this function with the nix major release.
239 void remove_option(int opt_index, int *argc, char **argv) {
241 // remove the options.
244 for(i = opt_index; i < *argc; i++) {
248 } while(argv[i][0] != '-' && opt_index >= *argc);
252 int main(int argc, char **argv)
255 int config_loaded = 0;
257 size_t wanted_stacksize = 0, stacksize = 0;
260 // global initialization
263 // set the name for logging
264 program_name = "netdata";
266 // parse command line.
268 // parse depercated options
269 // TODO: Remove this block with the next major release.
273 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
274 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
275 fprintf(stderr, "%s: deprecate option -- %s -- please use -P instead.\n", argv[0], argv[i]);
276 remove_option(i, &argc, argv);
278 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
280 fprintf(stderr, "%s: deprecate option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
281 remove_option(i, &argc, argv);
283 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
284 config_set("global", "host access prefix", argv[i+1]);
285 fprintf(stderr, "%s: deprecate option -- %s -- please use -s instead.\n", argv[0], argv[i]);
286 remove_option(i, &argc, argv);
288 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
289 config_set("global", "history", argv[i+1]);
290 fprintf(stderr, "%s: deprecate option -- %s -- This option will be rmoved with V2.*.\n", argv[0], argv[i]);
291 remove_option(i, &argc, argv);
299 int num_opts = sizeof(options) / sizeof(struct option_def);
300 char optstring[(num_opts * 2) + 1];
303 for( i = 0; i < num_opts; i++ ) {
304 optstring[string_i] = options[i].val;
306 if(options[i].arg_name) {
307 optstring[string_i] = ':';
313 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
316 if(load_config(optarg, 1) != 1) {
317 error("Cannot load configuration file %s.", optarg);
321 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
332 config_set("global", "bind socket to IP", optarg);
335 strncpy(pidfile, optarg, FILENAME_MAX);
336 pidfile[FILENAME_MAX] = '\0';
339 config_set("global", "port", optarg);
342 config_set("global", "host access prefix", optarg);
345 config_set("global", "update every", optarg);
348 config_set("global", "run as user", optarg);
351 // TODO: Outsource version to makefile which can compute version from git.
352 printf("netdata 1.1.0\n");
357 char* stacksize = "stacksize=";
358 char* debug_flags_string = "debug_flags=";
359 if(strcmp(optarg, "unittest") == 0) {
360 rrd_update_every = 1;
361 if(run_all_mockup_tests()) exit(1);
362 if(unit_test_storage()) exit(1);
363 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
365 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
366 optarg += strlen(stacksize);
367 config_set("global", "pthread stack size", optarg);
368 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
369 optarg += strlen(debug_flags_string);
370 config_set("global", "debug flags", optarg);
371 debug_flags = strtoull(optarg, NULL, 0);
382 if(!config_loaded) load_config(NULL, 0);
384 // prepare configuration environment variables for the plugins
385 setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1);
386 setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1);
387 setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1);
388 setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1);
389 setenv("NETDATA_LIB_DIR" , config_get("global", "lib directory" , VARLIB_DIR) , 1);
390 setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1);
391 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
392 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
394 // avoid extended to stat(/etc/localtime)
395 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
396 setenv("TZ", ":/etc/localtime", 0);
398 // cd to /tmp to avoid any plugins writing files at random places
399 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
401 char *input_log_file = NULL;
402 char *output_log_file = NULL;
403 char *error_log_file = NULL;
404 char *access_log_file = NULL;
409 // --------------------------------------------------------------------
411 sprintf(buffer, "0x%08llx", 0ULL);
412 char *flags = config_get("global", "debug flags", buffer);
413 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
415 debug_flags = strtoull(flags, NULL, 0);
416 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
418 if(debug_flags != 0) {
419 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
420 if(setrlimit(RLIMIT_CORE, &rl) != 0)
421 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
422 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
425 // --------------------------------------------------------------------
427 #ifdef MADV_MERGEABLE
428 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
430 #warning "Kernel memory deduplication (KSM) is not available"
433 // --------------------------------------------------------------------
436 global_host_prefix = config_get("global", "host access prefix", "");
437 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
439 // --------------------------------------------------------------------
441 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
442 if(strcmp(output_log_file, "syslog") == 0) {
443 output_log_syslog = 1;
444 output_log_file = NULL;
446 else if(strcmp(output_log_file, "none") == 0) {
447 output_log_syslog = 0;
448 output_log_file = NULL;
450 else output_log_syslog = 0;
452 // --------------------------------------------------------------------
454 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
455 if(strcmp(error_log_file, "syslog") == 0) {
456 error_log_syslog = 1;
457 error_log_file = NULL;
459 else if(strcmp(error_log_file, "none") == 0) {
460 error_log_syslog = 0;
461 error_log_file = NULL;
462 // optimization - do not even generate debug log entries
464 else error_log_syslog = 0;
466 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
467 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
469 error_log_errors_per_period = config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
470 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
472 // --------------------------------------------------------------------
474 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
475 if(strcmp(access_log_file, "syslog") == 0) {
476 access_log_syslog = 1;
477 access_log_file = NULL;
479 else if(strcmp(access_log_file, "none") == 0) {
480 access_log_syslog = 0;
481 access_log_file = NULL;
483 else access_log_syslog = 0;
485 // --------------------------------------------------------------------
487 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
489 // --------------------------------------------------------------------
491 if(gethostname(buffer, HOSTNAME_MAX) == -1)
492 error("WARNING: Cannot get machine hostname.");
493 hostname = config_get("global", "hostname", buffer);
494 debug(D_OPTIONS, "hostname set to '%s'", hostname);
496 // --------------------------------------------------------------------
498 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
499 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
500 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
501 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
504 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
507 // --------------------------------------------------------------------
509 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
510 if(rrd_update_every < 1 || rrd_update_every > 600) {
511 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
512 rrd_update_every = UPDATE_EVERY;
514 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
516 // let the plugins know the min update_every
519 snprintfz(buf, 50, "%d", rrd_update_every);
520 setenv("NETDATA_UPDATE_EVERY", buf, 1);
523 // --------------------------------------------------------------------
525 // block signals while initializing threads.
526 // this causes the threads to block signals.
530 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
531 error("Could not block signals for threads");
534 // Catch signals which we want to use to quit savely
536 sigemptyset(&sa.sa_mask);
537 sigaddset(&sa.sa_mask, SIGHUP);
538 sigaddset(&sa.sa_mask, SIGINT);
539 sigaddset(&sa.sa_mask, SIGTERM);
540 sa.sa_handler = sig_handler;
542 if(sigaction(SIGHUP, &sa, NULL) == -1) {
543 error("Failed to change signal handler for SIGHUP");
545 if(sigaction(SIGINT, &sa, NULL) == -1) {
546 error("Failed to change signal handler for SIGINT");
548 if(sigaction(SIGTERM, &sa, NULL) == -1) {
549 error("Failed to change signal handler for SIGTERM");
551 // Ignore SIGPIPE completely.
552 // INFO: If we add signals here we have to unblock them
553 // at popen.c when running a external plugin.
554 sa.sa_handler = SIG_IGN;
555 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
556 error("Failed to change signal handler for SIGTERM");
559 // --------------------------------------------------------------------
561 i = pthread_attr_init(&attr);
563 fatal("pthread_attr_init() failed with code %d.", i);
565 i = pthread_attr_getstacksize(&attr, &stacksize);
567 fatal("pthread_attr_getstacksize() failed with code %d.", i);
569 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
571 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
573 // --------------------------------------------------------------------
575 for (i = 0; static_threads[i].name != NULL ; i++) {
576 struct netdata_static_thread *st = &static_threads[i];
578 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
579 if(st->enabled && st->init_routine) st->init_routine();
582 // --------------------------------------------------------------------
584 // get the user we should run
585 // IMPORTANT: this is required before web_files_uid()
586 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
588 // IMPORTANT: these have to run once, while single threaded
589 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
592 // --------------------------------------------------------------------
594 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
596 listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
597 if(listen_port < 1 || listen_port > 65535) {
598 info("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
599 listen_port = LISTEN_PORT;
601 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
604 char *ipv = config_get("global", "ip version", "any");
605 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
606 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
607 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
608 else info("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
610 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
612 listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
613 if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port);
616 if(listen_fd < 0) fatal("Cannot listen socket.");
619 // never become a problem
620 if(nice(20) == -1) error("Cannot lower my CPU priority.");
622 if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
623 fatal("Cannot demonize myself.");
625 #ifdef NETDATA_INTERNAL_CHECKS
626 if(debug_flags != 0) {
627 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
628 if(setrlimit(RLIMIT_CORE, &rl) != 0)
629 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
630 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
632 #endif /* NETDATA_INTERNAL_CHECKS */
634 if(output_log_syslog || error_log_syslog || access_log_syslog)
635 openlog("netdata", LOG_PID, LOG_DAEMON);
637 info("NetData started on pid %d", getpid());
640 // ------------------------------------------------------------------------
641 // get default pthread stack size
643 if(stacksize < wanted_stacksize) {
644 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
646 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
648 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
651 // --------------------------------------------------------------------
652 // initialize the registry
656 // ------------------------------------------------------------------------
659 for (i = 0; static_threads[i].name != NULL ; i++) {
660 struct netdata_static_thread *st = &static_threads[i];
663 st->thread = malloc(sizeof(pthread_t));
665 fatal("Cannot allocate pthread_t memory");
667 info("Starting thread %s.", st->name);
669 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
670 error("failed to create new thread for %s.", st->name);
672 else if(pthread_detach(*st->thread))
673 error("Cannot request detach of newly created %s thread.", st->name);
675 else info("Not starting thread %s.", st->name);
678 // ------------------------------------------------------------------------
679 // block signals while initializing threads.
683 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
684 error("Could not unblock signals for threads");
687 // Handle flags set in the signal handler.
691 info("Exit main loop of netdata.");
692 netdata_cleanup_and_exit(0);