main.c 56 KB

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