main.c 63 KB

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