12 #include <sys/types.h>
15 #include <sys/resource.h>
17 #include <sys/prctl.h>
22 #include "web_server.h"
24 #include "appconfig.h"
25 #include "web_client.h"
29 #include "unit_test.h"
31 #include "plugins_d.h"
32 #include "plugin_idlejitter.h"
33 #include "plugin_tc.h"
34 #include "plugin_checks.h"
35 #include "plugin_proc.h"
36 #include "plugin_nfacct.h"
41 extern void *cgroups_main(void *ptr);
45 void netdata_cleanup_and_exit(int ret)
51 // let it log a few more error messages
52 error_log_limit_reset();
55 if(ftruncate(pidfd, 0) != 0)
56 error("Cannot truncate pidfile '%s'.", pidfile);
63 if(unlink(pidfile) != 0)
64 error("Cannot unlink pidfile '%s'.", pidfile);
67 info("NetData exiting. Bye bye...");
71 struct netdata_static_thread {
81 void (*init_routine) (void);
82 void *(*start_routine) (void *);
85 struct netdata_static_thread static_threads[] = {
86 {"tc", "plugins", "tc", 1, NULL, NULL, tc_main},
87 {"idlejitter", "plugins", "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
88 {"proc", "plugins", "proc", 1, NULL, NULL, proc_main},
89 {"cgroups", "plugins", "cgroups", 1, NULL, NULL, cgroups_main},
91 #ifdef INTERNAL_PLUGIN_NFACCT
92 // nfacct requires root access
93 // so, we build it as an external plugin with setuid to root
94 {"nfacct", "plugins", "nfacct", 1, NULL, NULL, nfacct_main},
97 {"plugins.d", NULL, NULL, 1, NULL, NULL, pluginsd_main},
98 {"check", "plugins", "checks", 0, NULL, NULL, checks_main},
99 {"web", NULL, NULL, 1, NULL, NULL, socket_listen_main},
100 {NULL, NULL, NULL, 0, NULL, NULL, NULL}
103 int killpid(pid_t pid, int sig)
106 debug(D_EXIT, "Request to kill pid %d", pid);
109 if(kill(pid, 0) == -1) {
112 error("Request to kill pid %d, but it is not running.", pid);
116 error("Request to kill pid %d, but I do not have enough permissions.", pid);
120 error("Request to kill pid %d, but I received an error.", pid);
128 old = signal(sig, SIG_IGN);
130 error("Cannot overwrite signal handler for signal %d", sig);
134 ret = kill(pid, sig);
136 if(signal(sig, old) == SIG_ERR)
137 error("Cannot restore signal handler for signal %d", sig);
142 error("Cannot kill pid %d, but it is not running.", pid);
146 error("Cannot kill pid %d, but I do not have enough permissions.", pid);
150 error("Cannot kill pid %d, but I received an error.", pid);
163 struct web_client *w;
164 for(w = web_clients; w ; w = w->next) {
165 debug(D_EXIT, "Stopping web client %s", w->client_ip);
166 pthread_cancel(w->thread);
167 pthread_join(w->thread, NULL);
171 for (i = 0; static_threads[i].name != NULL ; i++) {
172 if(static_threads[i].thread) {
173 debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
174 pthread_cancel(*static_threads[i].thread);
175 pthread_join(*static_threads[i].thread, NULL);
176 static_threads[i].thread = NULL;
181 info("Killing tc-qos-helper procees");
182 if(killpid(tc_child_pid, SIGTERM) != -1)
183 waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
188 for(cd = pluginsd_root ; cd ; cd = cd->next) {
189 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
190 pthread_cancel(cd->thread);
191 pthread_join(cd->thread, NULL);
193 if(cd->pid && !cd->obsolete) {
194 debug(D_EXIT, "killing %s plugin process", cd->id);
195 if(killpid(cd->pid, SIGTERM) != -1)
196 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
200 // if, for any reason there is any child exited
202 waitid(P_PID, 0, &info, WEXITED|WNOHANG);
204 debug(D_EXIT, "All threads/childs stopped.");
208 int main(int argc, char **argv)
211 int config_loaded = 0;
213 size_t wanted_stacksize = 0, stacksize = 0;
216 // global initialization
219 // set the name for logging
220 program_name = "netdata";
222 // parse the arguments
223 for(i = 1; i < argc ; i++) {
224 if(strcmp(argv[i], "-c") == 0 && (i+1) < argc) {
225 if(load_config(argv[i+1], 1) != 1) {
226 error("Cannot load configuration file %s.", argv[i+1]);
230 debug(D_OPTIONS, "Configuration loaded from %s.", argv[i+1]);
235 else if(strcmp(argv[i], "-df") == 0 && (i+1) < argc) { config_set("global", "debug flags", argv[i+1]); debug_flags = strtoull(argv[i+1], NULL, 0); i++; }
236 else if(strcmp(argv[i], "-p") == 0 && (i+1) < argc) { config_set("global", "port", argv[i+1]); i++; }
237 else if(strcmp(argv[i], "-u") == 0 && (i+1) < argc) { config_set("global", "run as user", argv[i+1]); i++; }
238 else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) { config_set("global", "history", argv[i+1]); i++; }
239 else if(strcmp(argv[i], "-t") == 0 && (i+1) < argc) { config_set("global", "update every", argv[i+1]); i++; }
240 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) { config_set("global", "host access prefix", argv[i+1]); i++; }
241 else if(strcmp(argv[i], "-stacksize") == 0 && (i+1) < argc) { config_set("global", "pthread stack size", argv[i+1]); i++; }
242 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) dont_fork = 1;
243 else if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
245 strncpy(pidfile, argv[i], FILENAME_MAX);
246 pidfile[FILENAME_MAX] = '\0';
248 else if(strcmp(argv[i], "--unittest") == 0) {
249 rrd_update_every = 1;
250 if(run_all_mockup_tests()) exit(1);
251 if(unit_test_storage()) exit(1);
252 fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
256 fprintf(stderr, "Cannot understand option '%s'.\n", argv[i]);
257 fprintf(stderr, "\nUSAGE: %s [-d] [-l LINES_TO_SAVE] [-u UPDATE_TIMER] [-p LISTEN_PORT] [-df debug flags].\n\n", argv[0]);
258 fprintf(stderr, " -c CONFIG FILE the configuration file to load. Default: %s.\n", CONFIG_DIR "/" CONFIG_FILENAME);
259 fprintf(stderr, " -l LINES_TO_SAVE can be from 5 to %d lines in JSON data. Default: %d.\n", RRD_HISTORY_ENTRIES_MAX, RRD_DEFAULT_HISTORY_ENTRIES);
260 fprintf(stderr, " -t UPDATE_TIMER can be from 1 to %d seconds. Default: %d.\n", UPDATE_EVERY_MAX, UPDATE_EVERY);
261 fprintf(stderr, " -p LISTEN_PORT can be from 1 to %d. Default: %d.\n", 65535, LISTEN_PORT);
262 fprintf(stderr, " -u USERNAME can be any system username to run as. Default: none.\n");
263 fprintf(stderr, " -ch path to access host /proc and /sys when running in a container. Default: empty.\n");
264 fprintf(stderr, " -nd or -nodeamon to disable forking in the background. Default: unset.\n");
265 fprintf(stderr, " -df FLAGS debug options. Default: 0x%08llx.\n", debug_flags);
266 fprintf(stderr, " -stacksize BYTES to overwrite the pthread stack size.\n");
267 fprintf(stderr, " -pidfile FILENAME to save a pid while running.\n");
272 if(!config_loaded) load_config(NULL, 0);
274 // prepare configuration environment variables for the plugins
275 setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1);
276 setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1);
277 setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1);
278 setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1);
279 setenv("NETDATA_LIB_DIR" , config_get("global", "lib directory" , VARLIB_DIR) , 1);
280 setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1);
281 setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1);
282 setenv("HOME" , config_get("global", "home directory" , CACHE_DIR) , 1);
284 // avoid extended to stat(/etc/localtime)
285 // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
286 setenv("TZ", ":/etc/localtime", 0);
288 // cd to /tmp to avoid any plugins writing files at random places
289 if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
291 char *input_log_file = NULL;
292 char *output_log_file = NULL;
293 char *error_log_file = NULL;
294 char *access_log_file = NULL;
299 // --------------------------------------------------------------------
301 sprintf(buffer, "0x%08llx", 0ULL);
302 char *flags = config_get("global", "debug flags", buffer);
303 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
305 debug_flags = strtoull(flags, NULL, 0);
306 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
308 if(debug_flags != 0) {
309 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
310 if(setrlimit(RLIMIT_CORE, &rl) != 0)
311 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
312 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
315 // --------------------------------------------------------------------
317 #ifdef MADV_MERGEABLE
318 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
320 #warning "Kernel memory deduplication (KSM) is not available"
323 // --------------------------------------------------------------------
326 global_host_prefix = config_get("global", "host access prefix", "");
327 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
329 // --------------------------------------------------------------------
331 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
332 if(strcmp(output_log_file, "syslog") == 0) {
333 output_log_syslog = 1;
334 output_log_file = NULL;
336 else if(strcmp(output_log_file, "none") == 0) {
337 output_log_syslog = 0;
338 output_log_file = NULL;
340 else output_log_syslog = 0;
342 // --------------------------------------------------------------------
344 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
345 if(strcmp(error_log_file, "syslog") == 0) {
346 error_log_syslog = 1;
347 error_log_file = NULL;
349 else if(strcmp(error_log_file, "none") == 0) {
350 error_log_syslog = 0;
351 error_log_file = NULL;
352 // optimization - do not even generate debug log entries
354 else error_log_syslog = 0;
356 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
357 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period" , ""), 1);
359 error_log_errors_per_period = config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
360 setenv("NETDATA_ERRORS_PER_PERIOD" , config_get("global", "errors to trigger flood protection", ""), 1);
362 // --------------------------------------------------------------------
364 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
365 if(strcmp(access_log_file, "syslog") == 0) {
366 access_log_syslog = 1;
367 access_log_file = NULL;
369 else if(strcmp(access_log_file, "none") == 0) {
370 access_log_syslog = 0;
371 access_log_file = NULL;
373 else access_log_syslog = 0;
375 // --------------------------------------------------------------------
377 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
379 // --------------------------------------------------------------------
381 if(gethostname(buffer, HOSTNAME_MAX) == -1)
382 error("WARNING: Cannot get machine hostname.");
383 hostname = config_get("global", "hostname", buffer);
384 debug(D_OPTIONS, "hostname set to '%s'", hostname);
386 // --------------------------------------------------------------------
388 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
389 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
390 info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
391 rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
394 debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
397 // --------------------------------------------------------------------
399 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
400 if(rrd_update_every < 1 || rrd_update_every > 600) {
401 info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
402 rrd_update_every = UPDATE_EVERY;
404 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
406 // let the plugins know the min update_every
409 snprintf(buf, 50, "%d", rrd_update_every);
410 setenv("NETDATA_UPDATE_EVERY", buf, 1);
413 // --------------------------------------------------------------------
415 i = pthread_attr_init(&attr);
417 fatal("pthread_attr_init() failed with code %d.", i);
419 i = pthread_attr_getstacksize(&attr, &stacksize);
421 fatal("pthread_attr_getstacksize() failed with code %d.", i);
423 debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
425 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
427 // --------------------------------------------------------------------
429 for (i = 0; static_threads[i].name != NULL ; i++) {
430 struct netdata_static_thread *st = &static_threads[i];
432 if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
433 if(st->enabled && st->init_routine) st->init_routine();
436 // --------------------------------------------------------------------
438 // get the user we should run
439 // IMPORTANT: this is required before web_files_uid()
440 user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:"");
442 // IMPORTANT: these have to run once, while single threaded
443 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
446 // --------------------------------------------------------------------
448 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
450 listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
451 if(listen_port < 1 || listen_port > 65535) {
452 info("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
453 listen_port = LISTEN_PORT;
455 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
458 char *ipv = config_get("global", "ip version", "any");
459 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
460 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
461 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
462 else info("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
464 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
466 listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
467 if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port);
470 if(listen_fd < 0) fatal("Cannot listen socket.");
473 // never become a problem
474 if(nice(20) == -1) error("Cannot lower my CPU priority.");
476 if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1) {
477 fatal("Cannot demonize myself.");
481 if(debug_flags != 0) {
482 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
483 if(setrlimit(RLIMIT_CORE, &rl) != 0)
484 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
486 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
489 if(output_log_syslog || error_log_syslog || access_log_syslog)
490 openlog("netdata", LOG_PID, LOG_DAEMON);
492 info("NetData started on pid %d", getpid());
496 for (i = 1 ; i < 65 ;i++) {
498 case SIGKILL: // not catchable
499 case SIGSTOP: // not catchable
509 signal(i, sig_handler);
514 // ------------------------------------------------------------------------
515 // get default pthread stack size
517 if(stacksize < wanted_stacksize) {
518 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
520 fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
522 info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
525 // --------------------------------------------------------------------
526 // initialize the registry
531 // ------------------------------------------------------------------------
534 for (i = 0; static_threads[i].name != NULL ; i++) {
535 struct netdata_static_thread *st = &static_threads[i];
538 st->thread = malloc(sizeof(pthread_t));
540 fatal("Cannot allocate pthread_t memory");
542 info("Starting thread %s.", st->name);
544 if(pthread_create(st->thread, &attr, st->start_routine, NULL))
545 error("failed to create new thread for %s.", st->name);
547 else if(pthread_detach(*st->thread))
548 error("Cannot request detach of newly created %s thread.", st->name);
550 else info("Not starting thread %s.", st->name);
553 // for future use - the main thread
555 if(netdata_exit != 0) {
558 if(netdata_exit > 5) {
559 netdata_cleanup_and_exit(0);