main.c 57 KB

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