main.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "common.h"
  3. #include "buildinfo.h"
  4. int netdata_zero_metrics_enabled;
  5. int netdata_anonymous_statistics_enabled;
  6. struct config netdata_config = {
  7. .first_section = NULL,
  8. .last_section = NULL,
  9. .mutex = NETDATA_MUTEX_INITIALIZER,
  10. .index = {
  11. .avl_tree = {
  12. .root = NULL,
  13. .compar = appconfig_section_compare
  14. },
  15. .rwlock = AVL_LOCK_INITIALIZER
  16. }
  17. };
  18. void netdata_cleanup_and_exit(int ret) {
  19. // enabling this, is wrong
  20. // because the threads will be cancelled while cleaning up
  21. // netdata_exit = 1;
  22. error_log_limit_unlimited();
  23. info("EXIT: netdata prepares to exit with code %d...", ret);
  24. send_statistics("EXIT", ret?"ERROR":"OK","-");
  25. analytics_free_data();
  26. char agent_crash_file[FILENAME_MAX + 1];
  27. char agent_incomplete_shutdown_file[FILENAME_MAX + 1];
  28. snprintfz(agent_crash_file, FILENAME_MAX, "%s/.agent_crash", netdata_configured_varlib_dir);
  29. snprintfz(agent_incomplete_shutdown_file, FILENAME_MAX, "%s/.agent_incomplete_shutdown", netdata_configured_varlib_dir);
  30. (void) rename(agent_crash_file, agent_incomplete_shutdown_file);
  31. // cleanup/save the database and exit
  32. info("EXIT: cleaning up the database...");
  33. rrdhost_cleanup_all();
  34. if(!ret) {
  35. // exit cleanly
  36. // stop everything
  37. info("EXIT: stopping static threads...");
  38. cancel_main_threads();
  39. // free the database
  40. info("EXIT: freeing database memory...");
  41. #ifdef ENABLE_DBENGINE
  42. rrdeng_prepare_exit(&multidb_ctx);
  43. #endif
  44. rrdhost_free_all();
  45. #ifdef ENABLE_DBENGINE
  46. rrdeng_exit(&multidb_ctx);
  47. #endif
  48. }
  49. sql_close_database();
  50. // unlink the pid
  51. if(pidfile[0]) {
  52. info("EXIT: removing netdata PID file '%s'...", pidfile);
  53. if(unlink(pidfile) != 0)
  54. error("EXIT: cannot unlink pidfile '%s'.", pidfile);
  55. }
  56. #ifdef ENABLE_HTTPS
  57. security_clean_openssl();
  58. #endif
  59. info("EXIT: all done - netdata is now exiting - bye bye...");
  60. (void) unlink(agent_incomplete_shutdown_file);
  61. exit(ret);
  62. }
  63. struct netdata_static_thread static_threads[] = {
  64. NETDATA_PLUGIN_HOOK_GLOBAL_STATISTICS
  65. NETDATA_PLUGIN_HOOK_CHECKS
  66. NETDATA_PLUGIN_HOOK_FREEBSD
  67. NETDATA_PLUGIN_HOOK_MACOS
  68. // linux internal plugins
  69. NETDATA_PLUGIN_HOOK_LINUX_PROC
  70. NETDATA_PLUGIN_HOOK_LINUX_DISKSPACE
  71. NETDATA_PLUGIN_HOOK_LINUX_TIMEX
  72. NETDATA_PLUGIN_HOOK_LINUX_CGROUPS
  73. NETDATA_PLUGIN_HOOK_LINUX_TC
  74. NETDATA_PLUGIN_HOOK_IDLEJITTER
  75. NETDATA_PLUGIN_HOOK_STATSD
  76. #if defined(ENABLE_ACLK) || defined(ACLK_NG)
  77. NETDATA_ACLK_HOOK
  78. #endif
  79. // common plugins for all systems
  80. {"BACKENDS", NULL, NULL, 1, NULL, NULL, backends_main},
  81. {"EXPORTING", NULL, NULL, 1, NULL, NULL, exporting_main},
  82. {"WEB_SERVER[static1]", NULL, NULL, 0, NULL, NULL, socket_listen_main_static_threaded},
  83. {"STREAM", NULL, NULL, 0, NULL, NULL, rrdpush_sender_thread},
  84. NETDATA_PLUGIN_HOOK_PLUGINSD
  85. NETDATA_PLUGIN_HOOK_HEALTH
  86. NETDATA_PLUGIN_HOOK_ANALYTICS
  87. {NULL, NULL, NULL, 0, NULL, NULL, NULL}
  88. };
  89. void web_server_threading_selection(void) {
  90. web_server_mode = web_server_mode_id(config_get(CONFIG_SECTION_WEB, "mode", web_server_mode_name(web_server_mode)));
  91. int static_threaded = (web_server_mode == WEB_SERVER_MODE_STATIC_THREADED);
  92. int i;
  93. for (i = 0; static_threads[i].name; i++) {
  94. if (static_threads[i].start_routine == socket_listen_main_static_threaded)
  95. static_threads[i].enabled = static_threaded;
  96. }
  97. }
  98. int make_dns_decision(const char *section_name, const char *config_name, const char *default_value, SIMPLE_PATTERN *p)
  99. {
  100. char *value = config_get(section_name,config_name,default_value);
  101. if(!strcmp("yes",value))
  102. return 1;
  103. if(!strcmp("no",value))
  104. return 0;
  105. if(strcmp("heuristic",value))
  106. error("Invalid configuration option '%s' for '%s'/'%s'. Valid options are 'yes', 'no' and 'heuristic'. Proceeding with 'heuristic'",
  107. value, section_name, config_name);
  108. return simple_pattern_is_potential_name(p);
  109. }
  110. void web_server_config_options(void)
  111. {
  112. web_client_timeout =
  113. (int)config_get_number(CONFIG_SECTION_WEB, "disconnect idle clients after seconds", web_client_timeout);
  114. web_client_first_request_timeout =
  115. (int)config_get_number(CONFIG_SECTION_WEB, "timeout for first request", web_client_first_request_timeout);
  116. web_client_streaming_rate_t =
  117. config_get_number(CONFIG_SECTION_WEB, "accept a streaming request every seconds", web_client_streaming_rate_t);
  118. respect_web_browser_do_not_track_policy =
  119. config_get_boolean(CONFIG_SECTION_WEB, "respect do not track policy", respect_web_browser_do_not_track_policy);
  120. web_x_frame_options = config_get(CONFIG_SECTION_WEB, "x-frame-options response header", "");
  121. if(!*web_x_frame_options)
  122. web_x_frame_options = NULL;
  123. web_allow_connections_from =
  124. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow connections from", "localhost *"),
  125. NULL, SIMPLE_PATTERN_EXACT);
  126. web_allow_connections_dns =
  127. make_dns_decision(CONFIG_SECTION_WEB, "allow connections by dns", "heuristic", web_allow_connections_from);
  128. web_allow_dashboard_from =
  129. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow dashboard from", "localhost *"),
  130. NULL, SIMPLE_PATTERN_EXACT);
  131. web_allow_dashboard_dns =
  132. make_dns_decision(CONFIG_SECTION_WEB, "allow dashboard by dns", "heuristic", web_allow_dashboard_from);
  133. web_allow_badges_from =
  134. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow badges from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  135. web_allow_badges_dns =
  136. make_dns_decision(CONFIG_SECTION_WEB, "allow badges by dns", "heuristic", web_allow_badges_from);
  137. web_allow_registry_from =
  138. simple_pattern_create(config_get(CONFIG_SECTION_REGISTRY, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  139. web_allow_registry_dns = make_dns_decision(CONFIG_SECTION_REGISTRY, "allow by dns", "heuristic",
  140. web_allow_registry_from);
  141. web_allow_streaming_from = simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow streaming from", "*"),
  142. NULL, SIMPLE_PATTERN_EXACT);
  143. web_allow_streaming_dns = make_dns_decision(CONFIG_SECTION_WEB, "allow streaming by dns", "heuristic",
  144. web_allow_streaming_from);
  145. // Note the default is not heuristic, the wildcards could match DNS but the intent is ip-addresses.
  146. web_allow_netdataconf_from = simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow netdata.conf from",
  147. "localhost fd* 10.* 192.168.* 172.16.* 172.17.* 172.18.*"
  148. " 172.19.* 172.20.* 172.21.* 172.22.* 172.23.* 172.24.*"
  149. " 172.25.* 172.26.* 172.27.* 172.28.* 172.29.* 172.30.*"
  150. " 172.31.* UNKNOWN"), NULL, SIMPLE_PATTERN_EXACT);
  151. web_allow_netdataconf_dns =
  152. make_dns_decision(CONFIG_SECTION_WEB, "allow netdata.conf by dns", "no", web_allow_netdataconf_from);
  153. web_allow_mgmt_from =
  154. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow management from", "localhost"),
  155. NULL, SIMPLE_PATTERN_EXACT);
  156. web_allow_mgmt_dns =
  157. make_dns_decision(CONFIG_SECTION_WEB, "allow management by dns","heuristic",web_allow_mgmt_from);
  158. #ifdef NETDATA_WITH_ZLIB
  159. web_enable_gzip = config_get_boolean(CONFIG_SECTION_WEB, "enable gzip compression", web_enable_gzip);
  160. char *s = config_get(CONFIG_SECTION_WEB, "gzip compression strategy", "default");
  161. if(!strcmp(s, "default"))
  162. web_gzip_strategy = Z_DEFAULT_STRATEGY;
  163. else if(!strcmp(s, "filtered"))
  164. web_gzip_strategy = Z_FILTERED;
  165. else if(!strcmp(s, "huffman only"))
  166. web_gzip_strategy = Z_HUFFMAN_ONLY;
  167. else if(!strcmp(s, "rle"))
  168. web_gzip_strategy = Z_RLE;
  169. else if(!strcmp(s, "fixed"))
  170. web_gzip_strategy = Z_FIXED;
  171. else {
  172. error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
  173. web_gzip_strategy = Z_DEFAULT_STRATEGY;
  174. }
  175. web_gzip_level = (int)config_get_number(CONFIG_SECTION_WEB, "gzip compression level", 3);
  176. if(web_gzip_level < 1) {
  177. error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
  178. web_gzip_level = 1;
  179. }
  180. else if(web_gzip_level > 9) {
  181. error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
  182. web_gzip_level = 9;
  183. }
  184. #endif /* NETDATA_WITH_ZLIB */
  185. }
  186. // killpid kills pid with SIGTERM.
  187. int killpid(pid_t pid) {
  188. int ret;
  189. debug(D_EXIT, "Request to kill pid %d", pid);
  190. errno = 0;
  191. ret = kill(pid, SIGTERM);
  192. if (ret == -1) {
  193. switch(errno) {
  194. case ESRCH:
  195. // We wanted the process to exit so just let the caller handle.
  196. return ret;
  197. case EPERM:
  198. error("Cannot kill pid %d, but I do not have enough permissions.", pid);
  199. break;
  200. default:
  201. error("Cannot kill pid %d, but I received an error.", pid);
  202. break;
  203. }
  204. }
  205. return ret;
  206. }
  207. void cancel_main_threads() {
  208. error_log_limit_unlimited();
  209. int i, found = 0;
  210. usec_t max = 5 * USEC_PER_SEC, step = 100000;
  211. for (i = 0; static_threads[i].name != NULL ; i++) {
  212. if(static_threads[i].enabled == NETDATA_MAIN_THREAD_RUNNING) {
  213. info("EXIT: Stopping main thread: %s", static_threads[i].name);
  214. netdata_thread_cancel(*static_threads[i].thread);
  215. found++;
  216. }
  217. }
  218. netdata_exit = 1;
  219. while(found && max > 0) {
  220. max -= step;
  221. info("Waiting %d threads to finish...", found);
  222. sleep_usec(step);
  223. found = 0;
  224. for (i = 0; static_threads[i].name != NULL ; i++) {
  225. if (static_threads[i].enabled != NETDATA_MAIN_THREAD_EXITED)
  226. found++;
  227. }
  228. }
  229. if(found) {
  230. for (i = 0; static_threads[i].name != NULL ; i++) {
  231. if (static_threads[i].enabled != NETDATA_MAIN_THREAD_EXITED)
  232. error("Main thread %s takes too long to exit. Giving up...", static_threads[i].name);
  233. }
  234. }
  235. else
  236. info("All threads finished.");
  237. }
  238. struct option_def option_definitions[] = {
  239. // opt description arg name default value
  240. { 'c', "Configuration file to load.", "filename", CONFIG_DIR "/" CONFIG_FILENAME},
  241. { 'D', "Do not fork. Run in the foreground.", NULL, "run in the background"},
  242. { 'd', "Fork. Run in the background.", NULL, "run in the background"},
  243. { 'h', "Display this help message.", NULL, NULL},
  244. { 'P', "File to save a pid while running.", "filename", "do not save pid to a file"},
  245. { 'i', "The IP address to listen to.", "IP", "all IP addresses IPv4 and IPv6"},
  246. { 'p', "API/Web port to use.", "port", "19999"},
  247. { 's', "Prefix for /proc and /sys (for containers).", "path", "no prefix"},
  248. { 't', "The internal clock of netdata.", "seconds", "1"},
  249. { 'u', "Run as user.", "username", "netdata"},
  250. { 'v', "Print netdata version and exit.", NULL, NULL},
  251. { 'V', "Print netdata version and exit.", NULL, NULL},
  252. { 'W', "See Advanced options below.", "options", NULL},
  253. };
  254. int help(int exitcode) {
  255. FILE *stream;
  256. if(exitcode == 0)
  257. stream = stdout;
  258. else
  259. stream = stderr;
  260. int num_opts = sizeof(option_definitions) / sizeof(struct option_def);
  261. int i;
  262. int max_len_arg = 0;
  263. // Compute maximum argument length
  264. for( i = 0; i < num_opts; i++ ) {
  265. if(option_definitions[i].arg_name) {
  266. int len_arg = (int)strlen(option_definitions[i].arg_name);
  267. if(len_arg > max_len_arg) max_len_arg = len_arg;
  268. }
  269. }
  270. if(max_len_arg > 30) max_len_arg = 30;
  271. if(max_len_arg < 20) max_len_arg = 20;
  272. fprintf(stream, "%s", "\n"
  273. " ^\n"
  274. " |.-. .-. .-. .-. . netdata \n"
  275. " | '-' '-' '-' '-' real-time performance monitoring, done right! \n"
  276. " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
  277. "\n"
  278. " Copyright (C) 2016-2020, Netdata, Inc. <info@netdata.cloud>\n"
  279. " Released under GNU General Public License v3 or later.\n"
  280. " All rights reserved.\n"
  281. "\n"
  282. " Home Page : https://netdata.cloud\n"
  283. " Source Code: https://github.com/netdata/netdata\n"
  284. " Docs : https://learn.netdata.cloud\n"
  285. " Support : https://github.com/netdata/netdata/issues\n"
  286. " License : https://github.com/netdata/netdata/blob/master/LICENSE.md\n"
  287. "\n"
  288. " Twitter : https://twitter.com/linuxnetdata\n"
  289. " Facebook : https://www.facebook.com/linuxnetdata/\n"
  290. "\n"
  291. "\n"
  292. );
  293. fprintf(stream, " SYNOPSIS: netdata [options]\n");
  294. fprintf(stream, "\n");
  295. fprintf(stream, " Options:\n\n");
  296. // Output options description.
  297. for( i = 0; i < num_opts; i++ ) {
  298. fprintf(stream, " -%c %-*s %s", option_definitions[i].val, max_len_arg, option_definitions[i].arg_name ? option_definitions[i].arg_name : "", option_definitions[i].description);
  299. if(option_definitions[i].default_value) {
  300. fprintf(stream, "\n %c %-*s Default: %s\n", ' ', max_len_arg, "", option_definitions[i].default_value);
  301. } else {
  302. fprintf(stream, "\n");
  303. }
  304. fprintf(stream, "\n");
  305. }
  306. fprintf(stream, "\n Advanced options:\n\n"
  307. " -W stacksize=N Set the stacksize (in bytes).\n\n"
  308. " -W debug_flags=N Set runtime tracing to debug.log.\n\n"
  309. " -W unittest Run internal unittests and exit.\n\n"
  310. #ifdef ENABLE_DBENGINE
  311. " -W createdataset=N Create a DB engine dataset of N seconds and exit.\n\n"
  312. " -W stresstest=A,B,C,D,E,F\n"
  313. " Run a DB engine stress test for A seconds,\n"
  314. " with B writers and C readers, with a ramp up\n"
  315. " time of D seconds for writers, a page cache\n"
  316. " size of E MiB, an optional disk space limit"
  317. " of F MiB and exit.\n\n"
  318. #endif
  319. " -W set section option value\n"
  320. " set netdata.conf option from the command line.\n\n"
  321. " -W simple-pattern pattern string\n"
  322. " Check if string matches pattern and exit.\n\n"
  323. " -W \"claim -token=TOKEN -rooms=ROOM1,ROOM2\"\n"
  324. " Claim the agent to the workspace rooms pointed to by TOKEN and ROOM*.\n\n"
  325. );
  326. fprintf(stream, "\n Signals netdata handles:\n\n"
  327. " - HUP Close and reopen log files.\n"
  328. " - USR1 Save internal DB to disk.\n"
  329. " - USR2 Reload health configuration.\n"
  330. "\n"
  331. );
  332. fflush(stream);
  333. return exitcode;
  334. }
  335. #ifdef ENABLE_HTTPS
  336. static void security_init(){
  337. char filename[FILENAME_MAX + 1];
  338. snprintfz(filename, FILENAME_MAX, "%s/ssl/key.pem",netdata_configured_user_config_dir);
  339. security_key = config_get(CONFIG_SECTION_WEB, "ssl key", filename);
  340. snprintfz(filename, FILENAME_MAX, "%s/ssl/cert.pem",netdata_configured_user_config_dir);
  341. security_cert = config_get(CONFIG_SECTION_WEB, "ssl certificate", filename);
  342. tls_version = config_get(CONFIG_SECTION_WEB, "tls version", "1.3");
  343. tls_ciphers = config_get(CONFIG_SECTION_WEB, "tls ciphers", "none");
  344. security_openssl_library();
  345. }
  346. #endif
  347. static void log_init(void) {
  348. char filename[FILENAME_MAX + 1];
  349. snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);
  350. stdout_filename = config_get(CONFIG_SECTION_GLOBAL, "debug log", filename);
  351. snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);
  352. stderr_filename = config_get(CONFIG_SECTION_GLOBAL, "error log", filename);
  353. snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);
  354. stdaccess_filename = config_get(CONFIG_SECTION_GLOBAL, "access log", filename);
  355. char deffacility[8];
  356. snprintfz(deffacility,7,"%s","daemon");
  357. facility_log = config_get(CONFIG_SECTION_GLOBAL, "facility log", deffacility);
  358. error_log_throttle_period = config_get_number(CONFIG_SECTION_GLOBAL, "errors flood protection period", error_log_throttle_period);
  359. error_log_errors_per_period = (unsigned long)config_get_number(CONFIG_SECTION_GLOBAL, "errors to trigger flood protection", (long long int)error_log_errors_per_period);
  360. error_log_errors_per_period_backup = error_log_errors_per_period;
  361. setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get(CONFIG_SECTION_GLOBAL, "errors flood protection period" , ""), 1);
  362. setenv("NETDATA_ERRORS_PER_PERIOD", config_get(CONFIG_SECTION_GLOBAL, "errors to trigger flood protection", ""), 1);
  363. }
  364. char *initialize_lock_directory_path(char *prefix)
  365. {
  366. char filename[FILENAME_MAX + 1];
  367. snprintfz(filename, FILENAME_MAX, "%s/lock", prefix);
  368. return config_get(CONFIG_SECTION_GLOBAL, "lock directory", filename);
  369. }
  370. static void backwards_compatible_config() {
  371. // move [global] options to the [web] section
  372. config_move(CONFIG_SECTION_GLOBAL, "http port listen backlog",
  373. CONFIG_SECTION_WEB, "listen backlog");
  374. config_move(CONFIG_SECTION_GLOBAL, "bind socket to IP",
  375. CONFIG_SECTION_WEB, "bind to");
  376. config_move(CONFIG_SECTION_GLOBAL, "bind to",
  377. CONFIG_SECTION_WEB, "bind to");
  378. config_move(CONFIG_SECTION_GLOBAL, "port",
  379. CONFIG_SECTION_WEB, "default port");
  380. config_move(CONFIG_SECTION_GLOBAL, "default port",
  381. CONFIG_SECTION_WEB, "default port");
  382. config_move(CONFIG_SECTION_GLOBAL, "disconnect idle web clients after seconds",
  383. CONFIG_SECTION_WEB, "disconnect idle clients after seconds");
  384. config_move(CONFIG_SECTION_GLOBAL, "respect web browser do not track policy",
  385. CONFIG_SECTION_WEB, "respect do not track policy");
  386. config_move(CONFIG_SECTION_GLOBAL, "web x-frame-options header",
  387. CONFIG_SECTION_WEB, "x-frame-options response header");
  388. config_move(CONFIG_SECTION_GLOBAL, "enable web responses gzip compression",
  389. CONFIG_SECTION_WEB, "enable gzip compression");
  390. config_move(CONFIG_SECTION_GLOBAL, "web compression strategy",
  391. CONFIG_SECTION_WEB, "gzip compression strategy");
  392. config_move(CONFIG_SECTION_GLOBAL, "web compression level",
  393. CONFIG_SECTION_WEB, "gzip compression level");
  394. config_move(CONFIG_SECTION_GLOBAL, "web files owner",
  395. CONFIG_SECTION_WEB, "web files owner");
  396. config_move(CONFIG_SECTION_GLOBAL, "web files group",
  397. CONFIG_SECTION_WEB, "web files group");
  398. config_move(CONFIG_SECTION_BACKEND, "opentsdb host tags",
  399. CONFIG_SECTION_BACKEND, "host tags");
  400. }
  401. static void get_netdata_configured_variables() {
  402. backwards_compatible_config();
  403. // ------------------------------------------------------------------------
  404. // get the hostname
  405. char buf[HOSTNAME_MAX + 1];
  406. if(gethostname(buf, HOSTNAME_MAX) == -1){
  407. error("Cannot get machine hostname.");
  408. }
  409. netdata_configured_hostname = config_get(CONFIG_SECTION_GLOBAL, "hostname", buf);
  410. debug(D_OPTIONS, "hostname set to '%s'", netdata_configured_hostname);
  411. // ------------------------------------------------------------------------
  412. // get default database size
  413. default_rrd_history_entries = (int) config_get_number(CONFIG_SECTION_GLOBAL, "history", align_entries_to_pagesize(default_rrd_memory_mode, RRD_DEFAULT_HISTORY_ENTRIES));
  414. long h = align_entries_to_pagesize(default_rrd_memory_mode, default_rrd_history_entries);
  415. if(h != default_rrd_history_entries) {
  416. config_set_number(CONFIG_SECTION_GLOBAL, "history", h);
  417. default_rrd_history_entries = (int)h;
  418. }
  419. if(default_rrd_history_entries < 5 || default_rrd_history_entries > RRD_HISTORY_ENTRIES_MAX) {
  420. error("Invalid history entries %d given. Defaulting to %d.", default_rrd_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
  421. default_rrd_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
  422. }
  423. // ------------------------------------------------------------------------
  424. // get default database update frequency
  425. default_rrd_update_every = (int) config_get_number(CONFIG_SECTION_GLOBAL, "update every", UPDATE_EVERY);
  426. if(default_rrd_update_every < 1 || default_rrd_update_every > 600) {
  427. error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", default_rrd_update_every, UPDATE_EVERY_MAX);
  428. default_rrd_update_every = UPDATE_EVERY;
  429. }
  430. // ------------------------------------------------------------------------
  431. // get system paths
  432. netdata_configured_user_config_dir = config_get(CONFIG_SECTION_GLOBAL, "config directory", netdata_configured_user_config_dir);
  433. netdata_configured_stock_config_dir = config_get(CONFIG_SECTION_GLOBAL, "stock config directory", netdata_configured_stock_config_dir);
  434. netdata_configured_log_dir = config_get(CONFIG_SECTION_GLOBAL, "log directory", netdata_configured_log_dir);
  435. netdata_configured_web_dir = config_get(CONFIG_SECTION_GLOBAL, "web files directory", netdata_configured_web_dir);
  436. netdata_configured_cache_dir = config_get(CONFIG_SECTION_GLOBAL, "cache directory", netdata_configured_cache_dir);
  437. netdata_configured_varlib_dir = config_get(CONFIG_SECTION_GLOBAL, "lib directory", netdata_configured_varlib_dir);
  438. char *env_home=getenv("HOME");
  439. netdata_configured_home_dir = config_get(CONFIG_SECTION_GLOBAL, "home directory", env_home?env_home:netdata_configured_home_dir);
  440. netdata_configured_lock_dir = initialize_lock_directory_path(netdata_configured_varlib_dir);
  441. {
  442. pluginsd_initialize_plugin_directories();
  443. netdata_configured_primary_plugins_dir = plugin_directories[PLUGINSD_STOCK_PLUGINS_DIRECTORY_PATH];
  444. }
  445. // ------------------------------------------------------------------------
  446. // get default memory mode for the database
  447. default_rrd_memory_mode = rrd_memory_mode_id(config_get(CONFIG_SECTION_GLOBAL, "memory mode", rrd_memory_mode_name(default_rrd_memory_mode)));
  448. #ifdef ENABLE_DBENGINE
  449. // ------------------------------------------------------------------------
  450. // get default Database Engine page cache size in MiB
  451. default_rrdeng_page_cache_mb = (int) config_get_number(CONFIG_SECTION_GLOBAL, "page cache size", default_rrdeng_page_cache_mb);
  452. if(default_rrdeng_page_cache_mb < RRDENG_MIN_PAGE_CACHE_SIZE_MB) {
  453. error("Invalid page cache size %d given. Defaulting to %d.", default_rrdeng_page_cache_mb, RRDENG_MIN_PAGE_CACHE_SIZE_MB);
  454. default_rrdeng_page_cache_mb = RRDENG_MIN_PAGE_CACHE_SIZE_MB;
  455. }
  456. // ------------------------------------------------------------------------
  457. // get default Database Engine disk space quota in MiB
  458. default_rrdeng_disk_quota_mb = (int) config_get_number(CONFIG_SECTION_GLOBAL, "dbengine disk space", default_rrdeng_disk_quota_mb);
  459. if(default_rrdeng_disk_quota_mb < RRDENG_MIN_DISK_SPACE_MB) {
  460. error("Invalid dbengine disk space %d given. Defaulting to %d.", default_rrdeng_disk_quota_mb, RRDENG_MIN_DISK_SPACE_MB);
  461. default_rrdeng_disk_quota_mb = RRDENG_MIN_DISK_SPACE_MB;
  462. }
  463. default_multidb_disk_quota_mb = (int) config_get_number(CONFIG_SECTION_GLOBAL, "dbengine multihost disk space", compute_multidb_diskspace());
  464. if(default_multidb_disk_quota_mb < RRDENG_MIN_DISK_SPACE_MB) {
  465. error("Invalid multidb disk space %d given. Defaulting to %d.", default_multidb_disk_quota_mb, default_rrdeng_disk_quota_mb);
  466. default_multidb_disk_quota_mb = default_rrdeng_disk_quota_mb;
  467. }
  468. #else
  469. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE) {
  470. error_report("RRD_MEMORY_MODE_DBENGINE is not supported in this platform. The agent will use memory mode ram instead.");
  471. default_rrd_memory_mode = RRD_MEMORY_MODE_RAM;
  472. }
  473. #endif
  474. // ------------------------------------------------------------------------
  475. netdata_configured_host_prefix = config_get(CONFIG_SECTION_GLOBAL, "host access prefix", "");
  476. verify_netdata_host_prefix();
  477. // --------------------------------------------------------------------
  478. // get KSM settings
  479. #ifdef MADV_MERGEABLE
  480. enable_ksm = config_get_boolean(CONFIG_SECTION_GLOBAL, "memory deduplication (ksm)", enable_ksm);
  481. #endif
  482. // --------------------------------------------------------------------
  483. // get various system parameters
  484. get_system_HZ();
  485. get_system_cpus();
  486. get_system_pid_max();
  487. }
  488. static int load_netdata_conf(char *filename, char overwrite_used) {
  489. errno = 0;
  490. int ret = 0;
  491. if(filename && *filename) {
  492. ret = config_load(filename, overwrite_used, NULL);
  493. if(!ret)
  494. error("CONFIG: cannot load config file '%s'.", filename);
  495. }
  496. else {
  497. filename = strdupz_path_subpath(netdata_configured_user_config_dir, "netdata.conf");
  498. ret = config_load(filename, overwrite_used, NULL);
  499. if(!ret) {
  500. info("CONFIG: cannot load user config '%s'. Will try the stock version.", filename);
  501. freez(filename);
  502. filename = strdupz_path_subpath(netdata_configured_stock_config_dir, "netdata.conf");
  503. ret = config_load(filename, overwrite_used, NULL);
  504. if(!ret)
  505. info("CONFIG: cannot load stock config '%s'. Running with internal defaults.", filename);
  506. }
  507. freez(filename);
  508. }
  509. return ret;
  510. }
  511. // coverity[ +tainted_string_sanitize_content : arg-0 ]
  512. static inline void coverity_remove_taint(char *s)
  513. {
  514. (void)s;
  515. }
  516. int get_system_info(struct rrdhost_system_info *system_info) {
  517. char *script;
  518. script = mallocz(sizeof(char) * (strlen(netdata_configured_primary_plugins_dir) + strlen("system-info.sh") + 2));
  519. sprintf(script, "%s/%s", netdata_configured_primary_plugins_dir, "system-info.sh");
  520. if (unlikely(access(script, R_OK) != 0)) {
  521. info("System info script %s not found.",script);
  522. freez(script);
  523. return 1;
  524. }
  525. pid_t command_pid;
  526. info("Executing %s", script);
  527. FILE *fp = mypopen(script, &command_pid);
  528. if(fp) {
  529. char line[200 + 1];
  530. // Removed the double strlens, if the Coverity tainted string warning reappears I'll revert.
  531. // One time init code, but I'm curious about the warning...
  532. while (fgets(line, 200, fp) != NULL) {
  533. char *value=line;
  534. while (*value && *value != '=') value++;
  535. if (*value=='=') {
  536. *value='\0';
  537. value++;
  538. char *end = value;
  539. while (*end && *end != '\n') end++;
  540. *end = '\0'; // Overwrite newline if present
  541. coverity_remove_taint(line); // I/O is controlled result of system_info.sh - not tainted
  542. coverity_remove_taint(value);
  543. if(unlikely(rrdhost_set_system_info_variable(system_info, line, value))) {
  544. info("Unexpected environment variable %s=%s", line, value);
  545. }
  546. else {
  547. info("%s=%s", line, value);
  548. setenv(line, value, 1);
  549. }
  550. }
  551. }
  552. mypclose(fp, command_pid);
  553. }
  554. freez(script);
  555. return 0;
  556. }
  557. void set_silencers_filename() {
  558. char filename[FILENAME_MAX + 1];
  559. snprintfz(filename, FILENAME_MAX, "%s/health.silencers.json", netdata_configured_varlib_dir);
  560. silencers_filename = config_get(CONFIG_SECTION_HEALTH, "silencers file", filename);
  561. }
  562. /* Any config setting that can be accessed without a default value i.e. configget(...,...,NULL) *MUST*
  563. be set in this procedure to be called in all the relevant code paths.
  564. */
  565. void post_conf_load(char **user)
  566. {
  567. // --------------------------------------------------------------------
  568. // get the user we should run
  569. // IMPORTANT: this is required before web_files_uid()
  570. if(getuid() == 0) {
  571. *user = config_get(CONFIG_SECTION_GLOBAL, "run as user", NETDATA_USER);
  572. }
  573. else {
  574. struct passwd *passwd = getpwuid(getuid());
  575. *user = config_get(CONFIG_SECTION_GLOBAL, "run as user", (passwd && passwd->pw_name)?passwd->pw_name:"");
  576. }
  577. // --------------------------------------------------------------------
  578. // Check if the cloud is enabled
  579. #if defined( DISABLE_CLOUD ) || !defined( ENABLE_ACLK )
  580. netdata_cloud_setting = 0;
  581. #else
  582. netdata_cloud_setting = appconfig_get_boolean(&cloud_config, CONFIG_SECTION_GLOBAL, "enabled", 1);
  583. #endif
  584. // This must be set before any point in the code that accesses it. Do not move it from this function.
  585. appconfig_get(&cloud_config, CONFIG_SECTION_GLOBAL, "cloud base url", DEFAULT_CLOUD_BASE_URL);
  586. }
  587. int main(int argc, char **argv) {
  588. int i;
  589. int config_loaded = 0;
  590. int dont_fork = 0;
  591. size_t default_stacksize;
  592. char *user = NULL;
  593. netdata_ready=0;
  594. // set the name for logging
  595. program_name = "netdata";
  596. if (argc > 1 && strcmp(argv[1], SPAWN_SERVER_COMMAND_LINE_ARGUMENT) == 0) {
  597. // don't run netdata, this is the spawn server
  598. spawn_server();
  599. exit(0);
  600. }
  601. // parse options
  602. {
  603. int num_opts = sizeof(option_definitions) / sizeof(struct option_def);
  604. char optstring[(num_opts * 2) + 1];
  605. int string_i = 0;
  606. for( i = 0; i < num_opts; i++ ) {
  607. optstring[string_i] = option_definitions[i].val;
  608. string_i++;
  609. if(option_definitions[i].arg_name) {
  610. optstring[string_i] = ':';
  611. string_i++;
  612. }
  613. }
  614. // terminate optstring
  615. optstring[string_i] ='\0';
  616. optstring[(num_opts *2)] ='\0';
  617. int opt;
  618. while( (opt = getopt(argc, argv, optstring)) != -1 ) {
  619. switch(opt) {
  620. case 'c':
  621. if(load_netdata_conf(optarg, 1) != 1) {
  622. error("Cannot load configuration file %s.", optarg);
  623. return 1;
  624. }
  625. else {
  626. debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
  627. post_conf_load(&user);
  628. load_cloud_conf(1);
  629. config_loaded = 1;
  630. }
  631. break;
  632. case 'D':
  633. dont_fork = 1;
  634. break;
  635. case 'd':
  636. dont_fork = 0;
  637. break;
  638. case 'h':
  639. return help(0);
  640. case 'i':
  641. config_set(CONFIG_SECTION_WEB, "bind to", optarg);
  642. break;
  643. case 'P':
  644. strncpy(pidfile, optarg, FILENAME_MAX);
  645. pidfile[FILENAME_MAX] = '\0';
  646. break;
  647. case 'p':
  648. config_set(CONFIG_SECTION_GLOBAL, "default port", optarg);
  649. break;
  650. case 's':
  651. config_set(CONFIG_SECTION_GLOBAL, "host access prefix", optarg);
  652. break;
  653. case 't':
  654. config_set(CONFIG_SECTION_GLOBAL, "update every", optarg);
  655. break;
  656. case 'u':
  657. config_set(CONFIG_SECTION_GLOBAL, "run as user", optarg);
  658. break;
  659. case 'v':
  660. case 'V':
  661. printf("%s %s\n", program_name, program_version);
  662. return 0;
  663. case 'W':
  664. {
  665. char* stacksize_string = "stacksize=";
  666. char* debug_flags_string = "debug_flags=";
  667. char* claim_string = "claim";
  668. #ifdef ENABLE_DBENGINE
  669. char* createdataset_string = "createdataset=";
  670. char* stresstest_string = "stresstest=";
  671. #endif
  672. if(strcmp(optarg, "unittest") == 0) {
  673. if(unit_test_buffer()) return 1;
  674. if(unit_test_str2ld()) return 1;
  675. // No call to load the config file on this code-path
  676. post_conf_load(&user);
  677. get_netdata_configured_variables();
  678. default_rrd_update_every = 1;
  679. default_rrd_memory_mode = RRD_MEMORY_MODE_RAM;
  680. default_health_enabled = 0;
  681. registry_init();
  682. if(rrd_init("unittest", NULL)) {
  683. fprintf(stderr, "rrd_init failed for unittest\n");
  684. return 1;
  685. }
  686. default_rrdpush_enabled = 0;
  687. if(run_all_mockup_tests()) return 1;
  688. if(unit_test_storage()) return 1;
  689. #ifdef ENABLE_DBENGINE
  690. if(test_dbengine()) return 1;
  691. #endif
  692. fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
  693. return 0;
  694. }
  695. #ifdef ENABLE_DBENGINE
  696. else if(strncmp(optarg, createdataset_string, strlen(createdataset_string)) == 0) {
  697. optarg += strlen(createdataset_string);
  698. unsigned history_seconds = strtoul(optarg, NULL, 0);
  699. generate_dbengine_dataset(history_seconds);
  700. return 0;
  701. }
  702. else if(strncmp(optarg, stresstest_string, strlen(stresstest_string)) == 0) {
  703. char *endptr;
  704. unsigned test_duration_sec = 0, dset_charts = 0, query_threads = 0, ramp_up_seconds = 0,
  705. page_cache_mb = 0, disk_space_mb = 0;
  706. optarg += strlen(stresstest_string);
  707. test_duration_sec = (unsigned)strtoul(optarg, &endptr, 0);
  708. if (',' == *endptr)
  709. dset_charts = (unsigned)strtoul(endptr + 1, &endptr, 0);
  710. if (',' == *endptr)
  711. query_threads = (unsigned)strtoul(endptr + 1, &endptr, 0);
  712. if (',' == *endptr)
  713. ramp_up_seconds = (unsigned)strtoul(endptr + 1, &endptr, 0);
  714. if (',' == *endptr)
  715. page_cache_mb = (unsigned)strtoul(endptr + 1, &endptr, 0);
  716. if (',' == *endptr)
  717. disk_space_mb = (unsigned)strtoul(endptr + 1, &endptr, 0);
  718. dbengine_stress_test(test_duration_sec, dset_charts, query_threads, ramp_up_seconds,
  719. page_cache_mb, disk_space_mb);
  720. return 0;
  721. }
  722. #endif
  723. else if(strcmp(optarg, "simple-pattern") == 0) {
  724. if(optind + 2 > argc) {
  725. fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
  726. " Checks if 'pattern' matches the given 'string'.\n"
  727. " - 'pattern' can be one or more space separated words.\n"
  728. " - each 'word' can contain one or more asterisks.\n"
  729. " - words starting with '!' give negative matches.\n"
  730. " - words are processed left to right\n"
  731. "\n"
  732. "Examples:\n"
  733. "\n"
  734. " > match all veth interfaces, except veth0:\n"
  735. "\n"
  736. " -W simple-pattern '!veth0 veth*' 'veth12'\n"
  737. "\n"
  738. "\n"
  739. " > match all *.ext files directly in /path/:\n"
  740. " (this will not match *.ext files in a subdir of /path/)\n"
  741. "\n"
  742. " -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
  743. "\n"
  744. );
  745. return 1;
  746. }
  747. const char *haystack = argv[optind];
  748. const char *needle = argv[optind + 1];
  749. size_t len = strlen(needle) + 1;
  750. char wildcarded[len];
  751. SIMPLE_PATTERN *p = simple_pattern_create(haystack, NULL, SIMPLE_PATTERN_EXACT);
  752. int ret = simple_pattern_matches_extract(p, needle, wildcarded, len);
  753. simple_pattern_free(p);
  754. if(ret) {
  755. fprintf(stdout, "RESULT: MATCHED - pattern '%s' matches '%s', wildcarded '%s'\n", haystack, needle, wildcarded);
  756. return 0;
  757. }
  758. else {
  759. fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s', wildcarded '%s'\n", haystack, needle, wildcarded);
  760. return 1;
  761. }
  762. }
  763. else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
  764. optarg += strlen(stacksize_string);
  765. config_set(CONFIG_SECTION_GLOBAL, "pthread stack size", optarg);
  766. }
  767. else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
  768. optarg += strlen(debug_flags_string);
  769. config_set(CONFIG_SECTION_GLOBAL, "debug flags", optarg);
  770. debug_flags = strtoull(optarg, NULL, 0);
  771. }
  772. else if(strcmp(optarg, "set") == 0) {
  773. if(optind + 3 > argc) {
  774. fprintf(stderr, "%s", "\nUSAGE: -W set 'section' 'key' 'value'\n\n"
  775. " Overwrites settings of netdata.conf.\n"
  776. "\n"
  777. " These options interact with: -c netdata.conf\n"
  778. " If -c netdata.conf is given on the command line,\n"
  779. " before -W set... the user may overwrite command\n"
  780. " line parameters at netdata.conf\n"
  781. " If -c netdata.conf is given after (or missing)\n"
  782. " -W set... the user cannot overwrite the command line\n"
  783. " parameters."
  784. "\n"
  785. );
  786. return 1;
  787. }
  788. const char *section = argv[optind];
  789. const char *key = argv[optind + 1];
  790. const char *value = argv[optind + 2];
  791. optind += 3;
  792. // set this one as the default
  793. // only if it is not already set in the config file
  794. // so the caller can use -c netdata.conf before or
  795. // after this parameter to prevent or allow overwriting
  796. // variables at netdata.conf
  797. config_set_default(section, key, value);
  798. // fprintf(stderr, "SET section '%s', key '%s', value '%s'\n", section, key, value);
  799. }
  800. else if(strcmp(optarg, "set2") == 0) {
  801. if(optind + 4 > argc) {
  802. fprintf(stderr, "%s", "\nUSAGE: -W set 'conf_file' 'section' 'key' 'value'\n\n"
  803. " Overwrites settings of netdata.conf or cloud.conf\n"
  804. "\n"
  805. " These options interact with: -c netdata.conf\n"
  806. " If -c netdata.conf is given on the command line,\n"
  807. " before -W set... the user may overwrite command\n"
  808. " line parameters at netdata.conf\n"
  809. " If -c netdata.conf is given after (or missing)\n"
  810. " -W set... the user cannot overwrite the command line\n"
  811. " parameters."
  812. " conf_file can be \"cloud\" or \"netdata\".\n"
  813. "\n"
  814. );
  815. return 1;
  816. }
  817. const char *conf_file = argv[optind]; /* "cloud" is cloud.conf, otherwise netdata.conf */
  818. struct config *tmp_config = strcmp(conf_file, "cloud") ? &netdata_config : &cloud_config;
  819. const char *section = argv[optind + 1];
  820. const char *key = argv[optind + 2];
  821. const char *value = argv[optind + 3];
  822. optind += 4;
  823. // set this one as the default
  824. // only if it is not already set in the config file
  825. // so the caller can use -c netdata.conf before or
  826. // after this parameter to prevent or allow overwriting
  827. // variables at netdata.conf
  828. appconfig_set_default(tmp_config, section, key, value);
  829. // fprintf(stderr, "SET section '%s', key '%s', value '%s'\n", section, key, value);
  830. }
  831. else if(strcmp(optarg, "get") == 0) {
  832. if(optind + 3 > argc) {
  833. fprintf(stderr, "%s", "\nUSAGE: -W get 'section' 'key' 'value'\n\n"
  834. " Prints settings of netdata.conf.\n"
  835. "\n"
  836. " These options interact with: -c netdata.conf\n"
  837. " -c netdata.conf has to be given before -W get.\n"
  838. "\n"
  839. );
  840. return 1;
  841. }
  842. if(!config_loaded) {
  843. fprintf(stderr, "warning: no configuration file has been loaded. Use -c CONFIG_FILE, before -W get. Using default config.\n");
  844. load_netdata_conf(NULL, 0);
  845. post_conf_load(&user);
  846. }
  847. get_netdata_configured_variables();
  848. const char *section = argv[optind];
  849. const char *key = argv[optind + 1];
  850. const char *def = argv[optind + 2];
  851. const char *value = config_get(section, key, def);
  852. printf("%s\n", value);
  853. return 0;
  854. }
  855. else if(strcmp(optarg, "get2") == 0) {
  856. if(optind + 4 > argc) {
  857. fprintf(stderr, "%s", "\nUSAGE: -W get2 'conf_file' 'section' 'key' 'value'\n\n"
  858. " Prints settings of netdata.conf or cloud.conf\n"
  859. "\n"
  860. " These options interact with: -c netdata.conf\n"
  861. " -c netdata.conf has to be given before -W get2.\n"
  862. " conf_file can be \"cloud\" or \"netdata\".\n"
  863. "\n"
  864. );
  865. return 1;
  866. }
  867. if(!config_loaded) {
  868. fprintf(stderr, "warning: no configuration file has been loaded. Use -c CONFIG_FILE, before -W get. Using default config.\n");
  869. load_netdata_conf(NULL, 0);
  870. post_conf_load(&user);
  871. load_cloud_conf(1);
  872. }
  873. get_netdata_configured_variables();
  874. const char *conf_file = argv[optind]; /* "cloud" is cloud.conf, otherwise netdata.conf */
  875. struct config *tmp_config = strcmp(conf_file, "cloud") ? &netdata_config : &cloud_config;
  876. const char *section = argv[optind + 1];
  877. const char *key = argv[optind + 2];
  878. const char *def = argv[optind + 3];
  879. const char *value = appconfig_get(tmp_config, section, key, def);
  880. printf("%s\n", value);
  881. return 0;
  882. }
  883. else if(strncmp(optarg, claim_string, strlen(claim_string)) == 0) {
  884. /* will trigger a claiming attempt when the agent is initialized */
  885. claiming_pending_arguments = optarg + strlen(claim_string);
  886. }
  887. else if(strcmp(optarg, "buildinfo") == 0) {
  888. printf("Version: %s %s\n", program_name, program_version);
  889. print_build_info();
  890. return 0;
  891. }
  892. else if(strcmp(optarg, "buildinfojson") == 0) {
  893. print_build_info_json();
  894. return 0;
  895. }
  896. else {
  897. fprintf(stderr, "Unknown -W parameter '%s'\n", optarg);
  898. return help(1);
  899. }
  900. }
  901. break;
  902. default: /* ? */
  903. fprintf(stderr, "Unknown parameter '%c'\n", opt);
  904. return help(1);
  905. }
  906. }
  907. }
  908. #ifdef _SC_OPEN_MAX
  909. // close all open file descriptors, except the standard ones
  910. // the caller may have left open files (lxc-attach has this issue)
  911. {
  912. int fd;
  913. for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
  914. if(fd_is_valid(fd)) close(fd);
  915. }
  916. #endif
  917. if(!config_loaded)
  918. {
  919. load_netdata_conf(NULL, 0);
  920. post_conf_load(&user);
  921. load_cloud_conf(0);
  922. }
  923. // ------------------------------------------------------------------------
  924. // initialize netdata
  925. {
  926. char *pmax = config_get(CONFIG_SECTION_GLOBAL, "glibc malloc arena max for plugins", "1");
  927. if(pmax && *pmax)
  928. setenv("MALLOC_ARENA_MAX", pmax, 1);
  929. #if defined(HAVE_C_MALLOPT)
  930. i = (int)config_get_number(CONFIG_SECTION_GLOBAL, "glibc malloc arena max for netdata", 1);
  931. if(i > 0)
  932. mallopt(M_ARENA_MAX, 1);
  933. #endif
  934. test_clock_boottime();
  935. test_clock_monotonic_coarse();
  936. // prepare configuration environment variables for the plugins
  937. get_netdata_configured_variables();
  938. set_global_environment();
  939. // work while we are cd into config_dir
  940. // to allow the plugins refer to their config
  941. // files using relative filenames
  942. if(chdir(netdata_configured_user_config_dir) == -1)
  943. fatal("Cannot cd to '%s'", netdata_configured_user_config_dir);
  944. // Get execution path before switching user to avoid permission issues
  945. get_netdata_execution_path();
  946. }
  947. {
  948. // --------------------------------------------------------------------
  949. // get the debugging flags from the configuration file
  950. char *flags = config_get(CONFIG_SECTION_GLOBAL, "debug flags", "0x0000000000000000");
  951. setenv("NETDATA_DEBUG_FLAGS", flags, 1);
  952. debug_flags = strtoull(flags, NULL, 0);
  953. debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);
  954. if(debug_flags != 0) {
  955. struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
  956. if(setrlimit(RLIMIT_CORE, &rl) != 0)
  957. error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
  958. #ifdef HAVE_SYS_PRCTL_H
  959. prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
  960. #endif
  961. }
  962. // --------------------------------------------------------------------
  963. // get log filenames and settings
  964. log_init();
  965. error_log_limit_unlimited();
  966. // --------------------------------------------------------------------
  967. // get the certificate and start security
  968. #ifdef ENABLE_HTTPS
  969. security_init();
  970. #endif
  971. // --------------------------------------------------------------------
  972. // This is the safest place to start the SILENCERS structure
  973. set_silencers_filename();
  974. health_initialize_global_silencers();
  975. // --------------------------------------------------------------------
  976. // setup process signals
  977. // block signals while initializing threads.
  978. // this causes the threads to block signals.
  979. signals_block();
  980. // setup the signals we want to use
  981. signals_init();
  982. // setup threads configs
  983. default_stacksize = netdata_threads_init();
  984. // --------------------------------------------------------------------
  985. // check which threads are enabled and initialize them
  986. for (i = 0; static_threads[i].name != NULL ; i++) {
  987. struct netdata_static_thread *st = &static_threads[i];
  988. if(st->config_name)
  989. st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
  990. if(st->enabled && st->init_routine)
  991. st->init_routine();
  992. }
  993. // --------------------------------------------------------------------
  994. // create the listening sockets
  995. web_client_api_v1_init();
  996. web_server_threading_selection();
  997. if(web_server_mode != WEB_SERVER_MODE_NONE)
  998. api_listen_sockets_setup();
  999. }
  1000. // initialize the log files
  1001. open_all_log_files();
  1002. #ifdef NETDATA_INTERNAL_CHECKS
  1003. if(debug_flags != 0) {
  1004. struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
  1005. if(setrlimit(RLIMIT_CORE, &rl) != 0)
  1006. error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
  1007. #ifdef HAVE_SYS_PRCTL_H
  1008. prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
  1009. #endif
  1010. }
  1011. #endif /* NETDATA_INTERNAL_CHECKS */
  1012. // get the max file limit
  1013. if(getrlimit(RLIMIT_NOFILE, &rlimit_nofile) != 0)
  1014. error("getrlimit(RLIMIT_NOFILE) failed");
  1015. else
  1016. info("resources control: allowed file descriptors: soft = %zu, max = %zu", (size_t)rlimit_nofile.rlim_cur, (size_t)rlimit_nofile.rlim_max);
  1017. // fork, switch user, create pid file, set process priority
  1018. if(become_daemon(dont_fork, user) == -1)
  1019. fatal("Cannot daemonize myself.");
  1020. info("netdata started on pid %d.", getpid());
  1021. // IMPORTANT: these have to run once, while single threaded
  1022. // but after we have switched user
  1023. web_files_uid();
  1024. web_files_gid();
  1025. netdata_threads_init_after_fork((size_t)config_get_number(CONFIG_SECTION_GLOBAL, "pthread stack size", (long)default_stacksize));
  1026. // initialize internal registry
  1027. registry_init();
  1028. // fork the spawn server
  1029. spawn_init();
  1030. /*
  1031. * Libuv uv_spawn() uses SIGCHLD internally:
  1032. * https://github.com/libuv/libuv/blob/cc51217a317e96510fbb284721d5e6bc2af31e33/src/unix/process.c#L485
  1033. * and inadvertently replaces the netdata signal handler which was setup during initialization.
  1034. * Thusly, we must explicitly restore the signal handler for SIGCHLD.
  1035. * Warning: extreme care is needed when mixing and matching POSIX and libuv.
  1036. */
  1037. signals_restore_SIGCHLD();
  1038. // ------------------------------------------------------------------------
  1039. // initialize rrd, registry, health, rrdpush, etc.
  1040. netdata_anonymous_statistics_enabled=-1;
  1041. struct rrdhost_system_info *system_info = calloc(1, sizeof(struct rrdhost_system_info));
  1042. get_system_info(system_info);
  1043. if(rrd_init(netdata_configured_hostname, system_info))
  1044. fatal("Cannot initialize localhost instance with name '%s'.", netdata_configured_hostname);
  1045. char agent_crash_file[FILENAME_MAX + 1];
  1046. char agent_incomplete_shutdown_file[FILENAME_MAX + 1];
  1047. snprintfz(agent_incomplete_shutdown_file, FILENAME_MAX, "%s/.agent_incomplete_shutdown", netdata_configured_varlib_dir);
  1048. int incomplete_shutdown_detected = (unlink(agent_incomplete_shutdown_file) == 0);
  1049. snprintfz(agent_crash_file, FILENAME_MAX, "%s/.agent_crash", netdata_configured_varlib_dir);
  1050. int crash_detected = (unlink(agent_crash_file) == 0);
  1051. int fd = open(agent_crash_file, O_WRONLY | O_CREAT | O_TRUNC, 444);
  1052. if (fd >= 0)
  1053. close(fd);
  1054. // ------------------------------------------------------------------------
  1055. // Claim netdata agent to a cloud endpoint
  1056. if (claiming_pending_arguments)
  1057. claim_agent(claiming_pending_arguments);
  1058. load_claiming_state();
  1059. // ------------------------------------------------------------------------
  1060. // enable log flood protection
  1061. error_log_limit_reset();
  1062. // Load host labels
  1063. reload_host_labels();
  1064. // ------------------------------------------------------------------------
  1065. // spawn the threads
  1066. web_server_config_options();
  1067. netdata_zero_metrics_enabled = config_get_boolean_ondemand(CONFIG_SECTION_GLOBAL, "enable zero metrics", CONFIG_BOOLEAN_NO);
  1068. for (i = 0; static_threads[i].name != NULL ; i++) {
  1069. struct netdata_static_thread *st = &static_threads[i];
  1070. if(st->enabled) {
  1071. st->thread = mallocz(sizeof(netdata_thread_t));
  1072. debug(D_SYSTEM, "Starting thread %s.", st->name);
  1073. netdata_thread_create(st->thread, st->name, NETDATA_THREAD_OPTION_DEFAULT, st->start_routine, st);
  1074. }
  1075. else debug(D_SYSTEM, "Not starting thread %s.", st->name);
  1076. }
  1077. // ------------------------------------------------------------------------
  1078. // Initialize netdata agent command serving from cli and signals
  1079. commands_init();
  1080. info("netdata initialization completed. Enjoy real-time performance monitoring!");
  1081. netdata_ready = 1;
  1082. set_late_global_environment();
  1083. send_statistics("START", "-", "-");
  1084. if (crash_detected)
  1085. send_statistics("CRASH", "-", "-");
  1086. if (incomplete_shutdown_detected)
  1087. send_statistics("INCOMPLETE_SHUTDOWN", "-", "-");
  1088. //check if ANALYTICS needs to start
  1089. if (netdata_anonymous_statistics_enabled == 1) {
  1090. for (i = 0; static_threads[i].name != NULL; i++) {
  1091. if (!strncmp(static_threads[i].name, "ANALYTICS", 9)) {
  1092. struct netdata_static_thread *st = &static_threads[i];
  1093. st->thread = mallocz(sizeof(netdata_thread_t));
  1094. st->enabled = 1;
  1095. debug(D_SYSTEM, "Starting thread %s.", st->name);
  1096. netdata_thread_create(st->thread, st->name, NETDATA_THREAD_OPTION_DEFAULT, st->start_routine, st);
  1097. }
  1098. }
  1099. }
  1100. // ------------------------------------------------------------------------
  1101. // Report ACLK build failure
  1102. #ifndef ENABLE_ACLK
  1103. error("This agent doesn't have ACLK.");
  1104. char filename[FILENAME_MAX + 1];
  1105. snprintfz(filename, FILENAME_MAX, "%s/.aclk_report_sent", netdata_configured_varlib_dir);
  1106. if (netdata_anonymous_statistics_enabled > 0 && access(filename, F_OK)) { // -1 -> not initialized
  1107. send_statistics("ACLK_DISABLED", "-", "-");
  1108. #ifdef ACLK_NO_LWS
  1109. send_statistics("BUILD_FAIL_LWS", "-", "-");
  1110. #endif
  1111. #ifdef ACLK_NO_LIBMOSQ
  1112. send_statistics("BUILD_FAIL_MOSQ", "-", "-");
  1113. #endif
  1114. int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 444);
  1115. if (fd == -1)
  1116. error("Cannot create file '%s'. Please fix this.", filename);
  1117. else
  1118. close(fd);
  1119. }
  1120. #endif
  1121. // ------------------------------------------------------------------------
  1122. // unblock signals
  1123. signals_unblock();
  1124. // ------------------------------------------------------------------------
  1125. // Handle signals
  1126. signals_handle();
  1127. // should never reach this point
  1128. // but we need it for rpmlint #2752
  1129. return 1;
  1130. }