main.c 71 KB

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