main.c 49 KB

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