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 *);
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 #ifdef NETDATA_WITH_ZLIB
106 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
108 char *s = config_get("global", "web compression strategy", "default");
109 if(!strcmp(s, "default"))
110 web_gzip_strategy = Z_DEFAULT_STRATEGY;
111 else if(!strcmp(s, "filtered"))
112 web_gzip_strategy = Z_FILTERED;
113 else if(!strcmp(s, "huffman only"))
114 web_gzip_strategy = Z_HUFFMAN_ONLY;
115 else if(!strcmp(s, "rle"))
116 web_gzip_strategy = Z_RLE;
117 else if(!strcmp(s, "fixed"))
118 web_gzip_strategy = Z_FIXED;
120 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.");
121 web_gzip_strategy = Z_DEFAULT_STRATEGY;
124 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
125 if(web_gzip_level < 1) {
126 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).");
129 else if(web_gzip_level > 9) {
130 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).");
133 #endif /* NETDATA_WITH_ZLIB */
137 int killpid(pid_t pid, int sig)
140 debug(D_EXIT, "Request to kill pid %d", pid);
143 if(kill(pid, 0) == -1) {
146 error("Request to kill pid %d, but it is not running.", pid);
150 error("Request to kill pid %d, but I do not have enough permissions.", pid);
154 error("Request to kill pid %d, but I received an error.", pid);
160 ret = kill(pid, sig);
164 error("Cannot kill pid %d, but it is not running.", pid);
168 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
172 error("Cannot kill pid %d, but I received an error.", pid);
185 struct web_client *w;
186 for(w = web_clients; w ; w = w->next) {
187 debug(D_EXIT, "Stopping web client %s", w->client_ip);
188 pthread_cancel(w->thread);
189 pthread_join(w->thread, NULL);
193 for (i = 0; static_threads[i].name != NULL ; i++) {
194 if(static_threads[i].thread) {
195 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
196 pthread_cancel(*static_threads[i].thread);
197 pthread_join(*static_threads[i].thread, NULL);
198 static_threads[i].thread = NULL;
203 info("Killing tc-qos-helper procees");
204 if(killpid(tc_child_pid, SIGTERM) != -1)
205 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
210 for(cd = pluginsd_root ; cd ; cd = cd->next) {
211 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
212 pthread_cancel(cd->thread);
213 pthread_join(cd->thread, NULL);
215 if(cd->pid && !cd->obsolete) {
216 debug(D_EXIT, "killing %s plugin process", cd->id);
217 if(killpid(cd->pid, SIGTERM) != -1)
218 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
222 // if, for any reason there is any child exited
224 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
226 debug(D_EXIT, "All threads/childs stopped.");
229 struct option_def options[] = {
230 // opt description arg name default value
231 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
232 {'D', "Disable fork into background", NULL, NULL},
233 {'h', "Display help message", NULL, NULL},
234 {'P', "File to save a pid while running", "FILE", NULL},
235 {'i', "The IP address to listen to.", "address", "All addresses"},
236 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
237 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
238 {'t', "The frequency in seconds, for data collection. \
239 Same as 'update every' config file option.", "seconds", "1"},
240 {'u', "System username to run as.", "username", "netdata"},
241 {'v', "Version of the program", NULL, NULL},
242 {'W', "vendor options.", "stacksize=<size>|unittest|debug_flag", NULL},
245 void help(int exitcode) {
252 int num_opts = sizeof(options) / sizeof(struct option_def);
256 // Compute maximum argument length
257 for( i = 0; i < num_opts; i++ ) {
258 if(options[i].arg_name) {
259 int len_arg = strlen(options[i].arg_name);
260 if(len_arg > max_len_arg) max_len_arg = len_arg;
264 fprintf(stream, "SYNOPSIS: netdata [options]\n");
265 fprintf(stream, "\n");
266 fprintf(stream, "Options:\n");
268 // Output options description.
269 for( i = 0; i < num_opts; i++ ) {
270 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
271 if(options[i].default_value) {
272 fprintf(stream, " Default: %s\n", options[i].default_value);
274 fprintf(stream, "\n");
282 // TODO: Remove this function with the nix major release.
283 void remove_option(int opt_index, int *argc, char **argv) {
285 // remove the options.
288 for(i = opt_index; i < *argc; i++) {
292 } while(argv[i][0] != '-' && opt_index >= *argc);
296 int main(int argc, char **argv)
299 int config_loaded = 0;
301 size_t wanted_stacksize = 0, stacksize = 0;
304 // global initialization
307 // set the name for logging
308 program_name = "netdata";
310 // parse command line.
312 // parse depercated options
313 // TODO: Remove this block with the next major release.
317 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
318 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
319 fprintf(stderr, "%s: deprecate option -- %s -- please use -P instead.\n", argv[0], argv[i]);
320 remove_option(i, &argc, argv);
322 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
324 fprintf(stderr, "%s: deprecate option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
325 remove_option(i, &argc, argv);
327 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
328 config_set("global", "host access prefix", argv[i+1]);
329 fprintf(stderr, "%s: deprecate option -- %s -- please use -s instead.\n", argv[0], argv[i]);
330 remove_option(i, &argc, argv);
332 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
333 config_set("global", "history", argv[i+1]);
334 fprintf(stderr, "%s: deprecate option -- %s -- This option will be rmoved with V2.*.\n", argv[0], argv[i]);
335 remove_option(i, &argc, argv);
343 int num_opts = sizeof(options) / sizeof(struct option_def);
344 char optstring[(num_opts * 2) + 1];
347 for( i = 0; i < num_opts; i++ ) {
348 optstring[string_i] = options[i].val;
350 if(options[i].arg_name) {
351 optstring[string_i] = ':';
357 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
360 if(load_config(optarg, 1) != 1) {
361 error("Cannot load configuration file %s.", optarg);
365 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
376 config_set("global", "bind socket to IP", optarg);
379 strncpy(pidfile, optarg, FILENAME_MAX);
380 pidfile[FILENAME_MAX] = '\0';
383 config_set("global", "port", optarg);
386 config_set("global", "host access prefix", optarg);
389 config_set("global", "update every", optarg);
392 config_set("global", "run as user", optarg);
395 // TODO: Outsource version to makefile which can compute version from git.
396 printf("netdata 1.1.0\n");
401 char* stacksize = "stacksize=";
402 char* debug_flags_string = "debug_flags=";
403 if(strcmp(optarg, "unittest") == 0) {
404 rrd_update_every = 1;
405 if(run_all_mockup_tests()) exit(1);
406 if(unit_test_storage()) exit(1);
407 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
409 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
410 optarg += strlen(stacksize);
411 config_set("global", "pthread stack size", optarg);
412 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
413 optarg += strlen(debug_flags_string);
414 config_set("global", "debug flags", optarg);
415 debug_flags = strtoull(optarg, NULL, 0);
426 if(!config_loaded) load_config(NULL, 0);
428 // prepare configuration environment variables for the plugins
429 setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1);
430 setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1);
431 setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1);
432 setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1);
433 setenv("NETDATA_LIB_DIR" , config_get("global", "lib directory" , VARLIB_DIR) , 1);
434 setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1);
435 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
436 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
438 // avoid extended to stat(/etc/localtime)
439 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
440 setenv("TZ", ":/etc/localtime", 0);
442 // cd to /tmp to avoid any plugins writing files at random places
443 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
445 char *input_log_file = NULL;
446 char *output_log_file = NULL;
447 char *error_log_file = NULL;
448 char *access_log_file = NULL;
453 // --------------------------------------------------------------------
455 sprintf(buffer, "0x%08llx", 0ULL);
456 char *flags = config_get("global", "debug flags", buffer);
457 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
459 debug_flags = strtoull(flags, NULL, 0);
460 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
462 if(debug_flags != 0) {
463 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
464 if(setrlimit(RLIMIT_CORE, &rl) != 0)
465 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
466 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
469 // --------------------------------------------------------------------
471 #ifdef MADV_MERGEABLE
472 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
474 #warning "Kernel memory deduplication (KSM) is not available"
477 // --------------------------------------------------------------------
480 global_host_prefix = config_get("global", "host access prefix", "");
481 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
483 // --------------------------------------------------------------------
485 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
486 if(strcmp(output_log_file, "syslog") == 0) {
487 output_log_syslog = 1;
488 output_log_file = NULL;
490 else if(strcmp(output_log_file, "none") == 0) {
491 output_log_syslog = 0;
492 output_log_file = NULL;
494 else output_log_syslog = 0;
496 // --------------------------------------------------------------------
498 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
499 if(strcmp(error_log_file, "syslog") == 0) {
500 error_log_syslog = 1;
501 error_log_file = NULL;
503 else if(strcmp(error_log_file, "none") == 0) {
504 error_log_syslog = 0;
505 error_log_file = NULL;
506 // optimization - do not even generate debug log entries
508 else error_log_syslog = 0;
510 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
511 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
513 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
514 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
516 // --------------------------------------------------------------------
518 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
519 if(strcmp(access_log_file, "syslog") == 0) {
520 access_log_syslog = 1;
521 access_log_file = NULL;
523 else if(strcmp(access_log_file, "none") == 0) {
524 access_log_syslog = 0;
525 access_log_file = NULL;
527 else access_log_syslog = 0;
529 // --------------------------------------------------------------------
531 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
533 // --------------------------------------------------------------------
535 if(gethostname(buffer, HOSTNAME_MAX) == -1)
536 error("WARNING: Cannot get machine hostname.");
537 hostname = config_get("global", "hostname", buffer);
538 debug(D_OPTIONS, "hostname set to '%s'", hostname);
540 // --------------------------------------------------------------------
542 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
543 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
544 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
545 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
548 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
551 // --------------------------------------------------------------------
553 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
554 if(rrd_update_every < 1 || rrd_update_every > 600) {
555 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
556 rrd_update_every = UPDATE_EVERY;
558 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
560 // let the plugins know the min update_every
563 snprintfz(buf, 50, "%d", rrd_update_every);
564 setenv("NETDATA_UPDATE_EVERY", buf, 1);
567 // --------------------------------------------------------------------
569 // block signals while initializing threads.
570 // this causes the threads to block signals.
574 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
575 error("Could not block signals for threads");
578 // Catch signals which we want to use to quit savely
580 sigemptyset(&sa.sa_mask);
581 sigaddset(&sa.sa_mask, SIGHUP);
582 sigaddset(&sa.sa_mask, SIGINT);
583 sigaddset(&sa.sa_mask, SIGTERM);
584 sa.sa_handler = sig_handler;
586 if(sigaction(SIGHUP, &sa, NULL) == -1) {
587 error("Failed to change signal handler for SIGHUP");
589 if(sigaction(SIGINT, &sa, NULL) == -1) {
590 error("Failed to change signal handler for SIGINT");
592 if(sigaction(SIGTERM, &sa, NULL) == -1) {
593 error("Failed to change signal handler for SIGTERM");
595 // Ignore SIGPIPE completely.
596 // INFO: If we add signals here we have to unblock them
597 // at popen.c when running a external plugin.
598 sa.sa_handler = SIG_IGN;
599 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
600 error("Failed to change signal handler for SIGTERM");
603 // --------------------------------------------------------------------
605 i = pthread_attr_init(&attr);
607 fatal("pthread_attr_init() failed with code %d.", i);
609 i = pthread_attr_getstacksize(&attr, &stacksize);
611 fatal("pthread_attr_getstacksize() failed with code %d.", i);
613 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
615 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
617 // --------------------------------------------------------------------
619 for (i = 0; static_threads[i].name != NULL ; i++) {
620 struct netdata_static_thread *st = &static_threads[i];
622 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
623 if(st->enabled && st->init_routine) st->init_routine();
626 // --------------------------------------------------------------------
628 // get the user we should run
629 // IMPORTANT: this is required before web_files_uid()
630 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
632 // IMPORTANT: these have to run once, while single threaded
633 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
636 // --------------------------------------------------------------------
638 listen_fd = create_listen_socket();
639 if(listen_fd < 0) fatal("Cannot listen socket.");
642 // never become a problem
643 if(nice(20) == -1) error("Cannot lower my CPU priority.");
645 if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
646 fatal("Cannot demonize myself.");
648 #ifdef NETDATA_INTERNAL_CHECKS
649 if(debug_flags != 0) {
650 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
651 if(setrlimit(RLIMIT_CORE, &rl) != 0)
652 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
653 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
655 #endif /* NETDATA_INTERNAL_CHECKS */
657 if(output_log_syslog || error_log_syslog || access_log_syslog)
658 openlog("netdata", LOG_PID, LOG_DAEMON);
660 info("NetData started on pid %d", getpid());
663 // ------------------------------------------------------------------------
664 // get default pthread stack size
666 if(stacksize < wanted_stacksize) {
667 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
669 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
671 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
674 // --------------------------------------------------------------------
675 // initialize the registry
679 // ------------------------------------------------------------------------
682 web_server_threading_selection();
684 for (i = 0; static_threads[i].name != NULL ; i++) {
685 struct netdata_static_thread *st = &static_threads[i];
688 st->thread = malloc(sizeof(pthread_t));
690 fatal("Cannot allocate pthread_t memory");
692 info("Starting thread %s.", st->name);
694 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
695 error("failed to create new thread for %s.", st->name);
697 else if(pthread_detach(*st->thread))
698 error("Cannot request detach of newly created %s thread.", st->name);
700 else info("Not starting thread %s.", st->name);
703 // ------------------------------------------------------------------------
704 // block signals while initializing threads.
708 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
709 error("Could not unblock signals for threads");
712 // Handle flags set in the signal handler.
716 info("Exit main loop of netdata.");
717 netdata_cleanup_and_exit(0);