3 extern void *cgroups_main(void *ptr);
5 volatile sig_atomic_t netdata_exit = 0;
7 void netdata_cleanup_and_exit(int ret) {
10 error_log_limit_unlimited();
12 info("Called: netdata_cleanup_and_exit()");
13 #ifdef NETDATA_INTERNAL_CHECKS
21 if(unlink(pidfile) != 0)
22 error("Cannot unlink pidfile '%s'.", pidfile);
25 info("NetData exiting. Bye bye...");
29 struct netdata_static_thread {
39 void (*init_routine) (void);
40 void *(*start_routine) (void *);
41 } static_threads[] = {
42 #ifdef INTERNAL_PLUGIN_NFACCT
43 // nfacct requires root access
44 // so, we build it as an external plugin with setuid to root
45 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
48 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
49 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
50 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
51 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
52 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
53 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
54 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
55 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
56 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
59 void web_server_threading_selection(void) {
60 int threaded = config_get_boolean("global", "multi threaded web server", 1);
63 for(i = 0; static_threads[i].name ; i++) {
64 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
65 static_threads[i].enabled = threaded?1:0;
67 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
68 static_threads[i].enabled = threaded?0:1;
71 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
73 web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
75 #ifdef NETDATA_WITH_ZLIB
76 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
78 char *s = config_get("global", "web compression strategy", "default");
79 if(!strcmp(s, "default"))
80 web_gzip_strategy = Z_DEFAULT_STRATEGY;
81 else if(!strcmp(s, "filtered"))
82 web_gzip_strategy = Z_FILTERED;
83 else if(!strcmp(s, "huffman only"))
84 web_gzip_strategy = Z_HUFFMAN_ONLY;
85 else if(!strcmp(s, "rle"))
86 web_gzip_strategy = Z_RLE;
87 else if(!strcmp(s, "fixed"))
88 web_gzip_strategy = Z_FIXED;
90 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
91 web_gzip_strategy = Z_DEFAULT_STRATEGY;
94 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
95 if(web_gzip_level < 1) {
96 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
99 else if(web_gzip_level > 9) {
100 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
103 #endif /* NETDATA_WITH_ZLIB */
107 int killpid(pid_t pid, int sig)
110 debug(D_EXIT, "Request to kill pid %d", pid);
113 if(kill(pid, 0) == -1) {
116 error("Request to kill pid %d, but it is not running.", pid);
120 error("Request to kill pid %d, but I do not have enough permissions.", pid);
124 error("Request to kill pid %d, but I received an error.", pid);
130 ret = kill(pid, sig);
134 error("Cannot kill pid %d, but it is not running.", pid);
138 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
142 error("Cannot kill pid %d, but I received an error.", pid);
155 struct web_client *w;
156 for(w = web_clients; w ; w = w->next) {
157 debug(D_EXIT, "Stopping web client %s", w->client_ip);
158 pthread_cancel(w->thread);
159 pthread_join(w->thread, NULL);
163 for (i = 0; static_threads[i].name != NULL ; i++) {
164 if(static_threads[i].thread) {
165 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
166 pthread_cancel(*static_threads[i].thread);
167 pthread_join(*static_threads[i].thread, NULL);
168 static_threads[i].thread = NULL;
173 info("Killing tc-qos-helper procees");
174 if(killpid(tc_child_pid, SIGTERM) != -1)
175 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
180 for(cd = pluginsd_root ; cd ; cd = cd->next) {
181 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
182 pthread_cancel(cd->thread);
183 pthread_join(cd->thread, NULL);
185 if(cd->pid && !cd->obsolete) {
186 debug(D_EXIT, "killing %s plugin process", cd->id);
187 if(killpid(cd->pid, SIGTERM) != -1)
188 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
192 // if, for any reason there is any child exited
194 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
196 debug(D_EXIT, "All threads/childs stopped.");
199 struct option_def options[] = {
200 // opt description arg name default value
201 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
202 {'D', "Disable fork into background", NULL, NULL},
203 {'h', "Display help message", NULL, NULL},
204 {'P', "File to save a pid while running", "FILE", NULL},
205 {'i', "The IP address to listen to.", "address", "All addresses"},
206 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
207 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
208 {'t', "The frequency in seconds, for data collection. \
209 Same as 'update every' config file option.", "seconds", "1"},
210 {'u', "System username to run as.", "username", "netdata"},
211 {'v', "Version of the program", NULL, NULL},
212 {'W', "vendor options.", "stacksize=<size>|unittest|debug_flag", NULL},
215 void help(int exitcode) {
222 int num_opts = sizeof(options) / sizeof(struct option_def);
226 // Compute maximum argument length
227 for( i = 0; i < num_opts; i++ ) {
228 if(options[i].arg_name) {
229 int len_arg = strlen(options[i].arg_name);
230 if(len_arg > max_len_arg) max_len_arg = len_arg;
234 fprintf(stream, "SYNOPSIS: netdata [options]\n");
235 fprintf(stream, "\n");
236 fprintf(stream, "Options:\n");
238 // Output options description.
239 for( i = 0; i < num_opts; i++ ) {
240 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
241 if(options[i].default_value) {
242 fprintf(stream, " Default: %s\n", options[i].default_value);
244 fprintf(stream, "\n");
252 // TODO: Remove this function with the nix major release.
253 void remove_option(int opt_index, int *argc, char **argv) {
255 // remove the options.
258 for(i = opt_index; i < *argc; i++) {
262 } while(argv[i][0] != '-' && opt_index >= *argc);
266 int main(int argc, char **argv)
269 int config_loaded = 0;
271 size_t wanted_stacksize = 0, stacksize = 0;
274 // global initialization
277 // set the name for logging
278 program_name = "netdata";
280 // parse command line.
282 // parse depercated options
283 // TODO: Remove this block with the next major release.
287 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
288 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
289 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
290 remove_option(i, &argc, argv);
292 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
294 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
295 remove_option(i, &argc, argv);
297 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
298 config_set("global", "host access prefix", argv[i+1]);
299 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
300 remove_option(i, &argc, argv);
302 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
303 config_set("global", "history", argv[i+1]);
304 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
305 remove_option(i, &argc, argv);
313 int num_opts = sizeof(options) / sizeof(struct option_def);
314 char optstring[(num_opts * 2) + 1];
317 for( i = 0; i < num_opts; i++ ) {
318 optstring[string_i] = options[i].val;
320 if(options[i].arg_name) {
321 optstring[string_i] = ':';
327 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
330 if(load_config(optarg, 1) != 1) {
331 error("Cannot load configuration file %s.", optarg);
335 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
346 config_set("global", "bind to", optarg);
349 strncpy(pidfile, optarg, FILENAME_MAX);
350 pidfile[FILENAME_MAX] = '\0';
353 config_set("global", "default port", optarg);
356 config_set("global", "host access prefix", optarg);
359 config_set("global", "update every", optarg);
362 config_set("global", "run as user", optarg);
365 // TODO: Outsource version to makefile which can compute version from git.
366 printf("netdata 1.2.1_master\n");
371 char* stacksize = "stacksize=";
372 char* debug_flags_string = "debug_flags=";
373 if(strcmp(optarg, "unittest") == 0) {
374 rrd_update_every = 1;
375 if(run_all_mockup_tests()) exit(1);
376 if(unit_test_storage()) exit(1);
377 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
379 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
380 optarg += strlen(stacksize);
381 config_set("global", "pthread stack size", optarg);
382 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
383 optarg += strlen(debug_flags_string);
384 config_set("global", "debug flags", optarg);
385 debug_flags = strtoull(optarg, NULL, 0);
396 if(!config_loaded) load_config(NULL, 0);
398 // prepare configuration environment variables for the plugins
399 setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1);
400 setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1);
401 setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1);
402 setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1);
403 setenv("NETDATA_LIB_DIR" , config_get("global", "lib directory" , VARLIB_DIR) , 1);
404 setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1);
405 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
406 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
408 // disable buffering for python plugins
409 setenv("PYTHONUNBUFFERED", "1", 1);
411 // avoid flood calls to stat(/etc/localtime)
412 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
413 setenv("TZ", ":/etc/localtime", 0);
416 char path[1024 + 1], *p = getenv("PATH");
417 if(!p) p = "/bin:/usr/bin";
418 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
419 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
422 // cd to /tmp to avoid any plugins writing files at random places
423 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
425 char *input_log_file = NULL;
426 char *output_log_file = NULL;
427 char *error_log_file = NULL;
428 char *access_log_file = NULL;
431 char *flags = config_get("global", "debug flags", "0x00000000");
432 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
434 debug_flags = strtoull(flags, NULL, 0);
435 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
437 if(debug_flags != 0) {
438 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
439 if(setrlimit(RLIMIT_CORE, &rl) != 0)
440 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
441 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
444 // --------------------------------------------------------------------
446 #ifdef MADV_MERGEABLE
447 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
449 #warning "Kernel memory deduplication (KSM) is not available"
452 // --------------------------------------------------------------------
455 global_host_prefix = config_get("global", "host access prefix", "");
456 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
458 // --------------------------------------------------------------------
460 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
461 if(strcmp(output_log_file, "syslog") == 0) {
462 output_log_syslog = 1;
463 output_log_file = NULL;
465 else if(strcmp(output_log_file, "none") == 0) {
466 output_log_syslog = 0;
467 output_log_file = NULL;
469 else output_log_syslog = 0;
471 // --------------------------------------------------------------------
473 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
474 if(strcmp(error_log_file, "syslog") == 0) {
475 error_log_syslog = 1;
476 error_log_file = NULL;
478 else if(strcmp(error_log_file, "none") == 0) {
479 error_log_syslog = 0;
480 error_log_file = NULL;
481 // optimization - do not even generate debug log entries
483 else error_log_syslog = 0;
485 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
486 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
488 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
489 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
491 // --------------------------------------------------------------------
493 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
494 if(strcmp(access_log_file, "syslog") == 0) {
495 access_log_syslog = 1;
496 access_log_file = NULL;
498 else if(strcmp(access_log_file, "none") == 0) {
499 access_log_syslog = 0;
500 access_log_file = NULL;
502 else access_log_syslog = 0;
504 // --------------------------------------------------------------------
506 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
508 // --------------------------------------------------------------------
511 char hostnamebuf[HOSTNAME_MAX + 1];
512 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
513 error("WARNING: Cannot get machine hostname.");
514 hostname = config_get("global", "hostname", hostnamebuf);
515 debug(D_OPTIONS, "hostname set to '%s'", hostname);
518 // --------------------------------------------------------------------
520 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
521 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
522 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
523 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
526 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
529 // --------------------------------------------------------------------
531 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
532 if(rrd_update_every < 1 || rrd_update_every > 600) {
533 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
534 rrd_update_every = UPDATE_EVERY;
536 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
538 // let the plugins know the min update_every
541 snprintfz(buf, 15, "%d", rrd_update_every);
542 setenv("NETDATA_UPDATE_EVERY", buf, 1);
545 // --------------------------------------------------------------------
547 // block signals while initializing threads.
548 // this causes the threads to block signals.
552 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
553 error("Could not block signals for threads");
556 // Catch signals which we want to use to quit savely
558 sigemptyset(&sa.sa_mask);
559 sigaddset(&sa.sa_mask, SIGHUP);
560 sigaddset(&sa.sa_mask, SIGINT);
561 sigaddset(&sa.sa_mask, SIGTERM);
562 sa.sa_handler = sig_handler_exit;
564 if(sigaction(SIGHUP, &sa, NULL) == -1) {
565 error("Failed to change signal handler for SIGHUP");
567 if(sigaction(SIGINT, &sa, NULL) == -1) {
568 error("Failed to change signal handler for SIGINT");
570 if(sigaction(SIGTERM, &sa, NULL) == -1) {
571 error("Failed to change signal handler for SIGTERM");
574 // save database on SIGUSR1
575 sa.sa_handler = sig_handler_save;
576 if(sigaction(SIGUSR1, &sa, NULL) == -1) {
577 error("Failed to change signal handler for SIGUSR1");
580 // Ignore SIGPIPE completely.
581 // INFO: If we add signals here we have to unblock them
582 // at popen.c when running a external plugin.
583 sa.sa_handler = SIG_IGN;
584 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
585 error("Failed to change signal handler for SIGPIPE");
588 // --------------------------------------------------------------------
590 i = pthread_attr_init(&attr);
592 fatal("pthread_attr_init() failed with code %d.", i);
594 i = pthread_attr_getstacksize(&attr, &stacksize);
596 fatal("pthread_attr_getstacksize() failed with code %d.", i);
598 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
600 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
602 // --------------------------------------------------------------------
604 for (i = 0; static_threads[i].name != NULL ; i++) {
605 struct netdata_static_thread *st = &static_threads[i];
607 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
608 if(st->enabled && st->init_routine) st->init_routine();
611 // --------------------------------------------------------------------
613 // get the user we should run
614 // IMPORTANT: this is required before web_files_uid()
615 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
617 // IMPORTANT: these have to run once, while single threaded
618 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
621 // --------------------------------------------------------------------
623 create_listen_sockets();
626 // never become a problem
627 if(nice(20) == -1) error("Cannot lower my CPU priority.");
629 if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
630 fatal("Cannot demonize myself.");
632 #ifdef NETDATA_INTERNAL_CHECKS
633 if(debug_flags != 0) {
634 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
635 if(setrlimit(RLIMIT_CORE, &rl) != 0)
636 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
637 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
639 #endif /* NETDATA_INTERNAL_CHECKS */
641 if(output_log_syslog || error_log_syslog || access_log_syslog)
642 openlog("netdata", LOG_PID, LOG_DAEMON);
644 info("NetData started on pid %d", getpid());
647 // ------------------------------------------------------------------------
648 // get default pthread stack size
650 if(stacksize < wanted_stacksize) {
651 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
653 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
655 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
658 // --------------------------------------------------------------------
659 // initialize the registry
663 // ------------------------------------------------------------------------
666 web_server_threading_selection();
668 for (i = 0; static_threads[i].name != NULL ; i++) {
669 struct netdata_static_thread *st = &static_threads[i];
672 st->thread = malloc(sizeof(pthread_t));
674 fatal("Cannot allocate pthread_t memory");
676 info("Starting thread %s.", st->name);
678 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
679 error("failed to create new thread for %s.", st->name);
681 else if(pthread_detach(*st->thread))
682 error("Cannot request detach of newly created %s thread.", st->name);
684 else info("Not starting thread %s.", st->name);
687 // ------------------------------------------------------------------------
688 // block signals while initializing threads.
692 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
693 error("Could not unblock signals for threads");
696 // Handle flags set in the signal handler.
700 info("Exit main loop of netdata.");
701 netdata_cleanup_and_exit(0);