main.c 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "common.h"
  3. #include "buildinfo.h"
  4. #include "static_threads.h"
  5. #if defined(ENV32BIT)
  6. #warning COMPILING 32BIT NETDATA
  7. #endif
  8. bool unittest_running = false;
  9. int netdata_zero_metrics_enabled;
  10. int netdata_anonymous_statistics_enabled;
  11. int libuv_worker_threads = MIN_LIBUV_WORKER_THREADS;
  12. bool ieee754_doubles = false;
  13. time_t netdata_start_time = 0;
  14. struct netdata_static_thread *static_threads;
  15. struct config netdata_config = {
  16. .first_section = NULL,
  17. .last_section = NULL,
  18. .mutex = NETDATA_MUTEX_INITIALIZER,
  19. .index = {
  20. .avl_tree = {
  21. .root = NULL,
  22. .compar = appconfig_section_compare
  23. },
  24. .rwlock = AVL_LOCK_INITIALIZER
  25. }
  26. };
  27. typedef struct service_thread {
  28. pid_t tid;
  29. SERVICE_THREAD_TYPE type;
  30. SERVICE_TYPE services;
  31. char name[NETDATA_THREAD_NAME_MAX + 1];
  32. bool stop_immediately;
  33. bool cancelled;
  34. union {
  35. netdata_thread_t netdata_thread;
  36. uv_thread_t uv_thread;
  37. };
  38. force_quit_t force_quit_callback;
  39. request_quit_t request_quit_callback;
  40. void *data;
  41. } SERVICE_THREAD;
  42. struct service_globals {
  43. SPINLOCK lock;
  44. Pvoid_t pid_judy;
  45. } service_globals = {
  46. .pid_judy = NULL,
  47. };
  48. SERVICE_THREAD *service_register(SERVICE_THREAD_TYPE thread_type, request_quit_t request_quit_callback, force_quit_t force_quit_callback, void *data, bool update __maybe_unused) {
  49. SERVICE_THREAD *sth = NULL;
  50. pid_t tid = gettid();
  51. spinlock_lock(&service_globals.lock);
  52. Pvoid_t *PValue = JudyLIns(&service_globals.pid_judy, tid, PJE0);
  53. if(!*PValue) {
  54. sth = callocz(1, sizeof(SERVICE_THREAD));
  55. sth->tid = tid;
  56. sth->type = thread_type;
  57. sth->request_quit_callback = request_quit_callback;
  58. sth->force_quit_callback = force_quit_callback;
  59. sth->data = data;
  60. os_thread_get_current_name_np(sth->name);
  61. *PValue = sth;
  62. switch(thread_type) {
  63. default:
  64. case SERVICE_THREAD_TYPE_NETDATA:
  65. sth->netdata_thread = netdata_thread_self();
  66. break;
  67. case SERVICE_THREAD_TYPE_EVENT_LOOP:
  68. case SERVICE_THREAD_TYPE_LIBUV:
  69. sth->uv_thread = uv_thread_self();
  70. break;
  71. }
  72. }
  73. else {
  74. sth = *PValue;
  75. }
  76. spinlock_unlock(&service_globals.lock);
  77. return sth;
  78. }
  79. void service_exits(void) {
  80. pid_t tid = gettid();
  81. spinlock_lock(&service_globals.lock);
  82. Pvoid_t *PValue = JudyLGet(service_globals.pid_judy, tid, PJE0);
  83. if(PValue) {
  84. freez(*PValue);
  85. JudyLDel(&service_globals.pid_judy, tid, PJE0);
  86. }
  87. spinlock_unlock(&service_globals.lock);
  88. }
  89. bool service_running(SERVICE_TYPE service) {
  90. static __thread SERVICE_THREAD *sth = NULL;
  91. if(unlikely(!sth))
  92. sth = service_register(SERVICE_THREAD_TYPE_NETDATA, NULL, NULL, NULL, false);
  93. sth->services |= service;
  94. return !(sth->stop_immediately || netdata_exit);
  95. }
  96. void service_signal_exit(SERVICE_TYPE service) {
  97. spinlock_lock(&service_globals.lock);
  98. Pvoid_t *PValue;
  99. Word_t tid = 0;
  100. bool first = true;
  101. while((PValue = JudyLFirstThenNext(service_globals.pid_judy, &tid, &first))) {
  102. SERVICE_THREAD *sth = *PValue;
  103. if((sth->services & service)) {
  104. sth->stop_immediately = true;
  105. if(sth->request_quit_callback) {
  106. spinlock_unlock(&service_globals.lock);
  107. sth->request_quit_callback(sth->data);
  108. spinlock_lock(&service_globals.lock);
  109. }
  110. }
  111. }
  112. spinlock_unlock(&service_globals.lock);
  113. }
  114. static void service_to_buffer(BUFFER *wb, SERVICE_TYPE service) {
  115. if(service & SERVICE_MAINTENANCE)
  116. buffer_strcat(wb, "MAINTENANCE ");
  117. if(service & SERVICE_COLLECTORS)
  118. buffer_strcat(wb, "COLLECTORS ");
  119. if(service & SERVICE_REPLICATION)
  120. buffer_strcat(wb, "REPLICATION ");
  121. if(service & ABILITY_DATA_QUERIES)
  122. buffer_strcat(wb, "DATA_QUERIES ");
  123. if(service & ABILITY_WEB_REQUESTS)
  124. buffer_strcat(wb, "WEB_REQUESTS ");
  125. if(service & SERVICE_WEB_SERVER)
  126. buffer_strcat(wb, "WEB_SERVER ");
  127. if(service & SERVICE_ACLK)
  128. buffer_strcat(wb, "ACLK ");
  129. if(service & SERVICE_HEALTH)
  130. buffer_strcat(wb, "HEALTH ");
  131. if(service & SERVICE_STREAMING)
  132. buffer_strcat(wb, "STREAMING ");
  133. if(service & ABILITY_STREAMING_CONNECTIONS)
  134. buffer_strcat(wb, "STREAMING_CONNECTIONS ");
  135. if(service & SERVICE_CONTEXT)
  136. buffer_strcat(wb, "CONTEXT ");
  137. if(service & SERVICE_ANALYTICS)
  138. buffer_strcat(wb, "ANALYTICS ");
  139. if(service & SERVICE_EXPORTERS)
  140. buffer_strcat(wb, "EXPORTERS ");
  141. if(service & SERVICE_HTTPD)
  142. buffer_strcat(wb, "HTTPD ");
  143. }
  144. static bool service_wait_exit(SERVICE_TYPE service, usec_t timeout_ut) {
  145. BUFFER *service_list = buffer_create(1024, NULL);
  146. BUFFER *thread_list = buffer_create(1024, NULL);
  147. usec_t started_ut = now_monotonic_usec(), ended_ut;
  148. size_t running;
  149. SERVICE_TYPE running_services = 0;
  150. // cancel the threads
  151. running = 0;
  152. running_services = 0;
  153. {
  154. buffer_flush(thread_list);
  155. spinlock_lock(&service_globals.lock);
  156. Pvoid_t *PValue;
  157. Word_t tid = 0;
  158. bool first = true;
  159. while((PValue = JudyLFirstThenNext(service_globals.pid_judy, &tid, &first))) {
  160. SERVICE_THREAD *sth = *PValue;
  161. if(sth->services & service && sth->tid != gettid() && !sth->cancelled) {
  162. sth->cancelled = true;
  163. switch(sth->type) {
  164. default:
  165. case SERVICE_THREAD_TYPE_NETDATA:
  166. netdata_thread_cancel(sth->netdata_thread);
  167. break;
  168. case SERVICE_THREAD_TYPE_EVENT_LOOP:
  169. case SERVICE_THREAD_TYPE_LIBUV:
  170. break;
  171. }
  172. if(running)
  173. buffer_strcat(thread_list, ", ");
  174. buffer_sprintf(thread_list, "'%s' (%d)", sth->name, sth->tid);
  175. running++;
  176. running_services |= sth->services & service;
  177. if(sth->force_quit_callback) {
  178. spinlock_unlock(&service_globals.lock);
  179. sth->force_quit_callback(sth->data);
  180. spinlock_lock(&service_globals.lock);
  181. continue;
  182. }
  183. }
  184. }
  185. spinlock_unlock(&service_globals.lock);
  186. }
  187. service_signal_exit(service);
  188. // signal them to stop
  189. size_t last_running = 0;
  190. size_t stale_time_ut = 0;
  191. usec_t sleep_ut = 50 * USEC_PER_MS;
  192. size_t log_countdown_ut = sleep_ut;
  193. do {
  194. if(running != last_running)
  195. stale_time_ut = 0;
  196. last_running = running;
  197. running = 0;
  198. running_services = 0;
  199. buffer_flush(thread_list);
  200. spinlock_lock(&service_globals.lock);
  201. Pvoid_t *PValue;
  202. Word_t tid = 0;
  203. bool first = true;
  204. while((PValue = JudyLFirstThenNext(service_globals.pid_judy, &tid, &first))) {
  205. SERVICE_THREAD *sth = *PValue;
  206. if(sth->services & service && sth->tid != gettid()) {
  207. if(running)
  208. buffer_strcat(thread_list, ", ");
  209. buffer_sprintf(thread_list, "'%s' (%d)", sth->name, sth->tid);
  210. running_services |= sth->services & service;
  211. running++;
  212. }
  213. }
  214. spinlock_unlock(&service_globals.lock);
  215. if(running) {
  216. log_countdown_ut -= (log_countdown_ut >= sleep_ut) ? sleep_ut : log_countdown_ut;
  217. if(log_countdown_ut == 0 || running != last_running) {
  218. log_countdown_ut = 20 * sleep_ut;
  219. buffer_flush(service_list);
  220. service_to_buffer(service_list, running_services);
  221. netdata_log_info("SERVICE CONTROL: waiting for the following %zu services [ %s] to exit: %s",
  222. running, buffer_tostring(service_list),
  223. running <= 10 ? buffer_tostring(thread_list) : "");
  224. }
  225. sleep_usec(sleep_ut);
  226. stale_time_ut += sleep_ut;
  227. }
  228. ended_ut = now_monotonic_usec();
  229. } while(running && (ended_ut - started_ut < timeout_ut || stale_time_ut < timeout_ut));
  230. if(running) {
  231. buffer_flush(service_list);
  232. service_to_buffer(service_list, running_services);
  233. netdata_log_info("SERVICE CONTROL: "
  234. "the following %zu service(s) [ %s] take too long to exit: %s; "
  235. "giving up on them...",
  236. running, buffer_tostring(service_list),
  237. buffer_tostring(thread_list));
  238. }
  239. buffer_free(thread_list);
  240. buffer_free(service_list);
  241. return (running == 0);
  242. }
  243. #define delta_shutdown_time(msg) \
  244. { \
  245. usec_t now_ut = now_monotonic_usec(); \
  246. if(prev_msg) \
  247. netdata_log_info("NETDATA SHUTDOWN: in %7llu ms, %s%s - next: %s", (now_ut - last_ut) / USEC_PER_MS, (timeout)?"(TIMEOUT) ":"", prev_msg, msg); \
  248. else \
  249. netdata_log_info("NETDATA SHUTDOWN: next: %s", msg); \
  250. last_ut = now_ut; \
  251. prev_msg = msg; \
  252. timeout = false; \
  253. }
  254. void web_client_cache_destroy(void);
  255. void netdata_cleanup_and_exit(int ret) {
  256. usec_t started_ut = now_monotonic_usec();
  257. usec_t last_ut = started_ut;
  258. const char *prev_msg = NULL;
  259. bool timeout = false;
  260. error_log_limit_unlimited();
  261. netdata_log_info("NETDATA SHUTDOWN: initializing shutdown with code %d...", ret);
  262. send_statistics("EXIT", ret?"ERROR":"OK","-");
  263. delta_shutdown_time("create shutdown file");
  264. char agent_crash_file[FILENAME_MAX + 1];
  265. char agent_incomplete_shutdown_file[FILENAME_MAX + 1];
  266. snprintfz(agent_crash_file, FILENAME_MAX, "%s/.agent_crash", netdata_configured_varlib_dir);
  267. snprintfz(agent_incomplete_shutdown_file, FILENAME_MAX, "%s/.agent_incomplete_shutdown", netdata_configured_varlib_dir);
  268. (void) rename(agent_crash_file, agent_incomplete_shutdown_file);
  269. #ifdef ENABLE_DBENGINE
  270. if(dbengine_enabled) {
  271. delta_shutdown_time("dbengine exit mode");
  272. for (size_t tier = 0; tier < storage_tiers; tier++)
  273. rrdeng_exit_mode(multidb_ctx[tier]);
  274. }
  275. #endif
  276. delta_shutdown_time("close webrtc connections");
  277. webrtc_close_all_connections();
  278. delta_shutdown_time("disable maintenance, new queries, new web requests, new streaming connections and aclk");
  279. service_signal_exit(
  280. SERVICE_MAINTENANCE
  281. | ABILITY_DATA_QUERIES
  282. | ABILITY_WEB_REQUESTS
  283. | ABILITY_STREAMING_CONNECTIONS
  284. | SERVICE_ACLK
  285. | SERVICE_ACLKSYNC
  286. );
  287. delta_shutdown_time("stop replication, exporters, health and web servers threads");
  288. timeout = !service_wait_exit(
  289. SERVICE_EXPORTERS
  290. | SERVICE_HEALTH
  291. | SERVICE_WEB_SERVER
  292. | SERVICE_HTTPD
  293. , 3 * USEC_PER_SEC);
  294. delta_shutdown_time("stop collectors and streaming threads");
  295. timeout = !service_wait_exit(
  296. SERVICE_COLLECTORS
  297. | SERVICE_STREAMING
  298. , 3 * USEC_PER_SEC);
  299. delta_shutdown_time("stop replication threads");
  300. timeout = !service_wait_exit(
  301. SERVICE_REPLICATION // replication has to be stopped after STREAMING, because it cleans up ARAL
  302. , 3 * USEC_PER_SEC);
  303. delta_shutdown_time("disable ML detection and training threads");
  304. ml_stop_threads();
  305. ml_fini();
  306. delta_shutdown_time("stop context thread");
  307. timeout = !service_wait_exit(
  308. SERVICE_CONTEXT
  309. , 3 * USEC_PER_SEC);
  310. delta_shutdown_time("stop maintenance thread");
  311. timeout = !service_wait_exit(
  312. SERVICE_MAINTENANCE
  313. , 3 * USEC_PER_SEC);
  314. delta_shutdown_time("clear web client cache");
  315. web_client_cache_destroy();
  316. delta_shutdown_time("clean rrdhost database");
  317. rrdhost_cleanup_all();
  318. delta_shutdown_time("prepare metasync shutdown");
  319. metadata_sync_shutdown_prepare();
  320. delta_shutdown_time("stop aclk threads");
  321. timeout = !service_wait_exit(
  322. SERVICE_ACLK
  323. , 3 * USEC_PER_SEC);
  324. delta_shutdown_time("stop all remaining worker threads");
  325. timeout = !service_wait_exit(~0, 10 * USEC_PER_SEC);
  326. delta_shutdown_time("cancel main threads");
  327. cancel_main_threads();
  328. if(!ret) {
  329. // exit cleanly
  330. #ifdef ENABLE_DBENGINE
  331. if(dbengine_enabled) {
  332. delta_shutdown_time("flush dbengine tiers");
  333. for (size_t tier = 0; tier < storage_tiers; tier++)
  334. rrdeng_prepare_exit(multidb_ctx[tier]);
  335. }
  336. #endif
  337. // free the database
  338. delta_shutdown_time("stop collection for all hosts");
  339. // rrdhost_free_all();
  340. rrd_finalize_collection_for_all_hosts();
  341. delta_shutdown_time("stop metasync threads");
  342. metadata_sync_shutdown();
  343. #ifdef ENABLE_DBENGINE
  344. if(dbengine_enabled) {
  345. delta_shutdown_time("wait for dbengine collectors to finish");
  346. size_t running = 1;
  347. while(running) {
  348. running = 0;
  349. for (size_t tier = 0; tier < storage_tiers; tier++)
  350. running += rrdeng_collectors_running(multidb_ctx[tier]);
  351. if(running) {
  352. error_limit_static_thread_var(erl, 1, 100 * USEC_PER_MS);
  353. error_limit(&erl, "waiting for %zu collectors to finish", running);
  354. // sleep_usec(100 * USEC_PER_MS);
  355. cleanup_destroyed_dictionaries();
  356. }
  357. }
  358. delta_shutdown_time("wait for dbengine main cache to finish flushing");
  359. while (pgc_hot_and_dirty_entries(main_cache)) {
  360. pgc_flush_all_hot_and_dirty_pages(main_cache, PGC_SECTION_ALL);
  361. sleep_usec(100 * USEC_PER_MS);
  362. }
  363. delta_shutdown_time("stop dbengine tiers");
  364. for (size_t tier = 0; tier < storage_tiers; tier++)
  365. rrdeng_exit(multidb_ctx[tier]);
  366. }
  367. #endif
  368. }
  369. delta_shutdown_time("close SQL context db");
  370. sql_close_context_database();
  371. delta_shutdown_time("closed SQL main db");
  372. sql_close_database();
  373. // unlink the pid
  374. if(pidfile[0]) {
  375. delta_shutdown_time("remove pid file");
  376. if(unlink(pidfile) != 0)
  377. netdata_log_error("EXIT: cannot unlink pidfile '%s'.", pidfile);
  378. }
  379. #ifdef ENABLE_HTTPS
  380. delta_shutdown_time("free openssl structures");
  381. netdata_ssl_cleanup();
  382. #endif
  383. delta_shutdown_time("remove incomplete shutdown file");
  384. (void) unlink(agent_incomplete_shutdown_file);
  385. delta_shutdown_time("exit");
  386. usec_t ended_ut = now_monotonic_usec();
  387. netdata_log_info("NETDATA SHUTDOWN: completed in %llu ms - netdata is now exiting - bye bye...", (ended_ut - started_ut) / USEC_PER_MS);
  388. exit(ret);
  389. }
  390. void web_server_threading_selection(void) {
  391. web_server_mode = web_server_mode_id(config_get(CONFIG_SECTION_WEB, "mode", web_server_mode_name(web_server_mode)));
  392. int static_threaded = (web_server_mode == WEB_SERVER_MODE_STATIC_THREADED);
  393. int i;
  394. for (i = 0; static_threads[i].name; i++) {
  395. if (static_threads[i].start_routine == socket_listen_main_static_threaded)
  396. static_threads[i].enabled = static_threaded;
  397. }
  398. }
  399. int make_dns_decision(const char *section_name, const char *config_name, const char *default_value, SIMPLE_PATTERN *p)
  400. {
  401. char *value = config_get(section_name,config_name,default_value);
  402. if(!strcmp("yes",value))
  403. return 1;
  404. if(!strcmp("no",value))
  405. return 0;
  406. if(strcmp("heuristic",value))
  407. netdata_log_error("Invalid configuration option '%s' for '%s'/'%s'. Valid options are 'yes', 'no' and 'heuristic'. Proceeding with 'heuristic'",
  408. value, section_name, config_name);
  409. return simple_pattern_is_potential_name(p);
  410. }
  411. void web_server_config_options(void)
  412. {
  413. web_client_timeout =
  414. (int)config_get_number(CONFIG_SECTION_WEB, "disconnect idle clients after seconds", web_client_timeout);
  415. web_client_first_request_timeout =
  416. (int)config_get_number(CONFIG_SECTION_WEB, "timeout for first request", web_client_first_request_timeout);
  417. web_client_streaming_rate_t =
  418. config_get_number(CONFIG_SECTION_WEB, "accept a streaming request every seconds", web_client_streaming_rate_t);
  419. respect_web_browser_do_not_track_policy =
  420. config_get_boolean(CONFIG_SECTION_WEB, "respect do not track policy", respect_web_browser_do_not_track_policy);
  421. web_x_frame_options = config_get(CONFIG_SECTION_WEB, "x-frame-options response header", "");
  422. if(!*web_x_frame_options)
  423. web_x_frame_options = NULL;
  424. web_allow_connections_from =
  425. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow connections from", "localhost *"),
  426. NULL, SIMPLE_PATTERN_EXACT, true);
  427. web_allow_connections_dns =
  428. make_dns_decision(CONFIG_SECTION_WEB, "allow connections by dns", "heuristic", web_allow_connections_from);
  429. web_allow_dashboard_from =
  430. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow dashboard from", "localhost *"),
  431. NULL, SIMPLE_PATTERN_EXACT, true);
  432. web_allow_dashboard_dns =
  433. make_dns_decision(CONFIG_SECTION_WEB, "allow dashboard by dns", "heuristic", web_allow_dashboard_from);
  434. web_allow_badges_from =
  435. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow badges from", "*"), NULL, SIMPLE_PATTERN_EXACT,
  436. true);
  437. web_allow_badges_dns =
  438. make_dns_decision(CONFIG_SECTION_WEB, "allow badges by dns", "heuristic", web_allow_badges_from);
  439. web_allow_registry_from =
  440. simple_pattern_create(config_get(CONFIG_SECTION_REGISTRY, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT,
  441. true);
  442. web_allow_registry_dns = make_dns_decision(CONFIG_SECTION_REGISTRY, "allow by dns", "heuristic",
  443. web_allow_registry_from);
  444. web_allow_streaming_from = simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow streaming from", "*"),
  445. NULL, SIMPLE_PATTERN_EXACT, true);
  446. web_allow_streaming_dns = make_dns_decision(CONFIG_SECTION_WEB, "allow streaming by dns", "heuristic",
  447. web_allow_streaming_from);
  448. // Note the default is not heuristic, the wildcards could match DNS but the intent is ip-addresses.
  449. web_allow_netdataconf_from = simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow netdata.conf from",
  450. "localhost fd* 10.* 192.168.* 172.16.* 172.17.* 172.18.*"
  451. " 172.19.* 172.20.* 172.21.* 172.22.* 172.23.* 172.24.*"
  452. " 172.25.* 172.26.* 172.27.* 172.28.* 172.29.* 172.30.*"
  453. " 172.31.* UNKNOWN"), NULL, SIMPLE_PATTERN_EXACT,
  454. true);
  455. web_allow_netdataconf_dns =
  456. make_dns_decision(CONFIG_SECTION_WEB, "allow netdata.conf by dns", "no", web_allow_netdataconf_from);
  457. web_allow_mgmt_from =
  458. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow management from", "localhost"),
  459. NULL, SIMPLE_PATTERN_EXACT, true);
  460. web_allow_mgmt_dns =
  461. make_dns_decision(CONFIG_SECTION_WEB, "allow management by dns","heuristic",web_allow_mgmt_from);
  462. web_enable_gzip = config_get_boolean(CONFIG_SECTION_WEB, "enable gzip compression", web_enable_gzip);
  463. char *s = config_get(CONFIG_SECTION_WEB, "gzip compression strategy", "default");
  464. if(!strcmp(s, "default"))
  465. web_gzip_strategy = Z_DEFAULT_STRATEGY;
  466. else if(!strcmp(s, "filtered"))
  467. web_gzip_strategy = Z_FILTERED;
  468. else if(!strcmp(s, "huffman only"))
  469. web_gzip_strategy = Z_HUFFMAN_ONLY;
  470. else if(!strcmp(s, "rle"))
  471. web_gzip_strategy = Z_RLE;
  472. else if(!strcmp(s, "fixed"))
  473. web_gzip_strategy = Z_FIXED;
  474. else {
  475. netdata_log_error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
  476. web_gzip_strategy = Z_DEFAULT_STRATEGY;
  477. }
  478. web_gzip_level = (int)config_get_number(CONFIG_SECTION_WEB, "gzip compression level", 3);
  479. if(web_gzip_level < 1) {
  480. netdata_log_error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
  481. web_gzip_level = 1;
  482. }
  483. else if(web_gzip_level > 9) {
  484. netdata_log_error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
  485. web_gzip_level = 9;
  486. }
  487. }
  488. // killpid kills pid with SIGTERM.
  489. int killpid(pid_t pid) {
  490. int ret;
  491. netdata_log_debug(D_EXIT, "Request to kill pid %d", pid);
  492. errno = 0;
  493. ret = kill(pid, SIGTERM);
  494. if (ret == -1) {
  495. switch(errno) {
  496. case ESRCH:
  497. // We wanted the process to exit so just let the caller handle.
  498. return ret;
  499. case EPERM:
  500. netdata_log_error("Cannot kill pid %d, but I do not have enough permissions.", pid);
  501. break;
  502. default:
  503. netdata_log_error("Cannot kill pid %d, but I received an error.", pid);
  504. break;
  505. }
  506. }
  507. return ret;
  508. }
  509. static void set_nofile_limit(struct rlimit *rl) {
  510. // get the num files allowed
  511. if(getrlimit(RLIMIT_NOFILE, rl) != 0) {
  512. netdata_log_error("getrlimit(RLIMIT_NOFILE) failed");
  513. return;
  514. }
  515. netdata_log_info("resources control: allowed file descriptors: soft = %zu, max = %zu",
  516. (size_t) rl->rlim_cur, (size_t) rl->rlim_max);
  517. // make the soft/hard limits equal
  518. rl->rlim_cur = rl->rlim_max;
  519. if (setrlimit(RLIMIT_NOFILE, rl) != 0) {
  520. netdata_log_error("setrlimit(RLIMIT_NOFILE, { %zu, %zu }) failed", (size_t)rl->rlim_cur, (size_t)rl->rlim_max);
  521. }
  522. // sanity check to make sure we have enough file descriptors available to open
  523. if (getrlimit(RLIMIT_NOFILE, rl) != 0) {
  524. netdata_log_error("getrlimit(RLIMIT_NOFILE) failed");
  525. return;
  526. }
  527. if (rl->rlim_cur < 1024)
  528. netdata_log_error("Number of open file descriptors allowed for this process is too low (RLIMIT_NOFILE=%zu)", (size_t)rl->rlim_cur);
  529. }
  530. void cancel_main_threads() {
  531. error_log_limit_unlimited();
  532. int i, found = 0;
  533. usec_t max = 5 * USEC_PER_SEC, step = 100000;
  534. for (i = 0; static_threads[i].name != NULL ; i++) {
  535. if (static_threads[i].enabled == NETDATA_MAIN_THREAD_RUNNING) {
  536. if (static_threads[i].thread) {
  537. netdata_log_info("EXIT: Stopping main thread: %s", static_threads[i].name);
  538. netdata_thread_cancel(*static_threads[i].thread);
  539. } else {
  540. netdata_log_info("EXIT: No thread running (marking as EXITED): %s", static_threads[i].name);
  541. static_threads[i].enabled = NETDATA_MAIN_THREAD_EXITED;
  542. }
  543. found++;
  544. }
  545. }
  546. netdata_exit = 1;
  547. while(found && max > 0) {
  548. max -= step;
  549. netdata_log_info("Waiting %d threads to finish...", found);
  550. sleep_usec(step);
  551. found = 0;
  552. for (i = 0; static_threads[i].name != NULL ; i++) {
  553. if (static_threads[i].enabled != NETDATA_MAIN_THREAD_EXITED)
  554. found++;
  555. }
  556. }
  557. if(found) {
  558. for (i = 0; static_threads[i].name != NULL ; i++) {
  559. if (static_threads[i].enabled != NETDATA_MAIN_THREAD_EXITED)
  560. netdata_log_error("Main thread %s takes too long to exit. Giving up...", static_threads[i].name);
  561. }
  562. }
  563. else
  564. netdata_log_info("All threads finished.");
  565. for (i = 0; static_threads[i].name != NULL ; i++)
  566. freez(static_threads[i].thread);
  567. freez(static_threads);
  568. }
  569. struct option_def option_definitions[] = {
  570. // opt description arg name default value
  571. { 'c', "Configuration file to load.", "filename", CONFIG_DIR "/" CONFIG_FILENAME},
  572. { 'D', "Do not fork. Run in the foreground.", NULL, "run in the background"},
  573. { 'd', "Fork. Run in the background.", NULL, "run in the background"},
  574. { 'h', "Display this help message.", NULL, NULL},
  575. { 'P', "File to save a pid while running.", "filename", "do not save pid to a file"},
  576. { 'i', "The IP address to listen to.", "IP", "all IP addresses IPv4 and IPv6"},
  577. { 'p', "API/Web port to use.", "port", "19999"},
  578. { 's', "Prefix for /proc and /sys (for containers).", "path", "no prefix"},
  579. { 't', "The internal clock of netdata.", "seconds", "1"},
  580. { 'u', "Run as user.", "username", "netdata"},
  581. { 'v', "Print netdata version and exit.", NULL, NULL},
  582. { 'V', "Print netdata version and exit.", NULL, NULL},
  583. { 'W', "See Advanced options below.", "options", NULL},
  584. };
  585. int help(int exitcode) {
  586. FILE *stream;
  587. if(exitcode == 0)
  588. stream = stdout;
  589. else
  590. stream = stderr;
  591. int num_opts = sizeof(option_definitions) / sizeof(struct option_def);
  592. int i;
  593. int max_len_arg = 0;
  594. // Compute maximum argument length
  595. for( i = 0; i < num_opts; i++ ) {
  596. if(option_definitions[i].arg_name) {
  597. int len_arg = (int)strlen(option_definitions[i].arg_name);
  598. if(len_arg > max_len_arg) max_len_arg = len_arg;
  599. }
  600. }
  601. if(max_len_arg > 30) max_len_arg = 30;
  602. if(max_len_arg < 20) max_len_arg = 20;
  603. fprintf(stream, "%s", "\n"
  604. " ^\n"
  605. " |.-. .-. .-. .-. . netdata \n"
  606. " | '-' '-' '-' '-' real-time performance monitoring, done right! \n"
  607. " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
  608. "\n"
  609. " Copyright (C) 2016-2022, Netdata, Inc. <info@netdata.cloud>\n"
  610. " Released under GNU General Public License v3 or later.\n"
  611. " All rights reserved.\n"
  612. "\n"
  613. " Home Page : https://netdata.cloud\n"
  614. " Source Code: https://github.com/netdata/netdata\n"
  615. " Docs : https://learn.netdata.cloud\n"
  616. " Support : https://github.com/netdata/netdata/issues\n"
  617. " License : https://github.com/netdata/netdata/blob/master/LICENSE.md\n"
  618. "\n"
  619. " Twitter : https://twitter.com/netdatahq\n"
  620. " LinkedIn : https://linkedin.com/company/netdata-cloud/\n"
  621. " Facebook : https://facebook.com/linuxnetdata/\n"
  622. "\n"
  623. "\n"
  624. );
  625. fprintf(stream, " SYNOPSIS: netdata [options]\n");
  626. fprintf(stream, "\n");
  627. fprintf(stream, " Options:\n\n");
  628. // Output options description.
  629. for( i = 0; i < num_opts; i++ ) {
  630. 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);
  631. if(option_definitions[i].default_value) {
  632. fprintf(stream, "\n %c %-*s Default: %s\n", ' ', max_len_arg, "", option_definitions[i].default_value);
  633. } else {
  634. fprintf(stream, "\n");
  635. }
  636. fprintf(stream, "\n");
  637. }
  638. fprintf(stream, "\n Advanced options:\n\n"
  639. " -W stacksize=N Set the stacksize (in bytes).\n\n"
  640. " -W debug_flags=N Set runtime tracing to debug.log.\n\n"
  641. " -W unittest Run internal unittests and exit.\n\n"
  642. " -W sqlite-meta-recover Run recovery on the metadata database and exit.\n\n"
  643. " -W sqlite-compact Reclaim metadata database unused space and exit.\n\n"
  644. #ifdef ENABLE_DBENGINE
  645. " -W createdataset=N Create a DB engine dataset of N seconds and exit.\n\n"
  646. " -W stresstest=A,B,C,D,E,F,G\n"
  647. " Run a DB engine stress test for A seconds,\n"
  648. " with B writers and C readers, with a ramp up\n"
  649. " time of D seconds for writers, a page cache\n"
  650. " size of E MiB, an optional disk space limit\n"
  651. " of F MiB, G libuv workers (default 16) and exit.\n\n"
  652. #endif
  653. " -W set section option value\n"
  654. " set netdata.conf option from the command line.\n\n"
  655. " -W buildinfo Print the version, the configure options,\n"
  656. " a list of optional features, and whether they\n"
  657. " are enabled or not.\n\n"
  658. " -W buildinfojson Print the version, the configure options,\n"
  659. " a list of optional features, and whether they\n"
  660. " are enabled or not, in JSON format.\n\n"
  661. " -W simple-pattern pattern string\n"
  662. " Check if string matches pattern and exit.\n\n"
  663. " -W \"claim -token=TOKEN -rooms=ROOM1,ROOM2\"\n"
  664. " Claim the agent to the workspace rooms pointed to by TOKEN and ROOM*.\n\n"
  665. );
  666. fprintf(stream, "\n Signals netdata handles:\n\n"
  667. " - HUP Close and reopen log files.\n"
  668. " - USR1 Save internal DB to disk.\n"
  669. " - USR2 Reload health configuration.\n"
  670. "\n"
  671. );
  672. fflush(stream);
  673. return exitcode;
  674. }
  675. #ifdef ENABLE_HTTPS
  676. static void security_init(){
  677. char filename[FILENAME_MAX + 1];
  678. snprintfz(filename, FILENAME_MAX, "%s/ssl/key.pem",netdata_configured_user_config_dir);
  679. netdata_ssl_security_key = config_get(CONFIG_SECTION_WEB, "ssl key", filename);
  680. snprintfz(filename, FILENAME_MAX, "%s/ssl/cert.pem",netdata_configured_user_config_dir);
  681. netdata_ssl_security_cert = config_get(CONFIG_SECTION_WEB, "ssl certificate", filename);
  682. tls_version = config_get(CONFIG_SECTION_WEB, "tls version", "1.3");
  683. tls_ciphers = config_get(CONFIG_SECTION_WEB, "tls ciphers", "none");
  684. netdata_ssl_initialize_openssl();
  685. }
  686. #endif
  687. static void log_init(void) {
  688. char filename[FILENAME_MAX + 1];
  689. snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);
  690. stdout_filename = config_get(CONFIG_SECTION_LOGS, "debug", filename);
  691. snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);
  692. stderr_filename = config_get(CONFIG_SECTION_LOGS, "error", filename);
  693. snprintfz(filename, FILENAME_MAX, "%s/collector.log", netdata_configured_log_dir);
  694. stdcollector_filename = config_get(CONFIG_SECTION_LOGS, "collector", filename);
  695. snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);
  696. stdaccess_filename = config_get(CONFIG_SECTION_LOGS, "access", filename);
  697. snprintfz(filename, FILENAME_MAX, "%s/health.log", netdata_configured_log_dir);
  698. stdhealth_filename = config_get(CONFIG_SECTION_LOGS, "health", filename);
  699. #ifdef ENABLE_ACLK
  700. aclklog_enabled = config_get_boolean(CONFIG_SECTION_CLOUD, "conversation log", CONFIG_BOOLEAN_NO);
  701. if (aclklog_enabled) {
  702. snprintfz(filename, FILENAME_MAX, "%s/aclk.log", netdata_configured_log_dir);
  703. aclklog_filename = config_get(CONFIG_SECTION_CLOUD, "conversation log file", filename);
  704. }
  705. #endif
  706. char deffacility[8];
  707. snprintfz(deffacility,7,"%s","daemon");
  708. facility_log = config_get(CONFIG_SECTION_LOGS, "facility", deffacility);
  709. error_log_throttle_period = config_get_number(CONFIG_SECTION_LOGS, "errors flood protection period", error_log_throttle_period);
  710. error_log_errors_per_period = (unsigned long)config_get_number(CONFIG_SECTION_LOGS, "errors to trigger flood protection", (long long int)error_log_errors_per_period);
  711. error_log_errors_per_period_backup = error_log_errors_per_period;
  712. setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get(CONFIG_SECTION_LOGS, "errors flood protection period" , ""), 1);
  713. setenv("NETDATA_ERRORS_PER_PERIOD", config_get(CONFIG_SECTION_LOGS, "errors to trigger flood protection", ""), 1);
  714. char *selected_level = config_get(CONFIG_SECTION_LOGS, "severity level", NETDATA_LOG_LEVEL_INFO_STR);
  715. global_log_severity_level = log_severity_string_to_severity_level(selected_level);
  716. setenv("NETDATA_LOG_SEVERITY_LEVEL", selected_level , 1);
  717. }
  718. char *initialize_lock_directory_path(char *prefix)
  719. {
  720. char filename[FILENAME_MAX + 1];
  721. snprintfz(filename, FILENAME_MAX, "%s/lock", prefix);
  722. return config_get(CONFIG_SECTION_DIRECTORIES, "lock", filename);
  723. }
  724. static void backwards_compatible_config() {
  725. // move [global] options to the [web] section
  726. config_move(CONFIG_SECTION_GLOBAL, "http port listen backlog",
  727. CONFIG_SECTION_WEB, "listen backlog");
  728. config_move(CONFIG_SECTION_GLOBAL, "bind socket to IP",
  729. CONFIG_SECTION_WEB, "bind to");
  730. config_move(CONFIG_SECTION_GLOBAL, "bind to",
  731. CONFIG_SECTION_WEB, "bind to");
  732. config_move(CONFIG_SECTION_GLOBAL, "port",
  733. CONFIG_SECTION_WEB, "default port");
  734. config_move(CONFIG_SECTION_GLOBAL, "default port",
  735. CONFIG_SECTION_WEB, "default port");
  736. config_move(CONFIG_SECTION_GLOBAL, "disconnect idle web clients after seconds",
  737. CONFIG_SECTION_WEB, "disconnect idle clients after seconds");
  738. config_move(CONFIG_SECTION_GLOBAL, "respect web browser do not track policy",
  739. CONFIG_SECTION_WEB, "respect do not track policy");
  740. config_move(CONFIG_SECTION_GLOBAL, "web x-frame-options header",
  741. CONFIG_SECTION_WEB, "x-frame-options response header");
  742. config_move(CONFIG_SECTION_GLOBAL, "enable web responses gzip compression",
  743. CONFIG_SECTION_WEB, "enable gzip compression");
  744. config_move(CONFIG_SECTION_GLOBAL, "web compression strategy",
  745. CONFIG_SECTION_WEB, "gzip compression strategy");
  746. config_move(CONFIG_SECTION_GLOBAL, "web compression level",
  747. CONFIG_SECTION_WEB, "gzip compression level");
  748. config_move(CONFIG_SECTION_GLOBAL, "config directory",
  749. CONFIG_SECTION_DIRECTORIES, "config");
  750. config_move(CONFIG_SECTION_GLOBAL, "stock config directory",
  751. CONFIG_SECTION_DIRECTORIES, "stock config");
  752. config_move(CONFIG_SECTION_GLOBAL, "log directory",
  753. CONFIG_SECTION_DIRECTORIES, "log");
  754. config_move(CONFIG_SECTION_GLOBAL, "web files directory",
  755. CONFIG_SECTION_DIRECTORIES, "web");
  756. config_move(CONFIG_SECTION_GLOBAL, "cache directory",
  757. CONFIG_SECTION_DIRECTORIES, "cache");
  758. config_move(CONFIG_SECTION_GLOBAL, "lib directory",
  759. CONFIG_SECTION_DIRECTORIES, "lib");
  760. config_move(CONFIG_SECTION_GLOBAL, "home directory",
  761. CONFIG_SECTION_DIRECTORIES, "home");
  762. config_move(CONFIG_SECTION_GLOBAL, "lock directory",
  763. CONFIG_SECTION_DIRECTORIES, "lock");
  764. config_move(CONFIG_SECTION_GLOBAL, "plugins directory",
  765. CONFIG_SECTION_DIRECTORIES, "plugins");
  766. config_move(CONFIG_SECTION_HEALTH, "health configuration directory",
  767. CONFIG_SECTION_DIRECTORIES, "health config");
  768. config_move(CONFIG_SECTION_HEALTH, "stock health configuration directory",
  769. CONFIG_SECTION_DIRECTORIES, "stock health config");
  770. config_move(CONFIG_SECTION_REGISTRY, "registry db directory",
  771. CONFIG_SECTION_DIRECTORIES, "registry");
  772. config_move(CONFIG_SECTION_GLOBAL, "debug log",
  773. CONFIG_SECTION_LOGS, "debug");
  774. config_move(CONFIG_SECTION_GLOBAL, "error log",
  775. CONFIG_SECTION_LOGS, "error");
  776. config_move(CONFIG_SECTION_GLOBAL, "access log",
  777. CONFIG_SECTION_LOGS, "access");
  778. config_move(CONFIG_SECTION_GLOBAL, "facility log",
  779. CONFIG_SECTION_LOGS, "facility");
  780. config_move(CONFIG_SECTION_GLOBAL, "errors flood protection period",
  781. CONFIG_SECTION_LOGS, "errors flood protection period");
  782. config_move(CONFIG_SECTION_GLOBAL, "errors to trigger flood protection",
  783. CONFIG_SECTION_LOGS, "errors to trigger flood protection");
  784. config_move(CONFIG_SECTION_GLOBAL, "debug flags",
  785. CONFIG_SECTION_LOGS, "debug flags");
  786. config_move(CONFIG_SECTION_GLOBAL, "TZ environment variable",
  787. CONFIG_SECTION_ENV_VARS, "TZ");
  788. config_move(CONFIG_SECTION_PLUGINS, "PATH environment variable",
  789. CONFIG_SECTION_ENV_VARS, "PATH");
  790. config_move(CONFIG_SECTION_PLUGINS, "PYTHONPATH environment variable",
  791. CONFIG_SECTION_ENV_VARS, "PYTHONPATH");
  792. config_move(CONFIG_SECTION_STATSD, "enabled",
  793. CONFIG_SECTION_PLUGINS, "statsd");
  794. config_move(CONFIG_SECTION_GLOBAL, "memory mode",
  795. CONFIG_SECTION_DB, "mode");
  796. config_move(CONFIG_SECTION_GLOBAL, "history",
  797. CONFIG_SECTION_DB, "retention");
  798. config_move(CONFIG_SECTION_GLOBAL, "update every",
  799. CONFIG_SECTION_DB, "update every");
  800. config_move(CONFIG_SECTION_GLOBAL, "page cache size",
  801. CONFIG_SECTION_DB, "dbengine page cache size MB");
  802. config_move(CONFIG_SECTION_DB, "page cache size",
  803. CONFIG_SECTION_DB, "dbengine page cache size MB");
  804. config_move(CONFIG_SECTION_GLOBAL, "page cache uses malloc",
  805. CONFIG_SECTION_DB, "dbengine page cache with malloc");
  806. config_move(CONFIG_SECTION_DB, "page cache with malloc",
  807. CONFIG_SECTION_DB, "dbengine page cache with malloc");
  808. config_move(CONFIG_SECTION_GLOBAL, "dbengine disk space",
  809. CONFIG_SECTION_DB, "dbengine disk space MB");
  810. config_move(CONFIG_SECTION_GLOBAL, "dbengine multihost disk space",
  811. CONFIG_SECTION_DB, "dbengine multihost disk space MB");
  812. config_move(CONFIG_SECTION_GLOBAL, "memory deduplication (ksm)",
  813. CONFIG_SECTION_DB, "memory deduplication (ksm)");
  814. config_move(CONFIG_SECTION_GLOBAL, "dbengine page fetch timeout",
  815. CONFIG_SECTION_DB, "dbengine page fetch timeout secs");
  816. config_move(CONFIG_SECTION_GLOBAL, "dbengine page fetch retries",
  817. CONFIG_SECTION_DB, "dbengine page fetch retries");
  818. config_move(CONFIG_SECTION_GLOBAL, "dbengine extent pages",
  819. CONFIG_SECTION_DB, "dbengine pages per extent");
  820. config_move(CONFIG_SECTION_GLOBAL, "cleanup obsolete charts after seconds",
  821. CONFIG_SECTION_DB, "cleanup obsolete charts after secs");
  822. config_move(CONFIG_SECTION_GLOBAL, "gap when lost iterations above",
  823. CONFIG_SECTION_DB, "gap when lost iterations above");
  824. config_move(CONFIG_SECTION_GLOBAL, "cleanup orphan hosts after seconds",
  825. CONFIG_SECTION_DB, "cleanup orphan hosts after secs");
  826. config_move(CONFIG_SECTION_GLOBAL, "delete obsolete charts files",
  827. CONFIG_SECTION_DB, "delete obsolete charts files");
  828. config_move(CONFIG_SECTION_GLOBAL, "delete orphan hosts files",
  829. CONFIG_SECTION_DB, "delete orphan hosts files");
  830. config_move(CONFIG_SECTION_GLOBAL, "enable zero metrics",
  831. CONFIG_SECTION_DB, "enable zero metrics");
  832. }
  833. static void get_netdata_configured_variables() {
  834. backwards_compatible_config();
  835. // ------------------------------------------------------------------------
  836. // get the hostname
  837. char buf[HOSTNAME_MAX + 1];
  838. if(gethostname(buf, HOSTNAME_MAX) == -1){
  839. netdata_log_error("Cannot get machine hostname.");
  840. }
  841. netdata_configured_hostname = config_get(CONFIG_SECTION_GLOBAL, "hostname", buf);
  842. netdata_log_debug(D_OPTIONS, "hostname set to '%s'", netdata_configured_hostname);
  843. // ------------------------------------------------------------------------
  844. // get default database update frequency
  845. default_rrd_update_every = (int) config_get_number(CONFIG_SECTION_DB, "update every", UPDATE_EVERY);
  846. if(default_rrd_update_every < 1 || default_rrd_update_every > 600) {
  847. netdata_log_error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", default_rrd_update_every, UPDATE_EVERY);
  848. default_rrd_update_every = UPDATE_EVERY;
  849. config_set_number(CONFIG_SECTION_DB, "update every", default_rrd_update_every);
  850. }
  851. // ------------------------------------------------------------------------
  852. // get default memory mode for the database
  853. {
  854. const char *mode = config_get(CONFIG_SECTION_DB, "mode", rrd_memory_mode_name(default_rrd_memory_mode));
  855. default_rrd_memory_mode = rrd_memory_mode_id(mode);
  856. if(strcmp(mode, rrd_memory_mode_name(default_rrd_memory_mode)) != 0) {
  857. netdata_log_error("Invalid memory mode '%s' given. Using '%s'", mode, rrd_memory_mode_name(default_rrd_memory_mode));
  858. config_set(CONFIG_SECTION_DB, "mode", rrd_memory_mode_name(default_rrd_memory_mode));
  859. }
  860. }
  861. // ------------------------------------------------------------------------
  862. // get default database size
  863. if(default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE && default_rrd_memory_mode != RRD_MEMORY_MODE_NONE) {
  864. default_rrd_history_entries = (int)config_get_number(
  865. CONFIG_SECTION_DB, "retention",
  866. align_entries_to_pagesize(default_rrd_memory_mode, RRD_DEFAULT_HISTORY_ENTRIES));
  867. long h = align_entries_to_pagesize(default_rrd_memory_mode, default_rrd_history_entries);
  868. if (h != default_rrd_history_entries) {
  869. config_set_number(CONFIG_SECTION_DB, "retention", h);
  870. default_rrd_history_entries = (int)h;
  871. }
  872. }
  873. // ------------------------------------------------------------------------
  874. // get system paths
  875. netdata_configured_user_config_dir = config_get(CONFIG_SECTION_DIRECTORIES, "config", netdata_configured_user_config_dir);
  876. netdata_configured_stock_config_dir = config_get(CONFIG_SECTION_DIRECTORIES, "stock config", netdata_configured_stock_config_dir);
  877. netdata_configured_log_dir = config_get(CONFIG_SECTION_DIRECTORIES, "log", netdata_configured_log_dir);
  878. netdata_configured_web_dir = config_get(CONFIG_SECTION_DIRECTORIES, "web", netdata_configured_web_dir);
  879. netdata_configured_cache_dir = config_get(CONFIG_SECTION_DIRECTORIES, "cache", netdata_configured_cache_dir);
  880. netdata_configured_varlib_dir = config_get(CONFIG_SECTION_DIRECTORIES, "lib", netdata_configured_varlib_dir);
  881. char *env_home=getenv("HOME");
  882. netdata_configured_home_dir = config_get(CONFIG_SECTION_DIRECTORIES, "home", env_home?env_home:netdata_configured_home_dir);
  883. netdata_configured_lock_dir = initialize_lock_directory_path(netdata_configured_varlib_dir);
  884. {
  885. pluginsd_initialize_plugin_directories();
  886. netdata_configured_primary_plugins_dir = plugin_directories[PLUGINSD_STOCK_PLUGINS_DIRECTORY_PATH];
  887. }
  888. #ifdef ENABLE_DBENGINE
  889. // ------------------------------------------------------------------------
  890. // get default Database Engine page cache size in MiB
  891. default_rrdeng_page_cache_mb = (int) config_get_number(CONFIG_SECTION_DB, "dbengine page cache size MB", default_rrdeng_page_cache_mb);
  892. default_rrdeng_extent_cache_mb = (int) config_get_number(CONFIG_SECTION_DB, "dbengine extent cache size MB", default_rrdeng_extent_cache_mb);
  893. db_engine_journal_check = config_get_boolean(CONFIG_SECTION_DB, "dbengine enable journal integrity check", CONFIG_BOOLEAN_NO);
  894. if(default_rrdeng_extent_cache_mb < 0)
  895. default_rrdeng_extent_cache_mb = 0;
  896. if(default_rrdeng_page_cache_mb < RRDENG_MIN_PAGE_CACHE_SIZE_MB) {
  897. netdata_log_error("Invalid page cache size %d given. Defaulting to %d.", default_rrdeng_page_cache_mb, RRDENG_MIN_PAGE_CACHE_SIZE_MB);
  898. default_rrdeng_page_cache_mb = RRDENG_MIN_PAGE_CACHE_SIZE_MB;
  899. config_set_number(CONFIG_SECTION_DB, "dbengine page cache size MB", default_rrdeng_page_cache_mb);
  900. }
  901. // ------------------------------------------------------------------------
  902. // get default Database Engine disk space quota in MiB
  903. default_rrdeng_disk_quota_mb = (int) config_get_number(CONFIG_SECTION_DB, "dbengine disk space MB", default_rrdeng_disk_quota_mb);
  904. if(default_rrdeng_disk_quota_mb < RRDENG_MIN_DISK_SPACE_MB) {
  905. netdata_log_error("Invalid dbengine disk space %d given. Defaulting to %d.", default_rrdeng_disk_quota_mb, RRDENG_MIN_DISK_SPACE_MB);
  906. default_rrdeng_disk_quota_mb = RRDENG_MIN_DISK_SPACE_MB;
  907. config_set_number(CONFIG_SECTION_DB, "dbengine disk space MB", default_rrdeng_disk_quota_mb);
  908. }
  909. default_multidb_disk_quota_mb = (int) config_get_number(CONFIG_SECTION_DB, "dbengine multihost disk space MB", compute_multidb_diskspace());
  910. if(default_multidb_disk_quota_mb < RRDENG_MIN_DISK_SPACE_MB) {
  911. netdata_log_error("Invalid multidb disk space %d given. Defaulting to %d.", default_multidb_disk_quota_mb, default_rrdeng_disk_quota_mb);
  912. default_multidb_disk_quota_mb = default_rrdeng_disk_quota_mb;
  913. config_set_number(CONFIG_SECTION_DB, "dbengine multihost disk space MB", default_multidb_disk_quota_mb);
  914. }
  915. #else
  916. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE) {
  917. error_report("RRD_MEMORY_MODE_DBENGINE is not supported in this platform. The agent will use db mode 'save' instead.");
  918. default_rrd_memory_mode = RRD_MEMORY_MODE_SAVE;
  919. }
  920. #endif
  921. // ------------------------------------------------------------------------
  922. netdata_configured_host_prefix = config_get(CONFIG_SECTION_GLOBAL, "host access prefix", "");
  923. verify_netdata_host_prefix();
  924. // --------------------------------------------------------------------
  925. // get KSM settings
  926. #ifdef MADV_MERGEABLE
  927. enable_ksm = config_get_boolean(CONFIG_SECTION_DB, "memory deduplication (ksm)", enable_ksm);
  928. #endif
  929. // --------------------------------------------------------------------
  930. // metric correlations
  931. enable_metric_correlations = config_get_boolean(CONFIG_SECTION_GLOBAL, "enable metric correlations", enable_metric_correlations);
  932. default_metric_correlations_method = weights_string_to_method(config_get(
  933. CONFIG_SECTION_GLOBAL, "metric correlations method",
  934. weights_method_to_string(default_metric_correlations_method)));
  935. // --------------------------------------------------------------------
  936. rrdset_free_obsolete_time_s = config_get_number(CONFIG_SECTION_DB, "cleanup obsolete charts after secs", rrdset_free_obsolete_time_s);
  937. // Current chart locking and invalidation scheme doesn't prevent Netdata from segmentation faults if a short
  938. // cleanup delay is set. Extensive stress tests showed that 10 seconds is quite a safe delay. Look at
  939. // https://github.com/netdata/netdata/pull/11222#issuecomment-868367920 for more information.
  940. if (rrdset_free_obsolete_time_s < 10) {
  941. rrdset_free_obsolete_time_s = 10;
  942. netdata_log_info("The \"cleanup obsolete charts after seconds\" option was set to 10 seconds.");
  943. config_set_number(CONFIG_SECTION_DB, "cleanup obsolete charts after secs", rrdset_free_obsolete_time_s);
  944. }
  945. gap_when_lost_iterations_above = (int)config_get_number(CONFIG_SECTION_DB, "gap when lost iterations above", gap_when_lost_iterations_above);
  946. if (gap_when_lost_iterations_above < 1) {
  947. gap_when_lost_iterations_above = 1;
  948. config_set_number(CONFIG_SECTION_DB, "gap when lost iterations above", gap_when_lost_iterations_above);
  949. }
  950. gap_when_lost_iterations_above += 2;
  951. // --------------------------------------------------------------------
  952. // get various system parameters
  953. get_system_HZ();
  954. get_system_cpus_uncached();
  955. get_system_pid_max();
  956. }
  957. static void post_conf_load(char **user)
  958. {
  959. // --------------------------------------------------------------------
  960. // get the user we should run
  961. // IMPORTANT: this is required before web_files_uid()
  962. if(getuid() == 0) {
  963. *user = config_get(CONFIG_SECTION_GLOBAL, "run as user", NETDATA_USER);
  964. }
  965. else {
  966. struct passwd *passwd = getpwuid(getuid());
  967. *user = config_get(CONFIG_SECTION_GLOBAL, "run as user", (passwd && passwd->pw_name)?passwd->pw_name:"");
  968. }
  969. }
  970. static bool load_netdata_conf(char *filename, char overwrite_used, char **user) {
  971. errno = 0;
  972. int ret = 0;
  973. if(filename && *filename) {
  974. ret = config_load(filename, overwrite_used, NULL);
  975. if(!ret)
  976. netdata_log_error("CONFIG: cannot load config file '%s'.", filename);
  977. }
  978. else {
  979. filename = strdupz_path_subpath(netdata_configured_user_config_dir, "netdata.conf");
  980. ret = config_load(filename, overwrite_used, NULL);
  981. if(!ret) {
  982. netdata_log_info("CONFIG: cannot load user config '%s'. Will try the stock version.", filename);
  983. freez(filename);
  984. filename = strdupz_path_subpath(netdata_configured_stock_config_dir, "netdata.conf");
  985. ret = config_load(filename, overwrite_used, NULL);
  986. if(!ret)
  987. netdata_log_info("CONFIG: cannot load stock config '%s'. Running with internal defaults.", filename);
  988. }
  989. freez(filename);
  990. }
  991. post_conf_load(user);
  992. return ret;
  993. }
  994. // coverity[ +tainted_string_sanitize_content : arg-0 ]
  995. static inline void coverity_remove_taint(char *s)
  996. {
  997. (void)s;
  998. }
  999. int get_system_info(struct rrdhost_system_info *system_info, bool log) {
  1000. char *script;
  1001. script = mallocz(sizeof(char) * (strlen(netdata_configured_primary_plugins_dir) + strlen("system-info.sh") + 2));
  1002. sprintf(script, "%s/%s", netdata_configured_primary_plugins_dir, "system-info.sh");
  1003. if (unlikely(access(script, R_OK) != 0)) {
  1004. netdata_log_error("System info script %s not found.",script);
  1005. freez(script);
  1006. return 1;
  1007. }
  1008. pid_t command_pid;
  1009. FILE *fp_child_input;
  1010. FILE *fp_child_output = netdata_popen(script, &command_pid, &fp_child_input);
  1011. if(fp_child_output) {
  1012. char line[200 + 1];
  1013. // Removed the double strlens, if the Coverity tainted string warning reappears I'll revert.
  1014. // One time init code, but I'm curious about the warning...
  1015. while (fgets(line, 200, fp_child_output) != NULL) {
  1016. char *value=line;
  1017. while (*value && *value != '=') value++;
  1018. if (*value=='=') {
  1019. *value='\0';
  1020. value++;
  1021. char *end = value;
  1022. while (*end && *end != '\n') end++;
  1023. *end = '\0'; // Overwrite newline if present
  1024. coverity_remove_taint(line); // I/O is controlled result of system_info.sh - not tainted
  1025. coverity_remove_taint(value);
  1026. if(unlikely(rrdhost_set_system_info_variable(system_info, line, value))) {
  1027. netdata_log_error("Unexpected environment variable %s=%s", line, value);
  1028. }
  1029. else {
  1030. if(log)
  1031. netdata_log_info("%s=%s", line, value);
  1032. setenv(line, value, 1);
  1033. }
  1034. }
  1035. }
  1036. netdata_pclose(fp_child_input, fp_child_output, command_pid);
  1037. }
  1038. freez(script);
  1039. return 0;
  1040. }
  1041. void set_silencers_filename() {
  1042. char filename[FILENAME_MAX + 1];
  1043. snprintfz(filename, FILENAME_MAX, "%s/health.silencers.json", netdata_configured_varlib_dir);
  1044. silencers_filename = config_get(CONFIG_SECTION_HEALTH, "silencers file", filename);
  1045. }
  1046. /* Any config setting that can be accessed without a default value i.e. configget(...,...,NULL) *MUST*
  1047. be set in this procedure to be called in all the relevant code paths.
  1048. */
  1049. #define delta_startup_time(msg) \
  1050. { \
  1051. usec_t now_ut = now_monotonic_usec(); \
  1052. if(prev_msg) \
  1053. netdata_log_info("NETDATA STARTUP: in %7llu ms, %s - next: %s", (now_ut - last_ut) / USEC_PER_MS, prev_msg, msg); \
  1054. else \
  1055. netdata_log_info("NETDATA STARTUP: next: %s", msg); \
  1056. last_ut = now_ut; \
  1057. prev_msg = msg; \
  1058. }
  1059. int buffer_unittest(void);
  1060. int pgc_unittest(void);
  1061. int mrg_unittest(void);
  1062. int julytest(void);
  1063. int pluginsd_parser_unittest(void);
  1064. void replication_initialize(void);
  1065. void bearer_tokens_init(void);
  1066. int main(int argc, char **argv) {
  1067. // initialize the system clocks
  1068. clocks_init();
  1069. netdata_start_time = now_realtime_sec();
  1070. usec_t started_ut = now_monotonic_usec();
  1071. usec_t last_ut = started_ut;
  1072. const char *prev_msg = NULL;
  1073. // Initialize stderror avoiding coredump when netdata_log_info() or netdata_log_error() is called
  1074. stderror = stderr;
  1075. int i;
  1076. int config_loaded = 0;
  1077. int dont_fork = 0;
  1078. bool close_open_fds = true;
  1079. size_t default_stacksize;
  1080. char *user = NULL;
  1081. static_threads = static_threads_get();
  1082. netdata_ready = false;
  1083. // set the name for logging
  1084. program_name = "netdata";
  1085. if (argc > 1 && strcmp(argv[1], SPAWN_SERVER_COMMAND_LINE_ARGUMENT) == 0) {
  1086. // don't run netdata, this is the spawn server
  1087. spawn_server();
  1088. exit(0);
  1089. }
  1090. // parse options
  1091. {
  1092. int num_opts = sizeof(option_definitions) / sizeof(struct option_def);
  1093. char optstring[(num_opts * 2) + 1];
  1094. int string_i = 0;
  1095. for( i = 0; i < num_opts; i++ ) {
  1096. optstring[string_i] = option_definitions[i].val;
  1097. string_i++;
  1098. if(option_definitions[i].arg_name) {
  1099. optstring[string_i] = ':';
  1100. string_i++;
  1101. }
  1102. }
  1103. // terminate optstring
  1104. optstring[string_i] ='\0';
  1105. optstring[(num_opts *2)] ='\0';
  1106. int opt;
  1107. while( (opt = getopt(argc, argv, optstring)) != -1 ) {
  1108. switch(opt) {
  1109. case 'c':
  1110. if(!load_netdata_conf(optarg, 1, &user)) {
  1111. netdata_log_error("Cannot load configuration file %s.", optarg);
  1112. return 1;
  1113. }
  1114. else {
  1115. netdata_log_debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
  1116. load_cloud_conf(1);
  1117. config_loaded = 1;
  1118. }
  1119. break;
  1120. case 'D':
  1121. dont_fork = 1;
  1122. break;
  1123. case 'd':
  1124. dont_fork = 0;
  1125. break;
  1126. case 'h':
  1127. return help(0);
  1128. case 'i':
  1129. config_set(CONFIG_SECTION_WEB, "bind to", optarg);
  1130. break;
  1131. case 'P':
  1132. strncpy(pidfile, optarg, FILENAME_MAX);
  1133. pidfile[FILENAME_MAX] = '\0';
  1134. break;
  1135. case 'p':
  1136. config_set(CONFIG_SECTION_GLOBAL, "default port", optarg);
  1137. break;
  1138. case 's':
  1139. config_set(CONFIG_SECTION_GLOBAL, "host access prefix", optarg);
  1140. break;
  1141. case 't':
  1142. config_set(CONFIG_SECTION_GLOBAL, "update every", optarg);
  1143. break;
  1144. case 'u':
  1145. config_set(CONFIG_SECTION_GLOBAL, "run as user", optarg);
  1146. break;
  1147. case 'v':
  1148. case 'V':
  1149. printf("%s %s\n", program_name, program_version);
  1150. return 0;
  1151. case 'W':
  1152. {
  1153. char* stacksize_string = "stacksize=";
  1154. char* debug_flags_string = "debug_flags=";
  1155. char* claim_string = "claim";
  1156. #ifdef ENABLE_DBENGINE
  1157. char* createdataset_string = "createdataset=";
  1158. char* stresstest_string = "stresstest=";
  1159. #endif
  1160. if(strcmp(optarg, "sqlite-meta-recover") == 0) {
  1161. sql_init_database(DB_CHECK_RECOVER, 0);
  1162. return 0;
  1163. }
  1164. if(strcmp(optarg, "sqlite-compact") == 0) {
  1165. sql_init_database(DB_CHECK_RECLAIM_SPACE, 0);
  1166. return 0;
  1167. }
  1168. if(strcmp(optarg, "unittest") == 0) {
  1169. unittest_running = true;
  1170. if (pluginsd_parser_unittest())
  1171. return 1;
  1172. if (unit_test_static_threads())
  1173. return 1;
  1174. if (unit_test_buffer())
  1175. return 1;
  1176. if (unit_test_str2ld())
  1177. return 1;
  1178. if (buffer_unittest())
  1179. return 1;
  1180. if (unit_test_bitmaps())
  1181. return 1;
  1182. // No call to load the config file on this code-path
  1183. post_conf_load(&user);
  1184. get_netdata_configured_variables();
  1185. default_rrd_update_every = 1;
  1186. default_rrd_memory_mode = RRD_MEMORY_MODE_RAM;
  1187. default_health_enabled = 0;
  1188. storage_tiers = 1;
  1189. registry_init();
  1190. if(rrd_init("unittest", NULL, true)) {
  1191. fprintf(stderr, "rrd_init failed for unittest\n");
  1192. return 1;
  1193. }
  1194. default_rrdpush_enabled = 0;
  1195. if(run_all_mockup_tests()) return 1;
  1196. if(unit_test_storage()) return 1;
  1197. #ifdef ENABLE_DBENGINE
  1198. if(test_dbengine()) return 1;
  1199. #endif
  1200. if(test_sqlite()) return 1;
  1201. if(string_unittest(10000)) return 1;
  1202. if (dictionary_unittest(10000))
  1203. return 1;
  1204. if(aral_unittest(10000))
  1205. return 1;
  1206. if (rrdlabels_unittest())
  1207. return 1;
  1208. if (ctx_unittest())
  1209. return 1;
  1210. fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
  1211. return 0;
  1212. }
  1213. else if(strcmp(optarg, "escapetest") == 0) {
  1214. return command_argument_sanitization_tests();
  1215. }
  1216. else if(strcmp(optarg, "dicttest") == 0) {
  1217. unittest_running = true;
  1218. return dictionary_unittest(10000);
  1219. }
  1220. else if(strcmp(optarg, "araltest") == 0) {
  1221. unittest_running = true;
  1222. return aral_unittest(10000);
  1223. }
  1224. else if(strcmp(optarg, "stringtest") == 0) {
  1225. unittest_running = true;
  1226. return string_unittest(10000);
  1227. }
  1228. else if(strcmp(optarg, "rrdlabelstest") == 0) {
  1229. unittest_running = true;
  1230. return rrdlabels_unittest();
  1231. }
  1232. else if(strcmp(optarg, "buffertest") == 0) {
  1233. unittest_running = true;
  1234. return buffer_unittest();
  1235. }
  1236. #ifdef ENABLE_DBENGINE
  1237. else if(strcmp(optarg, "mctest") == 0) {
  1238. unittest_running = true;
  1239. return mc_unittest();
  1240. }
  1241. else if(strcmp(optarg, "ctxtest") == 0) {
  1242. unittest_running = true;
  1243. return ctx_unittest();
  1244. }
  1245. else if(strcmp(optarg, "metatest") == 0) {
  1246. unittest_running = true;
  1247. return metadata_unittest();
  1248. }
  1249. else if(strcmp(optarg, "pgctest") == 0) {
  1250. unittest_running = true;
  1251. return pgc_unittest();
  1252. }
  1253. else if(strcmp(optarg, "mrgtest") == 0) {
  1254. unittest_running = true;
  1255. return mrg_unittest();
  1256. }
  1257. else if(strcmp(optarg, "julytest") == 0) {
  1258. unittest_running = true;
  1259. return julytest();
  1260. }
  1261. else if(strcmp(optarg, "parsertest") == 0) {
  1262. unittest_running = true;
  1263. return pluginsd_parser_unittest();
  1264. }
  1265. else if(strncmp(optarg, createdataset_string, strlen(createdataset_string)) == 0) {
  1266. optarg += strlen(createdataset_string);
  1267. unsigned history_seconds = strtoul(optarg, NULL, 0);
  1268. post_conf_load(&user);
  1269. get_netdata_configured_variables();
  1270. default_rrd_update_every = 1;
  1271. registry_init();
  1272. if(rrd_init("dbengine-dataset", NULL, true)) {
  1273. fprintf(stderr, "rrd_init failed for unittest\n");
  1274. return 1;
  1275. }
  1276. generate_dbengine_dataset(history_seconds);
  1277. return 0;
  1278. }
  1279. else if(strncmp(optarg, stresstest_string, strlen(stresstest_string)) == 0) {
  1280. char *endptr;
  1281. unsigned test_duration_sec = 0, dset_charts = 0, query_threads = 0, ramp_up_seconds = 0,
  1282. page_cache_mb = 0, disk_space_mb = 0, workers = 16;
  1283. optarg += strlen(stresstest_string);
  1284. test_duration_sec = (unsigned)strtoul(optarg, &endptr, 0);
  1285. if (',' == *endptr)
  1286. dset_charts = (unsigned)strtoul(endptr + 1, &endptr, 0);
  1287. if (',' == *endptr)
  1288. query_threads = (unsigned)strtoul(endptr + 1, &endptr, 0);
  1289. if (',' == *endptr)
  1290. ramp_up_seconds = (unsigned)strtoul(endptr + 1, &endptr, 0);
  1291. if (',' == *endptr)
  1292. page_cache_mb = (unsigned)strtoul(endptr + 1, &endptr, 0);
  1293. if (',' == *endptr)
  1294. disk_space_mb = (unsigned)strtoul(endptr + 1, &endptr, 0);
  1295. if (',' == *endptr)
  1296. workers = (unsigned)strtoul(endptr + 1, &endptr, 0);
  1297. if (workers > 1024)
  1298. workers = 1024;
  1299. char workers_str[16];
  1300. snprintf(workers_str, 15, "%u", workers);
  1301. setenv("UV_THREADPOOL_SIZE", workers_str, 1);
  1302. dbengine_stress_test(test_duration_sec, dset_charts, query_threads, ramp_up_seconds,
  1303. page_cache_mb, disk_space_mb);
  1304. return 0;
  1305. }
  1306. #endif
  1307. else if(strcmp(optarg, "simple-pattern") == 0) {
  1308. if(optind + 2 > argc) {
  1309. fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
  1310. " Checks if 'pattern' matches the given 'string'.\n"
  1311. " - 'pattern' can be one or more space separated words.\n"
  1312. " - each 'word' can contain one or more asterisks.\n"
  1313. " - words starting with '!' give negative matches.\n"
  1314. " - words are processed left to right\n"
  1315. "\n"
  1316. "Examples:\n"
  1317. "\n"
  1318. " > match all veth interfaces, except veth0:\n"
  1319. "\n"
  1320. " -W simple-pattern '!veth0 veth*' 'veth12'\n"
  1321. "\n"
  1322. "\n"
  1323. " > match all *.ext files directly in /path/:\n"
  1324. " (this will not match *.ext files in a subdir of /path/)\n"
  1325. "\n"
  1326. " -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
  1327. "\n"
  1328. );
  1329. return 1;
  1330. }
  1331. const char *haystack = argv[optind];
  1332. const char *needle = argv[optind + 1];
  1333. size_t len = strlen(needle) + 1;
  1334. char wildcarded[len];
  1335. SIMPLE_PATTERN *p = simple_pattern_create(haystack, NULL, SIMPLE_PATTERN_EXACT, true);
  1336. SIMPLE_PATTERN_RESULT ret = simple_pattern_matches_extract(p, needle, wildcarded, len);
  1337. simple_pattern_free(p);
  1338. if(ret == SP_MATCHED_POSITIVE) {
  1339. fprintf(stdout, "RESULT: POSITIVE MATCHED - pattern '%s' matches '%s', wildcarded '%s'\n", haystack, needle, wildcarded);
  1340. return 0;
  1341. }
  1342. else if(ret == SP_MATCHED_NEGATIVE) {
  1343. fprintf(stdout, "RESULT: NEGATIVE MATCHED - pattern '%s' matches '%s', wildcarded '%s'\n", haystack, needle, wildcarded);
  1344. return 0;
  1345. }
  1346. else {
  1347. fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s', wildcarded '%s'\n", haystack, needle, wildcarded);
  1348. return 1;
  1349. }
  1350. }
  1351. else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
  1352. optarg += strlen(stacksize_string);
  1353. config_set(CONFIG_SECTION_GLOBAL, "pthread stack size", optarg);
  1354. }
  1355. else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
  1356. optarg += strlen(debug_flags_string);
  1357. config_set(CONFIG_SECTION_LOGS, "debug flags", optarg);
  1358. debug_flags = strtoull(optarg, NULL, 0);
  1359. }
  1360. else if(strcmp(optarg, "set") == 0) {
  1361. if(optind + 3 > argc) {
  1362. fprintf(stderr, "%s", "\nUSAGE: -W set 'section' 'key' 'value'\n\n"
  1363. " Overwrites settings of netdata.conf.\n"
  1364. "\n"
  1365. " These options interact with: -c netdata.conf\n"
  1366. " If -c netdata.conf is given on the command line,\n"
  1367. " before -W set... the user may overwrite command\n"
  1368. " line parameters at netdata.conf\n"
  1369. " If -c netdata.conf is given after (or missing)\n"
  1370. " -W set... the user cannot overwrite the command line\n"
  1371. " parameters."
  1372. "\n"
  1373. );
  1374. return 1;
  1375. }
  1376. const char *section = argv[optind];
  1377. const char *key = argv[optind + 1];
  1378. const char *value = argv[optind + 2];
  1379. optind += 3;
  1380. // set this one as the default
  1381. // only if it is not already set in the config file
  1382. // so the caller can use -c netdata.conf before or
  1383. // after this parameter to prevent or allow overwriting
  1384. // variables at netdata.conf
  1385. config_set_default(section, key, value);
  1386. // fprintf(stderr, "SET section '%s', key '%s', value '%s'\n", section, key, value);
  1387. }
  1388. else if(strcmp(optarg, "set2") == 0) {
  1389. if(optind + 4 > argc) {
  1390. fprintf(stderr, "%s", "\nUSAGE: -W set 'conf_file' 'section' 'key' 'value'\n\n"
  1391. " Overwrites settings of netdata.conf or cloud.conf\n"
  1392. "\n"
  1393. " These options interact with: -c netdata.conf\n"
  1394. " If -c netdata.conf is given on the command line,\n"
  1395. " before -W set... the user may overwrite command\n"
  1396. " line parameters at netdata.conf\n"
  1397. " If -c netdata.conf is given after (or missing)\n"
  1398. " -W set... the user cannot overwrite the command line\n"
  1399. " parameters."
  1400. " conf_file can be \"cloud\" or \"netdata\".\n"
  1401. "\n"
  1402. );
  1403. return 1;
  1404. }
  1405. const char *conf_file = argv[optind]; /* "cloud" is cloud.conf, otherwise netdata.conf */
  1406. struct config *tmp_config = strcmp(conf_file, "cloud") ? &netdata_config : &cloud_config;
  1407. const char *section = argv[optind + 1];
  1408. const char *key = argv[optind + 2];
  1409. const char *value = argv[optind + 3];
  1410. optind += 4;
  1411. // set this one as the default
  1412. // only if it is not already set in the config file
  1413. // so the caller can use -c netdata.conf before or
  1414. // after this parameter to prevent or allow overwriting
  1415. // variables at netdata.conf
  1416. appconfig_set_default(tmp_config, section, key, value);
  1417. // fprintf(stderr, "SET section '%s', key '%s', value '%s'\n", section, key, value);
  1418. }
  1419. else if(strcmp(optarg, "get") == 0) {
  1420. if(optind + 3 > argc) {
  1421. fprintf(stderr, "%s", "\nUSAGE: -W get 'section' 'key' 'value'\n\n"
  1422. " Prints settings of netdata.conf.\n"
  1423. "\n"
  1424. " These options interact with: -c netdata.conf\n"
  1425. " -c netdata.conf has to be given before -W get.\n"
  1426. "\n"
  1427. );
  1428. return 1;
  1429. }
  1430. if(!config_loaded) {
  1431. fprintf(stderr, "warning: no configuration file has been loaded. Use -c CONFIG_FILE, before -W get. Using default config.\n");
  1432. load_netdata_conf(NULL, 0, &user);
  1433. }
  1434. get_netdata_configured_variables();
  1435. const char *section = argv[optind];
  1436. const char *key = argv[optind + 1];
  1437. const char *def = argv[optind + 2];
  1438. const char *value = config_get(section, key, def);
  1439. printf("%s\n", value);
  1440. return 0;
  1441. }
  1442. else if(strcmp(optarg, "get2") == 0) {
  1443. if(optind + 4 > argc) {
  1444. fprintf(stderr, "%s", "\nUSAGE: -W get2 'conf_file' 'section' 'key' 'value'\n\n"
  1445. " Prints settings of netdata.conf or cloud.conf\n"
  1446. "\n"
  1447. " These options interact with: -c netdata.conf\n"
  1448. " -c netdata.conf has to be given before -W get2.\n"
  1449. " conf_file can be \"cloud\" or \"netdata\".\n"
  1450. "\n"
  1451. );
  1452. return 1;
  1453. }
  1454. if(!config_loaded) {
  1455. fprintf(stderr, "warning: no configuration file has been loaded. Use -c CONFIG_FILE, before -W get. Using default config.\n");
  1456. load_netdata_conf(NULL, 0, &user);
  1457. load_cloud_conf(1);
  1458. }
  1459. get_netdata_configured_variables();
  1460. const char *conf_file = argv[optind]; /* "cloud" is cloud.conf, otherwise netdata.conf */
  1461. struct config *tmp_config = strcmp(conf_file, "cloud") ? &netdata_config : &cloud_config;
  1462. const char *section = argv[optind + 1];
  1463. const char *key = argv[optind + 2];
  1464. const char *def = argv[optind + 3];
  1465. const char *value = appconfig_get(tmp_config, section, key, def);
  1466. printf("%s\n", value);
  1467. return 0;
  1468. }
  1469. else if(strncmp(optarg, claim_string, strlen(claim_string)) == 0) {
  1470. /* will trigger a claiming attempt when the agent is initialized */
  1471. claiming_pending_arguments = optarg + strlen(claim_string);
  1472. }
  1473. else if(strcmp(optarg, "buildinfo") == 0) {
  1474. print_build_info();
  1475. return 0;
  1476. }
  1477. else if(strcmp(optarg, "buildinfojson") == 0) {
  1478. print_build_info_json();
  1479. return 0;
  1480. }
  1481. else if(strcmp(optarg, "keepopenfds") == 0) {
  1482. // Internal dev option to skip closing inherited
  1483. // open FDs. Useful, when we want to run the agent
  1484. // under profiling tools that open/maintain their
  1485. // own FDs.
  1486. close_open_fds = false;
  1487. } else {
  1488. fprintf(stderr, "Unknown -W parameter '%s'\n", optarg);
  1489. return help(1);
  1490. }
  1491. }
  1492. break;
  1493. default: /* ? */
  1494. fprintf(stderr, "Unknown parameter '%c'\n", opt);
  1495. return help(1);
  1496. }
  1497. }
  1498. }
  1499. if (close_open_fds == true) {
  1500. // close all open file descriptors, except the standard ones
  1501. // the caller may have left open files (lxc-attach has this issue)
  1502. for_each_open_fd(OPEN_FD_ACTION_CLOSE, OPEN_FD_EXCLUDE_STDIN | OPEN_FD_EXCLUDE_STDOUT | OPEN_FD_EXCLUDE_STDERR);
  1503. }
  1504. if(!config_loaded) {
  1505. load_netdata_conf(NULL, 0, &user);
  1506. load_cloud_conf(0);
  1507. }
  1508. // ------------------------------------------------------------------------
  1509. // initialize netdata
  1510. {
  1511. char *pmax = config_get(CONFIG_SECTION_GLOBAL, "glibc malloc arena max for plugins", "1");
  1512. if(pmax && *pmax)
  1513. setenv("MALLOC_ARENA_MAX", pmax, 1);
  1514. #if defined(HAVE_C_MALLOPT)
  1515. i = (int)config_get_number(CONFIG_SECTION_GLOBAL, "glibc malloc arena max for netdata", 1);
  1516. if(i > 0)
  1517. mallopt(M_ARENA_MAX, 1);
  1518. #ifdef NETDATA_INTERNAL_CHECKS
  1519. mallopt(M_PERTURB, 0x5A);
  1520. // mallopt(M_MXFAST, 0);
  1521. #endif
  1522. #endif
  1523. // set libuv worker threads
  1524. libuv_worker_threads = (int)get_netdata_cpus() * 6;
  1525. if(libuv_worker_threads < MIN_LIBUV_WORKER_THREADS)
  1526. libuv_worker_threads = MIN_LIBUV_WORKER_THREADS;
  1527. if(libuv_worker_threads > MAX_LIBUV_WORKER_THREADS)
  1528. libuv_worker_threads = MAX_LIBUV_WORKER_THREADS;
  1529. libuv_worker_threads = config_get_number(CONFIG_SECTION_GLOBAL, "libuv worker threads", libuv_worker_threads);
  1530. if(libuv_worker_threads < MIN_LIBUV_WORKER_THREADS) {
  1531. libuv_worker_threads = MIN_LIBUV_WORKER_THREADS;
  1532. config_set_number(CONFIG_SECTION_GLOBAL, "libuv worker threads", libuv_worker_threads);
  1533. }
  1534. {
  1535. char buf[20 + 1];
  1536. snprintfz(buf, 20, "%d", libuv_worker_threads);
  1537. setenv("UV_THREADPOOL_SIZE", buf, 1);
  1538. }
  1539. // prepare configuration environment variables for the plugins
  1540. get_netdata_configured_variables();
  1541. set_global_environment();
  1542. // work while we are cd into config_dir
  1543. // to allow the plugins refer to their config
  1544. // files using relative filenames
  1545. if(chdir(netdata_configured_user_config_dir) == -1)
  1546. fatal("Cannot cd to '%s'", netdata_configured_user_config_dir);
  1547. // Get execution path before switching user to avoid permission issues
  1548. get_netdata_execution_path();
  1549. }
  1550. {
  1551. // --------------------------------------------------------------------
  1552. // get the debugging flags from the configuration file
  1553. char *flags = config_get(CONFIG_SECTION_LOGS, "debug flags", "0x0000000000000000");
  1554. setenv("NETDATA_DEBUG_FLAGS", flags, 1);
  1555. debug_flags = strtoull(flags, NULL, 0);
  1556. netdata_log_debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);
  1557. if(debug_flags != 0) {
  1558. struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
  1559. if(setrlimit(RLIMIT_CORE, &rl) != 0)
  1560. netdata_log_error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
  1561. #ifdef HAVE_SYS_PRCTL_H
  1562. prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
  1563. #endif
  1564. }
  1565. // --------------------------------------------------------------------
  1566. // get log filenames and settings
  1567. log_init();
  1568. error_log_limit_unlimited();
  1569. // initialize the log files
  1570. open_all_log_files();
  1571. netdata_log_info("Netdata agent version \""VERSION"\" is starting");
  1572. ieee754_doubles = is_system_ieee754_double();
  1573. aral_judy_init();
  1574. get_system_timezone();
  1575. bearer_tokens_init();
  1576. replication_initialize();
  1577. rrd_functions_inflight_init();
  1578. // --------------------------------------------------------------------
  1579. // get the certificate and start security
  1580. #ifdef ENABLE_HTTPS
  1581. security_init();
  1582. #endif
  1583. // --------------------------------------------------------------------
  1584. // This is the safest place to start the SILENCERS structure
  1585. set_silencers_filename();
  1586. health_initialize_global_silencers();
  1587. // --------------------------------------------------------------------
  1588. // Initialize ML configuration
  1589. delta_startup_time("initialize ML");
  1590. ml_init();
  1591. // --------------------------------------------------------------------
  1592. // setup process signals
  1593. // block signals while initializing threads.
  1594. // this causes the threads to block signals.
  1595. delta_startup_time("initialize signals");
  1596. signals_block();
  1597. signals_init(); // setup the signals we want to use
  1598. // --------------------------------------------------------------------
  1599. // check which threads are enabled and initialize them
  1600. delta_startup_time("initialize static threads");
  1601. // setup threads configs
  1602. default_stacksize = netdata_threads_init();
  1603. for (i = 0; static_threads[i].name != NULL ; i++) {
  1604. struct netdata_static_thread *st = &static_threads[i];
  1605. if(st->config_name)
  1606. st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
  1607. if(st->enabled && st->init_routine)
  1608. st->init_routine();
  1609. if(st->env_name)
  1610. setenv(st->env_name, st->enabled?"YES":"NO", 1);
  1611. if(st->global_variable)
  1612. *st->global_variable = (st->enabled) ? true : false;
  1613. }
  1614. // --------------------------------------------------------------------
  1615. // create the listening sockets
  1616. delta_startup_time("initialize web server");
  1617. web_client_api_v1_init();
  1618. web_server_threading_selection();
  1619. if(web_server_mode != WEB_SERVER_MODE_NONE)
  1620. api_listen_sockets_setup();
  1621. #ifdef ENABLE_H2O
  1622. delta_startup_time("initialize h2o server");
  1623. for (int i = 0; static_threads[i].name; i++) {
  1624. if (static_threads[i].start_routine == h2o_main)
  1625. static_threads[i].enabled = httpd_is_enabled();
  1626. }
  1627. #endif
  1628. }
  1629. delta_startup_time("set resource limits");
  1630. #ifdef NETDATA_INTERNAL_CHECKS
  1631. if(debug_flags != 0) {
  1632. struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
  1633. if(setrlimit(RLIMIT_CORE, &rl) != 0)
  1634. netdata_log_error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
  1635. #ifdef HAVE_SYS_PRCTL_H
  1636. prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
  1637. #endif
  1638. }
  1639. #endif /* NETDATA_INTERNAL_CHECKS */
  1640. set_nofile_limit(&rlimit_nofile);
  1641. delta_startup_time("become daemon");
  1642. // fork, switch user, create pid file, set process priority
  1643. if(become_daemon(dont_fork, user) == -1)
  1644. fatal("Cannot daemonize myself.");
  1645. dyn_conf_init();
  1646. netdata_log_info("netdata started on pid %d.", getpid());
  1647. delta_startup_time("initialize threads after fork");
  1648. netdata_threads_init_after_fork((size_t)config_get_number(CONFIG_SECTION_GLOBAL, "pthread stack size", (long)default_stacksize));
  1649. // initialize internal registry
  1650. delta_startup_time("initialize registry");
  1651. registry_init();
  1652. // fork the spawn server
  1653. delta_startup_time("fork the spawn server");
  1654. spawn_init();
  1655. /*
  1656. * Libuv uv_spawn() uses SIGCHLD internally:
  1657. * https://github.com/libuv/libuv/blob/cc51217a317e96510fbb284721d5e6bc2af31e33/src/unix/process.c#L485
  1658. * and inadvertently replaces the netdata signal handler which was setup during initialization.
  1659. * Thusly, we must explicitly restore the signal handler for SIGCHLD.
  1660. * Warning: extreme care is needed when mixing and matching POSIX and libuv.
  1661. */
  1662. signals_restore_SIGCHLD();
  1663. // ------------------------------------------------------------------------
  1664. // initialize rrd, registry, health, rrdpush, etc.
  1665. delta_startup_time("collecting system info");
  1666. netdata_anonymous_statistics_enabled=-1;
  1667. struct rrdhost_system_info *system_info = callocz(1, sizeof(struct rrdhost_system_info));
  1668. __atomic_sub_fetch(&netdata_buffers_statistics.rrdhost_allocations_size, sizeof(struct rrdhost_system_info), __ATOMIC_RELAXED);
  1669. get_system_info(system_info, true);
  1670. (void) registry_get_this_machine_guid();
  1671. system_info->hops = 0;
  1672. get_install_type(&system_info->install_type, &system_info->prebuilt_arch, &system_info->prebuilt_dist);
  1673. delta_startup_time("initialize RRD structures");
  1674. if(rrd_init(netdata_configured_hostname, system_info, false)) {
  1675. set_late_global_environment(system_info);
  1676. fatal("Cannot initialize localhost instance with name '%s'.", netdata_configured_hostname);
  1677. }
  1678. delta_startup_time("check for incomplete shutdown");
  1679. char agent_crash_file[FILENAME_MAX + 1];
  1680. char agent_incomplete_shutdown_file[FILENAME_MAX + 1];
  1681. snprintfz(agent_incomplete_shutdown_file, FILENAME_MAX, "%s/.agent_incomplete_shutdown", netdata_configured_varlib_dir);
  1682. int incomplete_shutdown_detected = (unlink(agent_incomplete_shutdown_file) == 0);
  1683. snprintfz(agent_crash_file, FILENAME_MAX, "%s/.agent_crash", netdata_configured_varlib_dir);
  1684. int crash_detected = (unlink(agent_crash_file) == 0);
  1685. int fd = open(agent_crash_file, O_WRONLY | O_CREAT | O_TRUNC, 444);
  1686. if (fd >= 0)
  1687. close(fd);
  1688. // ------------------------------------------------------------------------
  1689. // Claim netdata agent to a cloud endpoint
  1690. delta_startup_time("collect claiming info");
  1691. if (claiming_pending_arguments)
  1692. claim_agent(claiming_pending_arguments, false, NULL);
  1693. load_claiming_state();
  1694. // ------------------------------------------------------------------------
  1695. // enable log flood protection
  1696. error_log_limit_reset();
  1697. // Load host labels
  1698. delta_startup_time("collect host labels");
  1699. reload_host_labels();
  1700. // ------------------------------------------------------------------------
  1701. // spawn the threads
  1702. delta_startup_time("start the static threads");
  1703. web_server_config_options();
  1704. netdata_zero_metrics_enabled = config_get_boolean_ondemand(CONFIG_SECTION_DB, "enable zero metrics", CONFIG_BOOLEAN_NO);
  1705. set_late_global_environment(system_info);
  1706. for (i = 0; static_threads[i].name != NULL ; i++) {
  1707. struct netdata_static_thread *st = &static_threads[i];
  1708. if(st->enabled) {
  1709. st->thread = mallocz(sizeof(netdata_thread_t));
  1710. netdata_log_debug(D_SYSTEM, "Starting thread %s.", st->name);
  1711. netdata_thread_create(st->thread, st->name, NETDATA_THREAD_OPTION_DEFAULT, st->start_routine, st);
  1712. }
  1713. else
  1714. netdata_log_debug(D_SYSTEM, "Not starting thread %s.", st->name);
  1715. }
  1716. ml_start_threads();
  1717. // ------------------------------------------------------------------------
  1718. // Initialize netdata agent command serving from cli and signals
  1719. delta_startup_time("initialize commands API");
  1720. commands_init();
  1721. delta_startup_time("ready");
  1722. usec_t ready_ut = now_monotonic_usec();
  1723. netdata_log_info("NETDATA STARTUP: completed in %llu ms. Enjoy real-time performance monitoring!", (ready_ut - started_ut) / USEC_PER_MS);
  1724. netdata_ready = true;
  1725. send_statistics("START", "-", "-");
  1726. if (crash_detected)
  1727. send_statistics("CRASH", "-", "-");
  1728. if (incomplete_shutdown_detected)
  1729. send_statistics("INCOMPLETE_SHUTDOWN", "-", "-");
  1730. //check if ANALYTICS needs to start
  1731. if (netdata_anonymous_statistics_enabled == 1) {
  1732. for (i = 0; static_threads[i].name != NULL; i++) {
  1733. if (!strncmp(static_threads[i].name, "ANALYTICS", 9)) {
  1734. struct netdata_static_thread *st = &static_threads[i];
  1735. st->thread = mallocz(sizeof(netdata_thread_t));
  1736. st->enabled = 1;
  1737. netdata_log_debug(D_SYSTEM, "Starting thread %s.", st->name);
  1738. netdata_thread_create(st->thread, st->name, NETDATA_THREAD_OPTION_DEFAULT, st->start_routine, st);
  1739. }
  1740. }
  1741. }
  1742. // ------------------------------------------------------------------------
  1743. // Report ACLK build failure
  1744. #ifndef ENABLE_ACLK
  1745. netdata_log_error("This agent doesn't have ACLK.");
  1746. char filename[FILENAME_MAX + 1];
  1747. snprintfz(filename, FILENAME_MAX, "%s/.aclk_report_sent", netdata_configured_varlib_dir);
  1748. if (netdata_anonymous_statistics_enabled > 0 && access(filename, F_OK)) { // -1 -> not initialized
  1749. send_statistics("ACLK_DISABLED", "-", "-");
  1750. int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 444);
  1751. if (fd == -1)
  1752. netdata_log_error("Cannot create file '%s'. Please fix this.", filename);
  1753. else
  1754. close(fd);
  1755. }
  1756. #endif
  1757. // ------------------------------------------------------------------------
  1758. // initialize WebRTC
  1759. webrtc_initialize();
  1760. // ------------------------------------------------------------------------
  1761. // unblock signals
  1762. signals_unblock();
  1763. // ------------------------------------------------------------------------
  1764. // Handle signals
  1765. signals_handle();
  1766. // should never reach this point
  1767. // but we need it for rpmlint #2752
  1768. return 1;
  1769. }