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 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
200 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
201 {'t', "The frequency in seconds, for data collection. \
202 Same as 'update every' config file option.", "seconds", "1"},
203 {'l', "The number of entries the netdata daemon will keep in memory \
204 for each chart dimension. Same as 'history config file option.", "lines_to_save", NULL},
205 {'u', "System username to run as.", "username", "netdata"},
206 {'v', "Version of the program", NULL, NULL},
207 {'W', "vendor options.", "stacksize=<size>|unittest|debug_flag", NULL},
210 void help(int exitcode) {
217 int num_opts = sizeof(options) / sizeof(struct option_def);
221 // Compute maximum argument length
222 for( i = 0; i < num_opts; i++ ) {
223 if(options[i].arg_name) {
224 int len_arg = strlen(options[i].arg_name);
225 if(len_arg > max_len_arg) max_len_arg = len_arg;
229 fprintf(stream, "SYNOPSIS: netdata [options]\n");
230 fprintf(stream, "\n");
231 fprintf(stream, "Options:\n");
233 // Output options description.
234 for( i = 0; i < num_opts; i++ ) {
235 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
236 if(options[i].default_value) {
237 fprintf(stream, " Default: %s\n", options[i].default_value);
239 fprintf(stream, "\n");
248 int main(int argc, char **argv)
251 int config_loaded = 0;
253 size_t wanted_stacksize = 0, stacksize = 0;
256 // global initialization
259 // set the name for logging
260 program_name = "netdata";
262 // parse command line.
264 // parse depercated options
265 // TODO: Remove this block with the next major release.
267 void remove_option(int opt_index, int *argc, char **argv) {
269 // remove the options.
272 for(i = opt_index; i < *argc; i++) {
276 } while(argv[i][0] != '-' && opt_index >= *argc);
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);
302 int num_opts = sizeof(options) / sizeof(struct option_def);
303 char optstring[(num_opts * 2) + 1];
306 for( i = 0; i < num_opts; i++ ) {
307 optstring[string_i] = options[i].val;
309 if(options[i].arg_name) {
310 optstring[string_i] = ':';
316 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
319 if(load_config(optarg, 1) != 1) {
320 error("Cannot load configuration file %s.", optarg);
324 debug(D_OPTIONS, "Configuration loaded from %s.", 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");
356 config_set("global", "history", optarg);
360 char* stacksize = "stacksize=";
361 char* debug_flags_string = "debug_flags=";
362 if(strcmp(optarg, "unittest") == 0) {
363 rrd_update_every = 1;
364 if(run_all_mockup_tests()) exit(1);
365 if(unit_test_storage()) exit(1);
366 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
368 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
369 optarg += strlen(stacksize);
370 config_set("global", "pthread stack size", optarg);
371 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
372 optarg += strlen(debug_flags_string);
373 config_set("global", "debug flags", optarg);
374 debug_flags = strtoull(optarg, NULL, 0);
385 if(!config_loaded) load_config(NULL, 0);
387 // prepare configuration environment variables for the plugins
388 setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1);
389 setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1);
390 setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1);
391 setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1);
392 setenv("NETDATA_LIB_DIR" , config_get("global", "lib directory" , VARLIB_DIR) , 1);
393 setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1);
394 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
395 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
397 // avoid extended to stat(/etc/localtime)
398 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
399 setenv("TZ", ":/etc/localtime", 0);
401 // cd to /tmp to avoid any plugins writing files at random places
402 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
404 char *input_log_file = NULL;
405 char *output_log_file = NULL;
406 char *error_log_file = NULL;
407 char *access_log_file = NULL;
412 // --------------------------------------------------------------------
414 sprintf(buffer, "0x%08llx", 0ULL);
415 char *flags = config_get("global", "debug flags", buffer);
416 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
418 debug_flags = strtoull(flags, NULL, 0);
419 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
421 if(debug_flags != 0) {
422 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
423 if(setrlimit(RLIMIT_CORE, &rl) != 0)
424 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
425 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
428 // --------------------------------------------------------------------
430 #ifdef MADV_MERGEABLE
431 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
433 #warning "Kernel memory deduplication (KSM) is not available"
436 // --------------------------------------------------------------------
439 global_host_prefix = config_get("global", "host access prefix", "");
440 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
442 // --------------------------------------------------------------------
444 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
445 if(strcmp(output_log_file, "syslog") == 0) {
446 output_log_syslog = 1;
447 output_log_file = NULL;
449 else if(strcmp(output_log_file, "none") == 0) {
450 output_log_syslog = 0;
451 output_log_file = NULL;
453 else output_log_syslog = 0;
455 // --------------------------------------------------------------------
457 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
458 if(strcmp(error_log_file, "syslog") == 0) {
459 error_log_syslog = 1;
460 error_log_file = NULL;
462 else if(strcmp(error_log_file, "none") == 0) {
463 error_log_syslog = 0;
464 error_log_file = NULL;
465 // optimization - do not even generate debug log entries
467 else error_log_syslog = 0;
469 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
470 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
472 error_log_errors_per_period = config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
473 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
475 // --------------------------------------------------------------------
477 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
478 if(strcmp(access_log_file, "syslog") == 0) {
479 access_log_syslog = 1;
480 access_log_file = NULL;
482 else if(strcmp(access_log_file, "none") == 0) {
483 access_log_syslog = 0;
484 access_log_file = NULL;
486 else access_log_syslog = 0;
488 // --------------------------------------------------------------------
490 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
492 // --------------------------------------------------------------------
494 if(gethostname(buffer, HOSTNAME_MAX) == -1)
495 error("WARNING: Cannot get machine hostname.");
496 hostname = config_get("global", "hostname", buffer);
497 debug(D_OPTIONS, "hostname set to '%s'", hostname);
499 // --------------------------------------------------------------------
501 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
502 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
503 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
504 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
507 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
510 // --------------------------------------------------------------------
512 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
513 if(rrd_update_every < 1 || rrd_update_every > 600) {
514 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
515 rrd_update_every = UPDATE_EVERY;
517 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
519 // let the plugins know the min update_every
522 snprintfz(buf, 50, "%d", rrd_update_every);
523 setenv("NETDATA_UPDATE_EVERY", buf, 1);
526 // --------------------------------------------------------------------
528 // block signals while initializing threads.
529 // this causes the threads to block signals.
533 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
534 error("Could not block signals for threads");
537 // Catch signals which we want to use to quit savely
539 sigemptyset(&sa.sa_mask);
540 sigaddset(&sa.sa_mask, SIGHUP);
541 sigaddset(&sa.sa_mask, SIGINT);
542 sigaddset(&sa.sa_mask, SIGTERM);
543 sa.sa_handler = sig_handler;
545 if(sigaction(SIGHUP, &sa, NULL) == -1) {
546 error("Failed to change signal handler for SIGHUP");
548 if(sigaction(SIGINT, &sa, NULL) == -1) {
549 error("Failed to change signal handler for SIGINT");
551 if(sigaction(SIGTERM, &sa, NULL) == -1) {
552 error("Failed to change signal handler for SIGTERM");
554 // Ignore SIGPIPE completely.
555 // INFO: If we add signals here we have to unblock them
556 // at popen.c when running a external plugin.
557 sa.sa_handler = SIG_IGN;
558 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
559 error("Failed to change signal handler for SIGTERM");
562 // --------------------------------------------------------------------
564 i = pthread_attr_init(&attr);
566 fatal("pthread_attr_init() failed with code %d.", i);
568 i = pthread_attr_getstacksize(&attr, &stacksize);
570 fatal("pthread_attr_getstacksize() failed with code %d.", i);
572 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
574 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
576 // --------------------------------------------------------------------
578 for (i = 0; static_threads[i].name != NULL ; i++) {
579 struct netdata_static_thread *st = &static_threads[i];
581 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
582 if(st->enabled && st->init_routine) st->init_routine();
585 // --------------------------------------------------------------------
587 // get the user we should run
588 // IMPORTANT: this is required before web_files_uid()
589 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
591 // IMPORTANT: these have to run once, while single threaded
592 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
595 // --------------------------------------------------------------------
597 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
599 listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
600 if(listen_port < 1 || listen_port > 65535) {
601 info("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
602 listen_port = LISTEN_PORT;
604 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
607 char *ipv = config_get("global", "ip version", "any");
608 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
609 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
610 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
611 else info("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
613 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
615 listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
616 if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port);
619 if(listen_fd < 0) fatal("Cannot listen socket.");
622 // never become a problem
623 if(nice(20) == -1) error("Cannot lower my CPU priority.");
625 if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
626 fatal("Cannot demonize myself.");
628 #ifdef NETDATA_INTERNAL_CHECKS
629 if(debug_flags != 0) {
630 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
631 if(setrlimit(RLIMIT_CORE, &rl) != 0)
632 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
633 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
635 #endif /* NETDATA_INTERNAL_CHECKS */
637 if(output_log_syslog || error_log_syslog || access_log_syslog)
638 openlog("netdata", LOG_PID, LOG_DAEMON);
640 info("NetData started on pid %d", getpid());
643 // ------------------------------------------------------------------------
644 // get default pthread stack size
646 if(stacksize < wanted_stacksize) {
647 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
649 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
651 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
654 // --------------------------------------------------------------------
655 // initialize the registry
659 // ------------------------------------------------------------------------
662 for (i = 0; static_threads[i].name != NULL ; i++) {
663 struct netdata_static_thread *st = &static_threads[i];
666 st->thread = malloc(sizeof(pthread_t));
668 fatal("Cannot allocate pthread_t memory");
670 info("Starting thread %s.", st->name);
672 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
673 error("failed to create new thread for %s.", st->name);
675 else if(pthread_detach(*st->thread))
676 error("Cannot request detach of newly created %s thread.", st->name);
678 else info("Not starting thread %s.", st->name);
681 // ------------------------------------------------------------------------
682 // block signals while initializing threads.
686 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
687 error("Could not unblock signals for threads");
690 // Handle flags set in the signal handler.
694 info("Exit main loop of netdata.");
695 netdata_cleanup_and_exit(0);