main.c 64 KB

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