main.c 65 KB

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