main.c 59 KB

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