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(ftruncate(pidfd, 0) != 0)
54 error("Cannot truncate pidfile '%s'.", pidfile);
61 if(unlink(pidfile) != 0)
62 error("Cannot unlink pidfile '%s'.", pidfile);
65 info("NetData exiting. Bye bye...");
69 struct netdata_static_thread {
79 void (*init_routine) (void);
80 void *(*start_routine) (void *);
83 struct netdata_static_thread static_threads[] = {
84 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
85 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
86 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
87 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
89 #ifdef INTERNAL_PLUGIN_NFACCT
90 // nfacct requires root access
91 // so, we build it as an external plugin with setuid to root
92 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
95 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
96 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
97 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main},
98 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
101 int killpid(pid_t pid, int sig)
104 debug(D_EXIT, "Request to kill pid %d", pid);
107 if(kill(pid, 0) == -1) {
110 error("Request to kill pid %d, but it is not running.", pid);
114 error("Request to kill pid %d, but I do not have enough permissions.", pid);
118 error("Request to kill pid %d, but I received an error.", pid);
124 ret = kill(pid, sig);
128 error("Cannot kill pid %d, but it is not running.", pid);
132 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
136 error("Cannot kill pid %d, but I received an error.", pid);
149 struct web_client *w;
150 for(w = web_clients; w ; w = w->next) {
151 debug(D_EXIT, "Stopping web client %s", w->client_ip);
152 pthread_cancel(w->thread);
153 pthread_join(w->thread, NULL);
157 for (i = 0; static_threads[i].name != NULL ; i++) {
158 if(static_threads[i].thread) {
159 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
160 pthread_cancel(*static_threads[i].thread);
161 pthread_join(*static_threads[i].thread, NULL);
162 static_threads[i].thread = NULL;
167 info("Killing tc-qos-helper procees");
168 if(killpid(tc_child_pid, SIGTERM) != -1)
169 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
174 for(cd = pluginsd_root ; cd ; cd = cd->next) {
175 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
176 pthread_cancel(cd->thread);
177 pthread_join(cd->thread, NULL);
179 if(cd->pid && !cd->obsolete) {
180 debug(D_EXIT, "killing %s plugin process", cd->id);
181 if(killpid(cd->pid, SIGTERM) != -1)
182 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
186 // if, for any reason there is any child exited
188 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
190 debug(D_EXIT, "All threads/childs stopped.");
193 struct option_def options[] = {
194 // opt description arg name default value
195 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
196 {'D', "Disable fork into background", NULL, NULL},
197 {'h', "Display help message", NULL, NULL},
198 {'P', "File to save a pid while running", "FILE", NULL},
199 {'i', "The IP address to listen to.", "address", "All addresses"},
200 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
201 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
202 {'t', "The frequency in seconds, for data collection. \
203 Same as 'update every' config file option.", "seconds", "1"},
204 {'u', "System username to run as.", "username", "netdata"},
205 {'v', "Version of the program", NULL, NULL},
206 {'W', "vendor options.", "stacksize=<size>|unittest|debug_flag", NULL},
209 void help(int exitcode) {
216 int num_opts = sizeof(options) / sizeof(struct option_def);
220 // Compute maximum argument length
221 for( i = 0; i < num_opts; i++ ) {
222 if(options[i].arg_name) {
223 int len_arg = strlen(options[i].arg_name);
224 if(len_arg > max_len_arg) max_len_arg = len_arg;
228 fprintf(stream, "SYNOPSIS: netdata [options]\n");
229 fprintf(stream, "\n");
230 fprintf(stream, "Options:\n");
232 // Output options description.
233 for( i = 0; i < num_opts; i++ ) {
234 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
235 if(options[i].default_value) {
236 fprintf(stream, " Default: %s\n", options[i].default_value);
238 fprintf(stream, "\n");
246 // TODO: Remove this function with the nix major release.
247 void remove_option(int opt_index, int *argc, char **argv) {
249 // remove the options.
252 for(i = opt_index; i < *argc; i++) {
256 } while(argv[i][0] != '-' && opt_index >= *argc);
260 int main(int argc, char **argv)
263 int config_loaded = 0;
265 size_t wanted_stacksize = 0, stacksize = 0;
268 // global initialization
271 // set the name for logging
272 program_name = "netdata";
274 // parse command line.
276 // parse depercated options
277 // TODO: Remove this block with the next major release.
281 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
282 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
283 fprintf(stderr, "%s: deprecate option -- %s -- please use -P instead.\n", argv[0], argv[i]);
284 remove_option(i, &argc, argv);
286 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
288 fprintf(stderr, "%s: deprecate option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
289 remove_option(i, &argc, argv);
291 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
292 config_set("global", "host access prefix", argv[i+1]);
293 fprintf(stderr, "%s: deprecate option -- %s -- please use -s instead.\n", argv[0], argv[i]);
294 remove_option(i, &argc, argv);
296 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
297 config_set("global", "history", argv[i+1]);
298 fprintf(stderr, "%s: deprecate option -- %s -- This option will be rmoved with V2.*.\n", argv[0], argv[i]);
299 remove_option(i, &argc, argv);
307 int num_opts = sizeof(options) / sizeof(struct option_def);
308 char optstring[(num_opts * 2) + 1];
311 for( i = 0; i < num_opts; i++ ) {
312 optstring[string_i] = options[i].val;
314 if(options[i].arg_name) {
315 optstring[string_i] = ':';
321 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
324 if(load_config(optarg, 1) != 1) {
325 error("Cannot load configuration file %s.", optarg);
329 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
340 config_set("global", "bind socket to IP", optarg);
343 strncpy(pidfile, optarg, FILENAME_MAX);
344 pidfile[FILENAME_MAX] = '\0';
347 config_set("global", "port", optarg);
350 config_set("global", "host access prefix", optarg);
353 config_set("global", "update every", optarg);
356 config_set("global", "run as user", optarg);
359 // TODO: Outsource version to makefile which can compute version from git.
360 printf("netdata 1.1.0\n");
365 char* stacksize = "stacksize=";
366 char* debug_flags_string = "debug_flags=";
367 if(strcmp(optarg, "unittest") == 0) {
368 rrd_update_every = 1;
369 if(run_all_mockup_tests()) exit(1);
370 if(unit_test_storage()) exit(1);
371 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
373 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
374 optarg += strlen(stacksize);
375 config_set("global", "pthread stack size", optarg);
376 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
377 optarg += strlen(debug_flags_string);
378 config_set("global", "debug flags", optarg);
379 debug_flags = strtoull(optarg, NULL, 0);
390 if(!config_loaded) load_config(NULL, 0);
392 // prepare configuration environment variables for the plugins
393 setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1);
394 setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1);
395 setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1);
396 setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1);
397 setenv("NETDATA_LIB_DIR" , config_get("global", "lib directory" , VARLIB_DIR) , 1);
398 setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1);
399 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
400 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
402 // avoid extended to stat(/etc/localtime)
403 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
404 setenv("TZ", ":/etc/localtime", 0);
406 // cd to /tmp to avoid any plugins writing files at random places
407 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
409 char *input_log_file = NULL;
410 char *output_log_file = NULL;
411 char *error_log_file = NULL;
412 char *access_log_file = NULL;
417 // --------------------------------------------------------------------
419 sprintf(buffer, "0x%08llx", 0ULL);
420 char *flags = config_get("global", "debug flags", buffer);
421 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
423 debug_flags = strtoull(flags, NULL, 0);
424 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
426 if(debug_flags != 0) {
427 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
428 if(setrlimit(RLIMIT_CORE, &rl) != 0)
429 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
430 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
433 // --------------------------------------------------------------------
435 #ifdef MADV_MERGEABLE
436 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
438 #warning "Kernel memory deduplication (KSM) is not available"
441 // --------------------------------------------------------------------
444 global_host_prefix = config_get("global", "host access prefix", "");
445 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
447 // --------------------------------------------------------------------
449 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
450 if(strcmp(output_log_file, "syslog") == 0) {
451 output_log_syslog = 1;
452 output_log_file = NULL;
454 else if(strcmp(output_log_file, "none") == 0) {
455 output_log_syslog = 0;
456 output_log_file = NULL;
458 else output_log_syslog = 0;
460 // --------------------------------------------------------------------
462 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
463 if(strcmp(error_log_file, "syslog") == 0) {
464 error_log_syslog = 1;
465 error_log_file = NULL;
467 else if(strcmp(error_log_file, "none") == 0) {
468 error_log_syslog = 0;
469 error_log_file = NULL;
470 // optimization - do not even generate debug log entries
472 else error_log_syslog = 0;
474 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
475 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
477 error_log_errors_per_period = config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
478 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
480 // --------------------------------------------------------------------
482 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
483 if(strcmp(access_log_file, "syslog") == 0) {
484 access_log_syslog = 1;
485 access_log_file = NULL;
487 else if(strcmp(access_log_file, "none") == 0) {
488 access_log_syslog = 0;
489 access_log_file = NULL;
491 else access_log_syslog = 0;
493 // --------------------------------------------------------------------
495 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
497 // --------------------------------------------------------------------
499 if(gethostname(buffer, HOSTNAME_MAX) == -1)
500 error("WARNING: Cannot get machine hostname.");
501 hostname = config_get("global", "hostname", buffer);
502 debug(D_OPTIONS, "hostname set to '%s'", hostname);
504 // --------------------------------------------------------------------
506 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
507 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
508 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
509 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
512 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
515 // --------------------------------------------------------------------
517 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
518 if(rrd_update_every < 1 || rrd_update_every > 600) {
519 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
520 rrd_update_every = UPDATE_EVERY;
522 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
524 // let the plugins know the min update_every
527 snprintfz(buf, 50, "%d", rrd_update_every);
528 setenv("NETDATA_UPDATE_EVERY", buf, 1);
531 // --------------------------------------------------------------------
533 // block signals while initializing threads.
534 // this causes the threads to block signals.
538 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
539 error("Could not block signals for threads");
542 // Catch signals which we want to use to quit savely
544 sigemptyset(&sa.sa_mask);
545 sigaddset(&sa.sa_mask, SIGHUP);
546 sigaddset(&sa.sa_mask, SIGINT);
547 sigaddset(&sa.sa_mask, SIGTERM);
548 sa.sa_handler = sig_handler;
550 if(sigaction(SIGHUP, &sa, NULL) == -1) {
551 error("Failed to change signal handler for SIGHUP");
553 if(sigaction(SIGINT, &sa, NULL) == -1) {
554 error("Failed to change signal handler for SIGINT");
556 if(sigaction(SIGTERM, &sa, NULL) == -1) {
557 error("Failed to change signal handler for SIGTERM");
559 // Ignore SIGPIPE completely.
560 // INFO: If we add signals here we have to unblock them
561 // at popen.c when running a external plugin.
562 sa.sa_handler = SIG_IGN;
563 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
564 error("Failed to change signal handler for SIGTERM");
567 // --------------------------------------------------------------------
569 i = pthread_attr_init(&attr);
571 fatal("pthread_attr_init() failed with code %d.", i);
573 i = pthread_attr_getstacksize(&attr, &stacksize);
575 fatal("pthread_attr_getstacksize() failed with code %d.", i);
577 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
579 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
581 // --------------------------------------------------------------------
583 for (i = 0; static_threads[i].name != NULL ; i++) {
584 struct netdata_static_thread *st = &static_threads[i];
586 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
587 if(st->enabled && st->init_routine) st->init_routine();
590 // --------------------------------------------------------------------
592 // get the user we should run
593 // IMPORTANT: this is required before web_files_uid()
594 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
596 // IMPORTANT: these have to run once, while single threaded
597 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
600 // --------------------------------------------------------------------
602 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
604 listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
605 if(listen_port < 1 || listen_port > 65535) {
606 info("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
607 listen_port = LISTEN_PORT;
609 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
612 char *ipv = config_get("global", "ip version", "any");
613 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
614 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
615 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
616 else info("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
618 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
620 listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
621 if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port);
624 if(listen_fd < 0) fatal("Cannot listen socket.");
627 // never become a problem
628 if(nice(20) == -1) error("Cannot lower my CPU priority.");
630 if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
631 fatal("Cannot demonize myself.");
633 #ifdef NETDATA_INTERNAL_CHECKS
634 if(debug_flags != 0) {
635 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
636 if(setrlimit(RLIMIT_CORE, &rl) != 0)
637 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
638 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
640 #endif /* NETDATA_INTERNAL_CHECKS */
642 if(output_log_syslog || error_log_syslog || access_log_syslog)
643 openlog("netdata", LOG_PID, LOG_DAEMON);
645 info("NetData started on pid %d", getpid());
648 // ------------------------------------------------------------------------
649 // get default pthread stack size
651 if(stacksize < wanted_stacksize) {
652 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
654 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
656 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
659 // --------------------------------------------------------------------
660 // initialize the registry
664 // ------------------------------------------------------------------------
667 for (i = 0; static_threads[i].name != NULL ; i++) {
668 struct netdata_static_thread *st = &static_threads[i];
671 st->thread = malloc(sizeof(pthread_t));
673 fatal("Cannot allocate pthread_t memory");
675 info("Starting thread %s.", st->name);
677 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
678 error("failed to create new thread for %s.", st->name);
680 else if(pthread_detach(*st->thread))
681 error("Cannot request detach of newly created %s thread.", st->name);
683 else info("Not starting thread %s.", st->name);
686 // ------------------------------------------------------------------------
687 // block signals while initializing threads.
691 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
692 error("Could not unblock signals for threads");
695 // Handle flags set in the signal handler.
699 info("Exit main loop of netdata.");
700 netdata_cleanup_and_exit(0);