3 extern void *cgroups_main(void *ptr);
5 void netdata_cleanup_and_exit(int ret) {
8 error_log_limit_unlimited();
10 info("Called: netdata_cleanup_and_exit()");
11 #ifdef NETDATA_INTERNAL_CHECKS
19 if(unlink(pidfile) != 0)
20 error("Cannot unlink pidfile '%s'.", pidfile);
23 info("NetData exiting. Bye bye...");
27 struct netdata_static_thread {
37 void (*init_routine) (void);
38 void *(*start_routine) (void *);
39 } static_threads[] = {
40 #ifdef INTERNAL_PLUGIN_NFACCT
41 // nfacct requires root access
42 // so, we build it as an external plugin with setuid to root
43 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
46 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
47 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
48 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
49 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
50 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
51 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
52 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main_multi_threaded},
53 {"web-single-threaded", NULL, NULL, 0, NULL, NULL, socket_listen_main_single_threaded},
54 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
57 void web_server_threading_selection(void) {
58 int threaded = config_get_boolean("global", "multi threaded web server", 1);
61 for(i = 0; static_threads[i].name ; i++) {
62 if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
63 static_threads[i].enabled = threaded?1:0;
65 if(static_threads[i].start_routine == socket_listen_main_single_threaded)
66 static_threads[i].enabled = threaded?0:1;
69 web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
71 web_donotrack_comply = config_get_boolean("global", "respect web browser do not track policy", web_donotrack_comply);
73 #ifdef NETDATA_WITH_ZLIB
74 web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
76 char *s = config_get("global", "web compression strategy", "default");
77 if(!strcmp(s, "default"))
78 web_gzip_strategy = Z_DEFAULT_STRATEGY;
79 else if(!strcmp(s, "filtered"))
80 web_gzip_strategy = Z_FILTERED;
81 else if(!strcmp(s, "huffman only"))
82 web_gzip_strategy = Z_HUFFMAN_ONLY;
83 else if(!strcmp(s, "rle"))
84 web_gzip_strategy = Z_RLE;
85 else if(!strcmp(s, "fixed"))
86 web_gzip_strategy = Z_FIXED;
88 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
89 web_gzip_strategy = Z_DEFAULT_STRATEGY;
92 web_gzip_level = (int)config_get_number("global", "web compression level", 3);
93 if(web_gzip_level < 1) {
94 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
97 else if(web_gzip_level > 9) {
98 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
101 #endif /* NETDATA_WITH_ZLIB */
105 int killpid(pid_t pid, int sig)
108 debug(D_EXIT, "Request to kill pid %d", pid);
111 if(kill(pid, 0) == -1) {
114 error("Request to kill pid %d, but it is not running.", pid);
118 error("Request to kill pid %d, but I do not have enough permissions.", pid);
122 error("Request to kill pid %d, but I received an error.", pid);
128 ret = kill(pid, sig);
132 error("Cannot kill pid %d, but it is not running.", pid);
136 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
140 error("Cannot kill pid %d, but I received an error.", pid);
153 struct web_client *w;
154 for(w = web_clients; w ; w = w->next) {
155 debug(D_EXIT, "Stopping web client %s", w->client_ip);
156 pthread_cancel(w->thread);
157 pthread_join(w->thread, NULL);
161 for (i = 0; static_threads[i].name != NULL ; i++) {
162 if(static_threads[i].thread) {
163 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
164 pthread_cancel(*static_threads[i].thread);
165 pthread_join(*static_threads[i].thread, NULL);
166 static_threads[i].thread = NULL;
171 info("Killing tc-qos-helper procees");
172 if(killpid(tc_child_pid, SIGTERM) != -1)
173 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
178 for(cd = pluginsd_root ; cd ; cd = cd->next) {
179 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
180 pthread_cancel(cd->thread);
181 pthread_join(cd->thread, NULL);
183 if(cd->pid && !cd->obsolete) {
184 debug(D_EXIT, "killing %s plugin process", cd->id);
185 if(killpid(cd->pid, SIGTERM) != -1)
186 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
190 // if, for any reason there is any child exited
192 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
194 debug(D_EXIT, "All threads/childs stopped.");
197 struct option_def options[] = {
198 // opt description arg name default value
199 {'c', "Load alternate configuration file", "config_file", CONFIG_DIR "/" CONFIG_FILENAME},
200 {'D', "Disable fork into background", NULL, NULL},
201 {'h', "Display help message", NULL, NULL},
202 {'P', "File to save a pid while running", "FILE", NULL},
203 {'i', "The IP address to listen to.", "address", "All addresses"},
204 {'k', "Check daemon configuration.", NULL, NULL},
205 {'p', "Port to listen. Can be from 1 to 65535.", "port_number", "19999"},
206 {'s', "Path to access host /proc and /sys when running in a container.", "PATH", NULL},
207 {'t', "The frequency in seconds, for data collection. \
208 Same as 'update every' config file option.", "seconds", "1"},
209 {'u', "System username to run as.", "username", "netdata"},
210 {'v', "Version of the program", NULL, NULL},
211 {'W', "vendor options.", "stacksize=<size>|unittest|debug_flag", NULL},
214 void help(int exitcode) {
221 int num_opts = sizeof(options) / sizeof(struct option_def);
225 // Compute maximum argument length
226 for( i = 0; i < num_opts; i++ ) {
227 if(options[i].arg_name) {
228 int len_arg = (int)strlen(options[i].arg_name);
229 if(len_arg > max_len_arg) max_len_arg = len_arg;
233 fprintf(stream, "SYNOPSIS: netdata [options]\n");
234 fprintf(stream, "\n");
235 fprintf(stream, "Options:\n");
237 // Output options description.
238 for( i = 0; i < num_opts; i++ ) {
239 fprintf(stream, " -%c %-*s %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
240 if(options[i].default_value) {
241 fprintf(stream, " Default: %s\n", options[i].default_value);
243 fprintf(stream, "\n");
251 // TODO: Remove this function with the nix major release.
252 void remove_option(int opt_index, int *argc, char **argv) {
254 // remove the options.
257 for(i = opt_index; i < *argc; i++) {
261 } while(argv[i][0] != '-' && opt_index >= *argc);
265 int main(int argc, char **argv)
267 int i, check_config = 0;
268 int config_loaded = 0;
270 size_t wanted_stacksize = 0, stacksize = 0;
273 // global initialization
276 // set the name for logging
277 program_name = "netdata";
279 // parse command line.
281 // parse depercated options
282 // TODO: Remove this block with the next major release.
286 if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
287 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
288 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
289 remove_option(i, &argc, argv);
291 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
293 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
294 remove_option(i, &argc, argv);
296 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
297 config_set("global", "host access prefix", argv[i+1]);
298 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
299 remove_option(i, &argc, argv);
301 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
302 config_set("global", "history", argv[i+1]);
303 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
304 remove_option(i, &argc, argv);
312 int num_opts = sizeof(options) / sizeof(struct option_def);
313 char optstring[(num_opts * 2) + 1];
316 for( i = 0; i < num_opts; i++ ) {
317 optstring[string_i] = options[i].val;
319 if(options[i].arg_name) {
320 optstring[string_i] = ':';
326 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
329 if(load_config(optarg, 1) != 1) {
330 error("Cannot load configuration file %s.", optarg);
334 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
345 config_set("global", "bind to", optarg);
352 strncpy(pidfile, optarg, FILENAME_MAX);
353 pidfile[FILENAME_MAX] = '\0';
356 config_set("global", "default port", optarg);
359 config_set("global", "host access prefix", optarg);
362 config_set("global", "update every", optarg);
365 config_set("global", "run as user", optarg);
368 // TODO: Outsource version to makefile which can compute version from git.
369 printf("netdata 1.2.1_master\n");
373 char* stacksize_string = "stacksize=";
374 char* debug_flags_string = "debug_flags=";
375 if(strcmp(optarg, "unittest") == 0) {
376 rrd_update_every = 1;
377 if(run_all_mockup_tests()) exit(1);
378 if(unit_test_storage()) exit(1);
379 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
381 } else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
382 optarg += strlen(stacksize_string);
383 config_set("global", "pthread stack size", optarg);
384 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
385 optarg += strlen(debug_flags_string);
386 config_set("global", "debug flags", optarg);
387 debug_flags = strtoull(optarg, NULL, 0);
398 if(!config_loaded) load_config(NULL, 0);
400 // prepare configuration environment variables for the plugins
401 setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1);
402 setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1);
403 setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1);
404 setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1);
405 setenv("NETDATA_LIB_DIR" , config_get("global", "lib directory" , VARLIB_DIR) , 1);
406 setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1);
407 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
408 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
410 // disable buffering for python plugins
411 setenv("PYTHONUNBUFFERED", "1", 1);
413 // avoid flood calls to stat(/etc/localtime)
414 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
415 setenv("TZ", ":/etc/localtime", 0);
418 char path[1024 + 1], *p = getenv("PATH");
419 if(!p) p = "/bin:/usr/bin";
420 snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
421 setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
424 // cd to /tmp to avoid any plugins writing files at random places
425 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
429 char *flags = config_get("global", "debug flags", "0x00000000");
430 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
432 debug_flags = strtoull(flags, NULL, 0);
433 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
435 if(debug_flags != 0) {
436 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
437 if(setrlimit(RLIMIT_CORE, &rl) != 0)
438 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
439 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
442 // --------------------------------------------------------------------
444 #ifdef MADV_MERGEABLE
445 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
447 #warning "Kernel memory deduplication (KSM) is not available"
450 // --------------------------------------------------------------------
452 global_host_prefix = config_get("global", "host access prefix", "");
453 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
455 // --------------------------------------------------------------------
457 stdout_filename = config_get("global", "debug log", LOG_DIR "/debug.log");
458 stderr_filename = config_get("global", "error log", LOG_DIR "/error.log");
459 stdaccess_filename = config_get("global", "access log", LOG_DIR "/access.log");
461 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
462 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
464 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
465 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
468 stdout_filename = stderr_filename = stdaccess_filename = "system";
469 error_log_throttle_period = 0;
470 error_log_errors_per_period = 0;
473 // --------------------------------------------------------------------
475 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
477 // --------------------------------------------------------------------
480 char hostnamebuf[HOSTNAME_MAX + 1];
481 if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
482 error("WARNING: Cannot get machine hostname.");
483 hostname = config_get("global", "hostname", hostnamebuf);
484 debug(D_OPTIONS, "hostname set to '%s'", hostname);
487 // --------------------------------------------------------------------
489 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
490 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
491 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
492 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
495 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
498 // --------------------------------------------------------------------
500 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
501 if(rrd_update_every < 1 || rrd_update_every > 600) {
502 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
503 rrd_update_every = UPDATE_EVERY;
505 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
507 // let the plugins know the min update_every
510 snprintfz(buf, 15, "%d", rrd_update_every);
511 setenv("NETDATA_UPDATE_EVERY", buf, 1);
514 // --------------------------------------------------------------------
516 // block signals while initializing threads.
517 // this causes the threads to block signals.
521 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
522 error("Could not block signals for threads");
525 // Catch signals which we want to use
527 sigemptyset(&sa.sa_mask);
528 sigaddset(&sa.sa_mask, SIGINT);
529 sigaddset(&sa.sa_mask, SIGTERM);
530 sa.sa_handler = sig_handler_exit;
532 if(sigaction(SIGINT, &sa, NULL) == -1) {
533 error("Failed to change signal handler for SIGINT");
535 if(sigaction(SIGTERM, &sa, NULL) == -1) {
536 error("Failed to change signal handler for SIGTERM");
539 sigemptyset(&sa.sa_mask);
540 sigaddset(&sa.sa_mask, SIGHUP);
541 sa.sa_handler = sig_handler_logrotate;
543 if(sigaction(SIGHUP, &sa, NULL) == -1) {
544 error("Failed to change signal handler for SIGHUP");
547 // save database on SIGUSR1
548 sigemptyset(&sa.sa_mask);
549 sigaddset(&sa.sa_mask, SIGUSR1);
550 sa.sa_handler = sig_handler_save;
551 if(sigaction(SIGUSR1, &sa, NULL) == -1) {
552 error("Failed to change signal handler for SIGUSR1");
555 // Ignore SIGPIPE completely.
556 // INFO: If we add signals here we have to unblock them
557 // at popen.c when running a external plugin.
558 sigemptyset(&sa.sa_mask);
559 sigaddset(&sa.sa_mask, SIGPIPE);
560 sa.sa_handler = SIG_IGN;
561 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
562 error("Failed to change signal handler for SIGPIPE");
565 // --------------------------------------------------------------------
567 i = pthread_attr_init(&attr);
569 fatal("pthread_attr_init() failed with code %d.", i);
571 i = pthread_attr_getstacksize(&attr, &stacksize);
573 fatal("pthread_attr_getstacksize() failed with code %d.", i);
575 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
577 wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
579 // --------------------------------------------------------------------
581 for (i = 0; static_threads[i].name != NULL ; i++) {
582 struct netdata_static_thread *st = &static_threads[i];
584 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
585 if(st->enabled && st->init_routine) st->init_routine();
588 // --------------------------------------------------------------------
590 // get the user we should run
591 // IMPORTANT: this is required before web_files_uid()
592 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
594 // IMPORTANT: these have to run once, while single threaded
595 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
598 // --------------------------------------------------------------------
600 create_listen_sockets();
603 // initialize the log files
604 open_all_log_files();
606 #ifdef NETDATA_INTERNAL_CHECKS
607 if(debug_flags != 0) {
608 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
609 if(setrlimit(RLIMIT_CORE, &rl) != 0)
610 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
611 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
613 #endif /* NETDATA_INTERNAL_CHECKS */
615 // fork, switch user, create pid file, set process priority
616 if(become_daemon(dont_fork, user) == -1)
617 fatal("Cannot demonize myself.");
619 info("NetData started on pid %d", getpid());
622 // ------------------------------------------------------------------------
623 // get default pthread stack size
625 if(stacksize < wanted_stacksize) {
626 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
628 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
630 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
633 // ------------------------------------------------------------------------
634 // initialize the registry
638 // ------------------------------------------------------------------------
639 // initialize health monitoring
646 // ------------------------------------------------------------------------
649 web_server_threading_selection();
651 for (i = 0; static_threads[i].name != NULL ; i++) {
652 struct netdata_static_thread *st = &static_threads[i];
655 st->thread = mallocz(sizeof(pthread_t));
657 info("Starting thread %s.", st->name);
659 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
660 error("failed to create new thread for %s.", st->name);
662 else if(pthread_detach(*st->thread))
663 error("Cannot request detach of newly created %s thread.", st->name);
665 else info("Not starting thread %s.", st->name);
668 // ------------------------------------------------------------------------
669 // block signals while initializing threads.
673 if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
674 error("Could not unblock signals for threads");
677 // Handle flags set in the signal handler.
681 info("Exit main loop of netdata.");
682 netdata_cleanup_and_exit(0);