main.c 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168
  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. }
  356. }
  357. delta_shutdown_time("wait for dbengine main cache to finish flushing");
  358. while (pgc_hot_and_dirty_entries(main_cache)) {
  359. pgc_flush_all_hot_and_dirty_pages(main_cache, PGC_SECTION_ALL);
  360. sleep_usec(100 * USEC_PER_MS);
  361. }
  362. delta_shutdown_time("stop dbengine tiers");
  363. for (size_t tier = 0; tier < storage_tiers; tier++)
  364. rrdeng_exit(multidb_ctx[tier]);
  365. }
  366. #endif
  367. }
  368. delta_shutdown_time("close SQL context db");
  369. sql_close_context_database();
  370. delta_shutdown_time("closed SQL main db");
  371. sql_close_database();
  372. // unlink the pid
  373. if(pidfile[0]) {
  374. delta_shutdown_time("remove pid file");
  375. if(unlink(pidfile) != 0)
  376. netdata_log_error("EXIT: cannot unlink pidfile '%s'.", pidfile);
  377. }
  378. #ifdef ENABLE_HTTPS
  379. delta_shutdown_time("free openssl structures");
  380. netdata_ssl_cleanup();
  381. #endif
  382. delta_shutdown_time("remove incomplete shutdown file");
  383. (void) unlink(agent_incomplete_shutdown_file);
  384. delta_shutdown_time("exit");
  385. usec_t ended_ut = now_monotonic_usec();
  386. netdata_log_info("NETDATA SHUTDOWN: completed in %llu ms - netdata is now exiting - bye bye...", (ended_ut - started_ut) / USEC_PER_MS);
  387. exit(ret);
  388. }
  389. void web_server_threading_selection(void) {
  390. web_server_mode = web_server_mode_id(config_get(CONFIG_SECTION_WEB, "mode", web_server_mode_name(web_server_mode)));
  391. int static_threaded = (web_server_mode == WEB_SERVER_MODE_STATIC_THREADED);
  392. int i;
  393. for (i = 0; static_threads[i].name; i++) {
  394. if (static_threads[i].start_routine == socket_listen_main_static_threaded)
  395. static_threads[i].enabled = static_threaded;
  396. }
  397. }
  398. int make_dns_decision(const char *section_name, const char *config_name, const char *default_value, SIMPLE_PATTERN *p)
  399. {
  400. char *value = config_get(section_name,config_name,default_value);
  401. if(!strcmp("yes",value))
  402. return 1;
  403. if(!strcmp("no",value))
  404. return 0;
  405. if(strcmp("heuristic",value))
  406. netdata_log_error("Invalid configuration option '%s' for '%s'/'%s'. Valid options are 'yes', 'no' and 'heuristic'. Proceeding with 'heuristic'",
  407. value, section_name, config_name);
  408. return simple_pattern_is_potential_name(p);
  409. }
  410. void web_server_config_options(void)
  411. {
  412. web_client_timeout =
  413. (int)config_get_number(CONFIG_SECTION_WEB, "disconnect idle clients after seconds", web_client_timeout);
  414. web_client_first_request_timeout =
  415. (int)config_get_number(CONFIG_SECTION_WEB, "timeout for first request", web_client_first_request_timeout);
  416. web_client_streaming_rate_t =
  417. config_get_number(CONFIG_SECTION_WEB, "accept a streaming request every seconds", web_client_streaming_rate_t);
  418. respect_web_browser_do_not_track_policy =
  419. config_get_boolean(CONFIG_SECTION_WEB, "respect do not track policy", respect_web_browser_do_not_track_policy);
  420. web_x_frame_options = config_get(CONFIG_SECTION_WEB, "x-frame-options response header", "");
  421. if(!*web_x_frame_options)
  422. web_x_frame_options = NULL;
  423. web_allow_connections_from =
  424. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow connections from", "localhost *"),
  425. NULL, SIMPLE_PATTERN_EXACT, true);
  426. web_allow_connections_dns =
  427. make_dns_decision(CONFIG_SECTION_WEB, "allow connections by dns", "heuristic", web_allow_connections_from);
  428. web_allow_dashboard_from =
  429. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow dashboard from", "localhost *"),
  430. NULL, SIMPLE_PATTERN_EXACT, true);
  431. web_allow_dashboard_dns =
  432. make_dns_decision(CONFIG_SECTION_WEB, "allow dashboard by dns", "heuristic", web_allow_dashboard_from);
  433. web_allow_badges_from =
  434. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow badges from", "*"), NULL, SIMPLE_PATTERN_EXACT,
  435. true);
  436. web_allow_badges_dns =
  437. make_dns_decision(CONFIG_SECTION_WEB, "allow badges by dns", "heuristic", web_allow_badges_from);
  438. web_allow_registry_from =
  439. simple_pattern_create(config_get(CONFIG_SECTION_REGISTRY, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT,
  440. true);
  441. web_allow_registry_dns = make_dns_decision(CONFIG_SECTION_REGISTRY, "allow by dns", "heuristic",
  442. web_allow_registry_from);
  443. web_allow_streaming_from = simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow streaming from", "*"),
  444. NULL, SIMPLE_PATTERN_EXACT, true);
  445. web_allow_streaming_dns = make_dns_decision(CONFIG_SECTION_WEB, "allow streaming by dns", "heuristic",
  446. web_allow_streaming_from);
  447. // Note the default is not heuristic, the wildcards could match DNS but the intent is ip-addresses.
  448. web_allow_netdataconf_from = simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow netdata.conf from",
  449. "localhost fd* 10.* 192.168.* 172.16.* 172.17.* 172.18.*"
  450. " 172.19.* 172.20.* 172.21.* 172.22.* 172.23.* 172.24.*"
  451. " 172.25.* 172.26.* 172.27.* 172.28.* 172.29.* 172.30.*"
  452. " 172.31.* UNKNOWN"), NULL, SIMPLE_PATTERN_EXACT,
  453. true);
  454. web_allow_netdataconf_dns =
  455. make_dns_decision(CONFIG_SECTION_WEB, "allow netdata.conf by dns", "no", web_allow_netdataconf_from);
  456. web_allow_mgmt_from =
  457. simple_pattern_create(config_get(CONFIG_SECTION_WEB, "allow management from", "localhost"),
  458. NULL, SIMPLE_PATTERN_EXACT, true);
  459. web_allow_mgmt_dns =
  460. make_dns_decision(CONFIG_SECTION_WEB, "allow management by dns","heuristic",web_allow_mgmt_from);
  461. web_enable_gzip = config_get_boolean(CONFIG_SECTION_WEB, "enable gzip compression", web_enable_gzip);
  462. char *s = config_get(CONFIG_SECTION_WEB, "gzip compression strategy", "default");
  463. if(!strcmp(s, "default"))
  464. web_gzip_strategy = Z_DEFAULT_STRATEGY;
  465. else if(!strcmp(s, "filtered"))
  466. web_gzip_strategy = Z_FILTERED;
  467. else if(!strcmp(s, "huffman only"))
  468. web_gzip_strategy = Z_HUFFMAN_ONLY;
  469. else if(!strcmp(s, "rle"))
  470. web_gzip_strategy = Z_RLE;
  471. else if(!strcmp(s, "fixed"))
  472. web_gzip_strategy = Z_FIXED;
  473. else {
  474. netdata_log_error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
  475. web_gzip_strategy = Z_DEFAULT_STRATEGY;
  476. }
  477. web_gzip_level = (int)config_get_number(CONFIG_SECTION_WEB, "gzip compression level", 3);
  478. if(web_gzip_level < 1) {
  479. 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);
  480. web_gzip_level = 1;
  481. }
  482. else if(web_gzip_level > 9) {
  483. 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);
  484. web_gzip_level = 9;
  485. }
  486. }
  487. // killpid kills pid with SIGTERM.
  488. int killpid(pid_t pid) {
  489. int ret;
  490. netdata_log_debug(D_EXIT, "Request to kill pid %d", pid);
  491. errno = 0;
  492. ret = kill(pid, SIGTERM);
  493. if (ret == -1) {
  494. switch(errno) {
  495. case ESRCH:
  496. // We wanted the process to exit so just let the caller handle.
  497. return ret;
  498. case EPERM:
  499. netdata_log_error("Cannot kill pid %d, but I do not have enough permissions.", pid);
  500. break;
  501. default:
  502. netdata_log_error("Cannot kill pid %d, but I received an error.", pid);
  503. break;
  504. }
  505. }
  506. return ret;
  507. }
  508. static void set_nofile_limit(struct rlimit *rl) {
  509. // get the num files allowed
  510. if(getrlimit(RLIMIT_NOFILE, rl) != 0) {
  511. netdata_log_error("getrlimit(RLIMIT_NOFILE) failed");
  512. return;
  513. }
  514. netdata_log_info("resources control: allowed file descriptors: soft = %zu, max = %zu",
  515. (size_t) rl->rlim_cur, (size_t) rl->rlim_max);
  516. // make the soft/hard limits equal
  517. rl->rlim_cur = rl->rlim_max;
  518. if (setrlimit(RLIMIT_NOFILE, rl) != 0) {
  519. netdata_log_error("setrlimit(RLIMIT_NOFILE, { %zu, %zu }) failed", (size_t)rl->rlim_cur, (size_t)rl->rlim_max);
  520. }
  521. // sanity check to make sure we have enough file descriptors available to open
  522. if (getrlimit(RLIMIT_NOFILE, rl) != 0) {
  523. netdata_log_error("getrlimit(RLIMIT_NOFILE) failed");
  524. return;
  525. }
  526. if (rl->rlim_cur < 1024)
  527. netdata_log_error("Number of open file descriptors allowed for this process is too low (RLIMIT_NOFILE=%zu)", (size_t)rl->rlim_cur);
  528. }
  529. void cancel_main_threads() {
  530. error_log_limit_unlimited();
  531. int i, found = 0;
  532. usec_t max = 5 * USEC_PER_SEC, step = 100000;
  533. for (i = 0; static_threads[i].name != NULL ; i++) {
  534. if (static_threads[i].enabled == NETDATA_MAIN_THREAD_RUNNING) {
  535. if (static_threads[i].thread) {
  536. netdata_log_info("EXIT: Stopping main thread: %s", static_threads[i].name);
  537. netdata_thread_cancel(*static_threads[i].thread);
  538. } else {
  539. netdata_log_info("EXIT: No thread running (marking as EXITED): %s", static_threads[i].name);
  540. static_threads[i].enabled = NETDATA_MAIN_THREAD_EXITED;
  541. }
  542. found++;
  543. }
  544. }
  545. netdata_exit = 1;
  546. while(found && max > 0) {
  547. max -= step;
  548. netdata_log_info("Waiting %d threads to finish...", found);
  549. sleep_usec(step);
  550. found = 0;
  551. for (i = 0; static_threads[i].name != NULL ; i++) {
  552. if (static_threads[i].enabled != NETDATA_MAIN_THREAD_EXITED)
  553. found++;
  554. }
  555. }
  556. if(found) {
  557. for (i = 0; static_threads[i].name != NULL ; i++) {
  558. if (static_threads[i].enabled != NETDATA_MAIN_THREAD_EXITED)
  559. netdata_log_error("Main thread %s takes too long to exit. Giving up...", static_threads[i].name);
  560. }
  561. }
  562. else
  563. netdata_log_info("All threads finished.");
  564. for (i = 0; static_threads[i].name != NULL ; i++)
  565. freez(static_threads[i].thread);
  566. freez(static_threads);
  567. }
  568. struct option_def option_definitions[] = {
  569. // opt description arg name default value
  570. { 'c', "Configuration file to load.", "filename", CONFIG_DIR "/" CONFIG_FILENAME},
  571. { 'D', "Do not fork. Run in the foreground.", NULL, "run in the background"},
  572. { 'd', "Fork. Run in the background.", NULL, "run in the background"},
  573. { 'h', "Display this help message.", NULL, NULL},
  574. { 'P', "File to save a pid while running.", "filename", "do not save pid to a file"},
  575. { 'i', "The IP address to listen to.", "IP", "all IP addresses IPv4 and IPv6"},
  576. { 'p', "API/Web port to use.", "port", "19999"},
  577. { 's', "Prefix for /proc and /sys (for containers).", "path", "no prefix"},
  578. { 't', "The internal clock of netdata.", "seconds", "1"},
  579. { 'u', "Run as user.", "username", "netdata"},
  580. { 'v', "Print netdata version and exit.", NULL, NULL},
  581. { 'V', "Print netdata version and exit.", NULL, NULL},
  582. { 'W', "See Advanced options below.", "options", NULL},
  583. };
  584. int help(int exitcode) {
  585. FILE *stream;
  586. if(exitcode == 0)
  587. stream = stdout;
  588. else
  589. stream = stderr;
  590. int num_opts = sizeof(option_definitions) / sizeof(struct option_def);
  591. int i;
  592. int max_len_arg = 0;
  593. // Compute maximum argument length
  594. for( i = 0; i < num_opts; i++ ) {
  595. if(option_definitions[i].arg_name) {
  596. int len_arg = (int)strlen(option_definitions[i].arg_name);
  597. if(len_arg > max_len_arg) max_len_arg = len_arg;
  598. }
  599. }
  600. if(max_len_arg > 30) max_len_arg = 30;
  601. if(max_len_arg < 20) max_len_arg = 20;
  602. fprintf(stream, "%s", "\n"
  603. " ^\n"
  604. " |.-. .-. .-. .-. . netdata \n"
  605. " | '-' '-' '-' '-' real-time performance monitoring, done right! \n"
  606. " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
  607. "\n"
  608. " Copyright (C) 2016-2022, Netdata, Inc. <info@netdata.cloud>\n"
  609. " Released under GNU General Public License v3 or later.\n"
  610. " All rights reserved.\n"
  611. "\n"
  612. " Home Page : https://netdata.cloud\n"
  613. " Source Code: https://github.com/netdata/netdata\n"
  614. " Docs : https://learn.netdata.cloud\n"
  615. " Support : https://github.com/netdata/netdata/issues\n"
  616. " License : https://github.com/netdata/netdata/blob/master/LICENSE.md\n"
  617. "\n"
  618. " Twitter : https://twitter.com/linuxnetdata\n"
  619. " LinkedIn : https://linkedin.com/company/netdata-cloud/\n"
  620. " Facebook : https://facebook.com/linuxnetdata/\n"
  621. "\n"
  622. "\n"
  623. );
  624. fprintf(stream, " SYNOPSIS: netdata [options]\n");
  625. fprintf(stream, "\n");
  626. fprintf(stream, " Options:\n\n");
  627. // Output options description.
  628. for( i = 0; i < num_opts; i++ ) {
  629. 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);
  630. if(option_definitions[i].default_value) {
  631. fprintf(stream, "\n %c %-*s Default: %s\n", ' ', max_len_arg, "", option_definitions[i].default_value);
  632. } else {
  633. fprintf(stream, "\n");
  634. }
  635. fprintf(stream, "\n");
  636. }
  637. fprintf(stream, "\n Advanced options:\n\n"
  638. " -W stacksize=N Set the stacksize (in bytes).\n\n"
  639. " -W debug_flags=N Set runtime tracing to debug.log.\n\n"
  640. " -W unittest Run internal unittests and exit.\n\n"
  641. " -W sqlite-check Check metadata database integrity and exit.\n\n"
  642. " -W sqlite-fix Check metadata database integrity, fix if needed 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. }
  715. char *initialize_lock_directory_path(char *prefix)
  716. {
  717. char filename[FILENAME_MAX + 1];
  718. snprintfz(filename, FILENAME_MAX, "%s/lock", prefix);
  719. return config_get(CONFIG_SECTION_DIRECTORIES, "lock", filename);
  720. }
  721. static void backwards_compatible_config() {
  722. // move [global] options to the [web] section
  723. config_move(CONFIG_SECTION_GLOBAL, "http port listen backlog",
  724. CONFIG_SECTION_WEB, "listen backlog");
  725. config_move(CONFIG_SECTION_GLOBAL, "bind socket to IP",
  726. CONFIG_SECTION_WEB, "bind to");
  727. config_move(CONFIG_SECTION_GLOBAL, "bind to",
  728. CONFIG_SECTION_WEB, "bind to");
  729. config_move(CONFIG_SECTION_GLOBAL, "port",
  730. CONFIG_SECTION_WEB, "default port");
  731. config_move(CONFIG_SECTION_GLOBAL, "default port",
  732. CONFIG_SECTION_WEB, "default port");
  733. config_move(CONFIG_SECTION_GLOBAL, "disconnect idle web clients after seconds",
  734. CONFIG_SECTION_WEB, "disconnect idle clients after seconds");
  735. config_move(CONFIG_SECTION_GLOBAL, "respect web browser do not track policy",
  736. CONFIG_SECTION_WEB, "respect do not track policy");
  737. config_move(CONFIG_SECTION_GLOBAL, "web x-frame-options header",
  738. CONFIG_SECTION_WEB, "x-frame-options response header");
  739. config_move(CONFIG_SECTION_GLOBAL, "enable web responses gzip compression",
  740. CONFIG_SECTION_WEB, "enable gzip compression");
  741. config_move(CONFIG_SECTION_GLOBAL, "web compression strategy",
  742. CONFIG_SECTION_WEB, "gzip compression strategy");
  743. config_move(CONFIG_SECTION_GLOBAL, "web compression level",
  744. CONFIG_SECTION_WEB, "gzip compression level");
  745. config_move(CONFIG_SECTION_GLOBAL, "config directory",
  746. CONFIG_SECTION_DIRECTORIES, "config");
  747. config_move(CONFIG_SECTION_GLOBAL, "stock config directory",
  748. CONFIG_SECTION_DIRECTORIES, "stock config");
  749. config_move(CONFIG_SECTION_GLOBAL, "log directory",
  750. CONFIG_SECTION_DIRECTORIES, "log");
  751. config_move(CONFIG_SECTION_GLOBAL, "web files directory",
  752. CONFIG_SECTION_DIRECTORIES, "web");
  753. config_move(CONFIG_SECTION_GLOBAL, "cache directory",
  754. CONFIG_SECTION_DIRECTORIES, "cache");
  755. config_move(CONFIG_SECTION_GLOBAL, "lib directory",
  756. CONFIG_SECTION_DIRECTORIES, "lib");
  757. config_move(CONFIG_SECTION_GLOBAL, "home directory",
  758. CONFIG_SECTION_DIRECTORIES, "home");
  759. config_move(CONFIG_SECTION_GLOBAL, "lock directory",
  760. CONFIG_SECTION_DIRECTORIES, "lock");
  761. config_move(CONFIG_SECTION_GLOBAL, "plugins directory",
  762. CONFIG_SECTION_DIRECTORIES, "plugins");
  763. config_move(CONFIG_SECTION_HEALTH, "health configuration directory",
  764. CONFIG_SECTION_DIRECTORIES, "health config");
  765. config_move(CONFIG_SECTION_HEALTH, "stock health configuration directory",
  766. CONFIG_SECTION_DIRECTORIES, "stock health config");
  767. config_move(CONFIG_SECTION_REGISTRY, "registry db directory",
  768. CONFIG_SECTION_DIRECTORIES, "registry");
  769. config_move(CONFIG_SECTION_GLOBAL, "debug log",
  770. CONFIG_SECTION_LOGS, "debug");
  771. config_move(CONFIG_SECTION_GLOBAL, "error log",
  772. CONFIG_SECTION_LOGS, "error");
  773. config_move(CONFIG_SECTION_GLOBAL, "access log",
  774. CONFIG_SECTION_LOGS, "access");
  775. config_move(CONFIG_SECTION_GLOBAL, "facility log",
  776. CONFIG_SECTION_LOGS, "facility");
  777. config_move(CONFIG_SECTION_GLOBAL, "errors flood protection period",
  778. CONFIG_SECTION_LOGS, "errors flood protection period");
  779. config_move(CONFIG_SECTION_GLOBAL, "errors to trigger flood protection",
  780. CONFIG_SECTION_LOGS, "errors to trigger flood protection");
  781. config_move(CONFIG_SECTION_GLOBAL, "debug flags",
  782. CONFIG_SECTION_LOGS, "debug flags");
  783. config_move(CONFIG_SECTION_GLOBAL, "TZ environment variable",
  784. CONFIG_SECTION_ENV_VARS, "TZ");
  785. config_move(CONFIG_SECTION_PLUGINS, "PATH environment variable",
  786. CONFIG_SECTION_ENV_VARS, "PATH");
  787. config_move(CONFIG_SECTION_PLUGINS, "PYTHONPATH environment variable",
  788. CONFIG_SECTION_ENV_VARS, "PYTHONPATH");
  789. config_move(CONFIG_SECTION_STATSD, "enabled",
  790. CONFIG_SECTION_PLUGINS, "statsd");
  791. config_move(CONFIG_SECTION_GLOBAL, "memory mode",
  792. CONFIG_SECTION_DB, "mode");
  793. config_move(CONFIG_SECTION_GLOBAL, "history",
  794. CONFIG_SECTION_DB, "retention");
  795. config_move(CONFIG_SECTION_GLOBAL, "update every",
  796. CONFIG_SECTION_DB, "update every");
  797. config_move(CONFIG_SECTION_GLOBAL, "page cache size",
  798. CONFIG_SECTION_DB, "dbengine page cache size MB");
  799. config_move(CONFIG_SECTION_DB, "page cache size",
  800. CONFIG_SECTION_DB, "dbengine page cache size MB");
  801. config_move(CONFIG_SECTION_GLOBAL, "page cache uses malloc",
  802. CONFIG_SECTION_DB, "dbengine page cache with malloc");
  803. config_move(CONFIG_SECTION_DB, "page cache with malloc",
  804. CONFIG_SECTION_DB, "dbengine page cache with malloc");
  805. config_move(CONFIG_SECTION_GLOBAL, "dbengine disk space",
  806. CONFIG_SECTION_DB, "dbengine disk space MB");
  807. config_move(CONFIG_SECTION_GLOBAL, "dbengine multihost disk space",
  808. CONFIG_SECTION_DB, "dbengine multihost disk space MB");
  809. config_move(CONFIG_SECTION_GLOBAL, "memory deduplication (ksm)",
  810. CONFIG_SECTION_DB, "memory deduplication (ksm)");
  811. config_move(CONFIG_SECTION_GLOBAL, "dbengine page fetch timeout",
  812. CONFIG_SECTION_DB, "dbengine page fetch timeout secs");
  813. config_move(CONFIG_SECTION_GLOBAL, "dbengine page fetch retries",
  814. CONFIG_SECTION_DB, "dbengine page fetch retries");
  815. config_move(CONFIG_SECTION_GLOBAL, "dbengine extent pages",
  816. CONFIG_SECTION_DB, "dbengine pages per extent");
  817. config_move(CONFIG_SECTION_GLOBAL, "cleanup obsolete charts after seconds",
  818. CONFIG_SECTION_DB, "cleanup obsolete charts after secs");
  819. config_move(CONFIG_SECTION_GLOBAL, "gap when lost iterations above",
  820. CONFIG_SECTION_DB, "gap when lost iterations above");
  821. config_move(CONFIG_SECTION_GLOBAL, "cleanup orphan hosts after seconds",
  822. CONFIG_SECTION_DB, "cleanup orphan hosts after secs");
  823. config_move(CONFIG_SECTION_GLOBAL, "delete obsolete charts files",
  824. CONFIG_SECTION_DB, "delete obsolete charts files");
  825. config_move(CONFIG_SECTION_GLOBAL, "delete orphan hosts files",
  826. CONFIG_SECTION_DB, "delete orphan hosts files");
  827. config_move(CONFIG_SECTION_GLOBAL, "enable zero metrics",
  828. CONFIG_SECTION_DB, "enable zero metrics");
  829. }
  830. static void get_netdata_configured_variables() {
  831. backwards_compatible_config();
  832. // ------------------------------------------------------------------------
  833. // get the hostname
  834. char buf[HOSTNAME_MAX + 1];
  835. if(gethostname(buf, HOSTNAME_MAX) == -1){
  836. netdata_log_error("Cannot get machine hostname.");
  837. }
  838. netdata_configured_hostname = config_get(CONFIG_SECTION_GLOBAL, "hostname", buf);
  839. netdata_log_debug(D_OPTIONS, "hostname set to '%s'", netdata_configured_hostname);
  840. // ------------------------------------------------------------------------
  841. // get default database update frequency
  842. default_rrd_update_every = (int) config_get_number(CONFIG_SECTION_DB, "update every", UPDATE_EVERY);
  843. if(default_rrd_update_every < 1 || default_rrd_update_every > 600) {
  844. netdata_log_error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", default_rrd_update_every, UPDATE_EVERY);
  845. default_rrd_update_every = UPDATE_EVERY;
  846. config_set_number(CONFIG_SECTION_DB, "update every", default_rrd_update_every);
  847. }
  848. // ------------------------------------------------------------------------
  849. // get default memory mode for the database
  850. {
  851. const char *mode = config_get(CONFIG_SECTION_DB, "mode", rrd_memory_mode_name(default_rrd_memory_mode));
  852. default_rrd_memory_mode = rrd_memory_mode_id(mode);
  853. if(strcmp(mode, rrd_memory_mode_name(default_rrd_memory_mode)) != 0) {
  854. netdata_log_error("Invalid memory mode '%s' given. Using '%s'", mode, rrd_memory_mode_name(default_rrd_memory_mode));
  855. config_set(CONFIG_SECTION_DB, "mode", rrd_memory_mode_name(default_rrd_memory_mode));
  856. }
  857. }
  858. // ------------------------------------------------------------------------
  859. // get default database size
  860. if(default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE && default_rrd_memory_mode != RRD_MEMORY_MODE_NONE) {
  861. default_rrd_history_entries = (int)config_get_number(
  862. CONFIG_SECTION_DB, "retention",
  863. align_entries_to_pagesize(default_rrd_memory_mode, RRD_DEFAULT_HISTORY_ENTRIES));
  864. long h = align_entries_to_pagesize(default_rrd_memory_mode, default_rrd_history_entries);
  865. if (h != default_rrd_history_entries) {
  866. config_set_number(CONFIG_SECTION_DB, "retention", h);
  867. default_rrd_history_entries = (int)h;
  868. }
  869. }
  870. // ------------------------------------------------------------------------
  871. // get system paths
  872. netdata_configured_user_config_dir = config_get(CONFIG_SECTION_DIRECTORIES, "config", netdata_configured_user_config_dir);
  873. netdata_configured_stock_config_dir = config_get(CONFIG_SECTION_DIRECTORIES, "stock config", netdata_configured_stock_config_dir);
  874. netdata_configured_log_dir = config_get(CONFIG_SECTION_DIRECTORIES, "log", netdata_configured_log_dir);
  875. netdata_configured_web_dir = config_get(CONFIG_SECTION_DIRECTORIES, "web", netdata_configured_web_dir);
  876. netdata_configured_cache_dir = config_get(CONFIG_SECTION_DIRECTORIES, "cache", netdata_configured_cache_dir);
  877. netdata_configured_varlib_dir = config_get(CONFIG_SECTION_DIRECTORIES, "lib", netdata_configured_varlib_dir);
  878. char *env_home=getenv("HOME");
  879. netdata_configured_home_dir = config_get(CONFIG_SECTION_DIRECTORIES, "home", env_home?env_home:netdata_configured_home_dir);
  880. netdata_configured_lock_dir = initialize_lock_directory_path(netdata_configured_varlib_dir);
  881. {
  882. pluginsd_initialize_plugin_directories();
  883. netdata_configured_primary_plugins_dir = plugin_directories[PLUGINSD_STOCK_PLUGINS_DIRECTORY_PATH];
  884. }
  885. #ifdef ENABLE_DBENGINE
  886. // ------------------------------------------------------------------------
  887. // get default Database Engine page cache size in MiB
  888. default_rrdeng_page_cache_mb = (int) config_get_number(CONFIG_SECTION_DB, "dbengine page cache size MB", default_rrdeng_page_cache_mb);
  889. default_rrdeng_extent_cache_mb = (int) config_get_number(CONFIG_SECTION_DB, "dbengine extent cache size MB", default_rrdeng_extent_cache_mb);
  890. db_engine_journal_check = config_get_boolean(CONFIG_SECTION_DB, "dbengine enable journal integrity check", CONFIG_BOOLEAN_NO);
  891. if(default_rrdeng_extent_cache_mb < 0)
  892. default_rrdeng_extent_cache_mb = 0;
  893. if(default_rrdeng_page_cache_mb < RRDENG_MIN_PAGE_CACHE_SIZE_MB) {
  894. netdata_log_error("Invalid page cache size %d given. Defaulting to %d.", default_rrdeng_page_cache_mb, RRDENG_MIN_PAGE_CACHE_SIZE_MB);
  895. default_rrdeng_page_cache_mb = RRDENG_MIN_PAGE_CACHE_SIZE_MB;
  896. config_set_number(CONFIG_SECTION_DB, "dbengine page cache size MB", default_rrdeng_page_cache_mb);
  897. }
  898. // ------------------------------------------------------------------------
  899. // get default Database Engine disk space quota in MiB
  900. default_rrdeng_disk_quota_mb = (int) config_get_number(CONFIG_SECTION_DB, "dbengine disk space MB", default_rrdeng_disk_quota_mb);
  901. if(default_rrdeng_disk_quota_mb < RRDENG_MIN_DISK_SPACE_MB) {
  902. netdata_log_error("Invalid dbengine disk space %d given. Defaulting to %d.", default_rrdeng_disk_quota_mb, RRDENG_MIN_DISK_SPACE_MB);
  903. default_rrdeng_disk_quota_mb = RRDENG_MIN_DISK_SPACE_MB;
  904. config_set_number(CONFIG_SECTION_DB, "dbengine disk space MB", default_rrdeng_disk_quota_mb);
  905. }
  906. default_multidb_disk_quota_mb = (int) config_get_number(CONFIG_SECTION_DB, "dbengine multihost disk space MB", compute_multidb_diskspace());
  907. if(default_multidb_disk_quota_mb < RRDENG_MIN_DISK_SPACE_MB) {
  908. netdata_log_error("Invalid multidb disk space %d given. Defaulting to %d.", default_multidb_disk_quota_mb, default_rrdeng_disk_quota_mb);
  909. default_multidb_disk_quota_mb = default_rrdeng_disk_quota_mb;
  910. config_set_number(CONFIG_SECTION_DB, "dbengine multihost disk space MB", default_multidb_disk_quota_mb);
  911. }
  912. #else
  913. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE) {
  914. error_report("RRD_MEMORY_MODE_DBENGINE is not supported in this platform. The agent will use db mode 'save' instead.");
  915. default_rrd_memory_mode = RRD_MEMORY_MODE_SAVE;
  916. }
  917. #endif
  918. // ------------------------------------------------------------------------
  919. netdata_configured_host_prefix = config_get(CONFIG_SECTION_GLOBAL, "host access prefix", "");
  920. verify_netdata_host_prefix();
  921. // --------------------------------------------------------------------
  922. // get KSM settings
  923. #ifdef MADV_MERGEABLE
  924. enable_ksm = config_get_boolean(CONFIG_SECTION_DB, "memory deduplication (ksm)", enable_ksm);
  925. #endif
  926. // --------------------------------------------------------------------
  927. // metric correlations
  928. enable_metric_correlations = config_get_boolean(CONFIG_SECTION_GLOBAL, "enable metric correlations", enable_metric_correlations);
  929. default_metric_correlations_method = weights_string_to_method(config_get(
  930. CONFIG_SECTION_GLOBAL, "metric correlations method",
  931. weights_method_to_string(default_metric_correlations_method)));
  932. // --------------------------------------------------------------------
  933. rrdset_free_obsolete_time_s = config_get_number(CONFIG_SECTION_DB, "cleanup obsolete charts after secs", rrdset_free_obsolete_time_s);
  934. // Current chart locking and invalidation scheme doesn't prevent Netdata from segmentation faults if a short
  935. // cleanup delay is set. Extensive stress tests showed that 10 seconds is quite a safe delay. Look at
  936. // https://github.com/netdata/netdata/pull/11222#issuecomment-868367920 for more information.
  937. if (rrdset_free_obsolete_time_s < 10) {
  938. rrdset_free_obsolete_time_s = 10;
  939. netdata_log_info("The \"cleanup obsolete charts after seconds\" option was set to 10 seconds.");
  940. config_set_number(CONFIG_SECTION_DB, "cleanup obsolete charts after secs", rrdset_free_obsolete_time_s);
  941. }
  942. gap_when_lost_iterations_above = (int)config_get_number(CONFIG_SECTION_DB, "gap when lost iterations above", gap_when_lost_iterations_above);
  943. if (gap_when_lost_iterations_above < 1) {
  944. gap_when_lost_iterations_above = 1;
  945. config_set_number(CONFIG_SECTION_DB, "gap when lost iterations above", gap_when_lost_iterations_above);
  946. }
  947. gap_when_lost_iterations_above += 2;
  948. // --------------------------------------------------------------------
  949. // get various system parameters
  950. get_system_HZ();
  951. get_system_cpus_uncached();
  952. get_system_pid_max();
  953. }
  954. static void post_conf_load(char **user)
  955. {
  956. // --------------------------------------------------------------------
  957. // get the user we should run
  958. // IMPORTANT: this is required before web_files_uid()
  959. if(getuid() == 0) {
  960. *user = config_get(CONFIG_SECTION_GLOBAL, "run as user", NETDATA_USER);
  961. }
  962. else {
  963. struct passwd *passwd = getpwuid(getuid());
  964. *user = config_get(CONFIG_SECTION_GLOBAL, "run as user", (passwd && passwd->pw_name)?passwd->pw_name:"");
  965. }
  966. }
  967. static bool load_netdata_conf(char *filename, char overwrite_used, char **user) {
  968. errno = 0;
  969. int ret = 0;
  970. if(filename && *filename) {
  971. ret = config_load(filename, overwrite_used, NULL);
  972. if(!ret)
  973. netdata_log_error("CONFIG: cannot load config file '%s'.", filename);
  974. }
  975. else {
  976. filename = strdupz_path_subpath(netdata_configured_user_config_dir, "netdata.conf");
  977. ret = config_load(filename, overwrite_used, NULL);
  978. if(!ret) {
  979. netdata_log_info("CONFIG: cannot load user config '%s'. Will try the stock version.", filename);
  980. freez(filename);
  981. filename = strdupz_path_subpath(netdata_configured_stock_config_dir, "netdata.conf");
  982. ret = config_load(filename, overwrite_used, NULL);
  983. if(!ret)
  984. netdata_log_info("CONFIG: cannot load stock config '%s'. Running with internal defaults.", filename);
  985. }
  986. freez(filename);
  987. }
  988. post_conf_load(user);
  989. return ret;
  990. }
  991. // coverity[ +tainted_string_sanitize_content : arg-0 ]
  992. static inline void coverity_remove_taint(char *s)
  993. {
  994. (void)s;
  995. }
  996. int get_system_info(struct rrdhost_system_info *system_info, bool log) {
  997. char *script;
  998. script = mallocz(sizeof(char) * (strlen(netdata_configured_primary_plugins_dir) + strlen("system-info.sh") + 2));
  999. sprintf(script, "%s/%s", netdata_configured_primary_plugins_dir, "system-info.sh");
  1000. if (unlikely(access(script, R_OK) != 0)) {
  1001. netdata_log_error("System info script %s not found.",script);
  1002. freez(script);
  1003. return 1;
  1004. }
  1005. pid_t command_pid;
  1006. FILE *fp_child_input;
  1007. FILE *fp_child_output = netdata_popen(script, &command_pid, &fp_child_input);
  1008. if(fp_child_output) {
  1009. char line[200 + 1];
  1010. // Removed the double strlens, if the Coverity tainted string warning reappears I'll revert.
  1011. // One time init code, but I'm curious about the warning...
  1012. while (fgets(line, 200, fp_child_output) != NULL) {
  1013. char *value=line;
  1014. while (*value && *value != '=') value++;
  1015. if (*value=='=') {
  1016. *value='\0';
  1017. value++;
  1018. char *end = value;
  1019. while (*end && *end != '\n') end++;
  1020. *end = '\0'; // Overwrite newline if present
  1021. coverity_remove_taint(line); // I/O is controlled result of system_info.sh - not tainted
  1022. coverity_remove_taint(value);
  1023. if(unlikely(rrdhost_set_system_info_variable(system_info, line, value))) {
  1024. netdata_log_error("Unexpected environment variable %s=%s", line, value);
  1025. }
  1026. else {
  1027. if(log)
  1028. netdata_log_info("%s=%s", line, value);
  1029. setenv(line, value, 1);
  1030. }
  1031. }
  1032. }
  1033. netdata_pclose(fp_child_input, fp_child_output, command_pid);
  1034. }
  1035. freez(script);
  1036. return 0;
  1037. }
  1038. void set_silencers_filename() {
  1039. char filename[FILENAME_MAX + 1];
  1040. snprintfz(filename, FILENAME_MAX, "%s/health.silencers.json", netdata_configured_varlib_dir);
  1041. silencers_filename = config_get(CONFIG_SECTION_HEALTH, "silencers file", filename);
  1042. }
  1043. /* Any config setting that can be accessed without a default value i.e. configget(...,...,NULL) *MUST*
  1044. be set in this procedure to be called in all the relevant code paths.
  1045. */
  1046. #define delta_startup_time(msg) \
  1047. { \
  1048. usec_t now_ut = now_monotonic_usec(); \
  1049. if(prev_msg) \
  1050. netdata_log_info("NETDATA STARTUP: in %7llu ms, %s - next: %s", (now_ut - last_ut) / USEC_PER_MS, prev_msg, msg); \
  1051. else \
  1052. netdata_log_info("NETDATA STARTUP: next: %s", msg); \
  1053. last_ut = now_ut; \
  1054. prev_msg = msg; \
  1055. }
  1056. int buffer_unittest(void);
  1057. int pgc_unittest(void);
  1058. int mrg_unittest(void);
  1059. int julytest(void);
  1060. int pluginsd_parser_unittest(void);
  1061. void replication_initialize(void);
  1062. int main(int argc, char **argv) {
  1063. // initialize the system clocks
  1064. clocks_init();
  1065. netdata_start_time = now_realtime_sec();
  1066. usec_t started_ut = now_monotonic_usec();
  1067. usec_t last_ut = started_ut;
  1068. const char *prev_msg = NULL;
  1069. // Initialize stderror avoiding coredump when netdata_log_info() or netdata_log_error() is called
  1070. stderror = stderr;
  1071. int i;
  1072. int config_loaded = 0;
  1073. int dont_fork = 0;
  1074. bool close_open_fds = true;
  1075. size_t default_stacksize;
  1076. char *user = NULL;
  1077. static_threads = static_threads_get();
  1078. netdata_ready = false;
  1079. // set the name for logging
  1080. program_name = "netdata";
  1081. if (argc > 1 && strcmp(argv[1], SPAWN_SERVER_COMMAND_LINE_ARGUMENT) == 0) {
  1082. // don't run netdata, this is the spawn server
  1083. spawn_server();
  1084. exit(0);
  1085. }
  1086. // parse options
  1087. {
  1088. int num_opts = sizeof(option_definitions) / sizeof(struct option_def);
  1089. char optstring[(num_opts * 2) + 1];
  1090. int string_i = 0;
  1091. for( i = 0; i < num_opts; i++ ) {
  1092. optstring[string_i] = option_definitions[i].val;
  1093. string_i++;
  1094. if(option_definitions[i].arg_name) {
  1095. optstring[string_i] = ':';
  1096. string_i++;
  1097. }
  1098. }
  1099. // terminate optstring
  1100. optstring[string_i] ='\0';
  1101. optstring[(num_opts *2)] ='\0';
  1102. int opt;
  1103. while( (opt = getopt(argc, argv, optstring)) != -1 ) {
  1104. switch(opt) {
  1105. case 'c':
  1106. if(!load_netdata_conf(optarg, 1, &user)) {
  1107. netdata_log_error("Cannot load configuration file %s.", optarg);
  1108. return 1;
  1109. }
  1110. else {
  1111. netdata_log_debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
  1112. load_cloud_conf(1);
  1113. config_loaded = 1;
  1114. }
  1115. break;
  1116. case 'D':
  1117. dont_fork = 1;
  1118. break;
  1119. case 'd':
  1120. dont_fork = 0;
  1121. break;
  1122. case 'h':
  1123. return help(0);
  1124. case 'i':
  1125. config_set(CONFIG_SECTION_WEB, "bind to", optarg);
  1126. break;
  1127. case 'P':
  1128. strncpy(pidfile, optarg, FILENAME_MAX);
  1129. pidfile[FILENAME_MAX] = '\0';
  1130. break;
  1131. case 'p':
  1132. config_set(CONFIG_SECTION_GLOBAL, "default port", optarg);
  1133. break;
  1134. case 's':
  1135. config_set(CONFIG_SECTION_GLOBAL, "host access prefix", optarg);
  1136. break;
  1137. case 't':
  1138. config_set(CONFIG_SECTION_GLOBAL, "update every", optarg);
  1139. break;
  1140. case 'u':
  1141. config_set(CONFIG_SECTION_GLOBAL, "run as user", optarg);
  1142. break;
  1143. case 'v':
  1144. case 'V':
  1145. printf("%s %s\n", program_name, program_version);
  1146. return 0;
  1147. case 'W':
  1148. {
  1149. char* stacksize_string = "stacksize=";
  1150. char* debug_flags_string = "debug_flags=";
  1151. char* claim_string = "claim";
  1152. #ifdef ENABLE_DBENGINE
  1153. char* createdataset_string = "createdataset=";
  1154. char* stresstest_string = "stresstest=";
  1155. #endif
  1156. if(strcmp(optarg, "sqlite-check") == 0) {
  1157. sql_init_database(DB_CHECK_INTEGRITY, 0);
  1158. return 0;
  1159. }
  1160. if(strcmp(optarg, "sqlite-fix") == 0) {
  1161. sql_init_database(DB_CHECK_FIX_DB, 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. ieee754_doubles = is_system_ieee754_double();
  1572. aral_judy_init();
  1573. get_system_timezone();
  1574. bearer_tokens_init();
  1575. replication_initialize();
  1576. // --------------------------------------------------------------------
  1577. // get the certificate and start security
  1578. #ifdef ENABLE_HTTPS
  1579. security_init();
  1580. #endif
  1581. // --------------------------------------------------------------------
  1582. // This is the safest place to start the SILENCERS structure
  1583. set_silencers_filename();
  1584. health_initialize_global_silencers();
  1585. // --------------------------------------------------------------------
  1586. // Initialize ML configuration
  1587. delta_startup_time("initialize ML");
  1588. ml_init();
  1589. // --------------------------------------------------------------------
  1590. // setup process signals
  1591. // block signals while initializing threads.
  1592. // this causes the threads to block signals.
  1593. delta_startup_time("initialize signals");
  1594. signals_block();
  1595. signals_init(); // setup the signals we want to use
  1596. // --------------------------------------------------------------------
  1597. // check which threads are enabled and initialize them
  1598. delta_startup_time("initialize static threads");
  1599. // setup threads configs
  1600. default_stacksize = netdata_threads_init();
  1601. for (i = 0; static_threads[i].name != NULL ; i++) {
  1602. struct netdata_static_thread *st = &static_threads[i];
  1603. if(st->config_name)
  1604. st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
  1605. if(st->enabled && st->init_routine)
  1606. st->init_routine();
  1607. if(st->env_name)
  1608. setenv(st->env_name, st->enabled?"YES":"NO", 1);
  1609. if(st->global_variable)
  1610. *st->global_variable = (st->enabled) ? true : false;
  1611. }
  1612. // --------------------------------------------------------------------
  1613. // create the listening sockets
  1614. delta_startup_time("initialize web server");
  1615. web_client_api_v1_init();
  1616. web_server_threading_selection();
  1617. if(web_server_mode != WEB_SERVER_MODE_NONE)
  1618. api_listen_sockets_setup();
  1619. #ifdef ENABLE_H2O
  1620. delta_startup_time("initialize h2o server");
  1621. for (int i = 0; static_threads[i].name; i++) {
  1622. if (static_threads[i].start_routine == h2o_main)
  1623. static_threads[i].enabled = httpd_is_enabled();
  1624. }
  1625. #endif
  1626. }
  1627. delta_startup_time("set resource limits");
  1628. #ifdef NETDATA_INTERNAL_CHECKS
  1629. if(debug_flags != 0) {
  1630. struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
  1631. if(setrlimit(RLIMIT_CORE, &rl) != 0)
  1632. netdata_log_error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
  1633. #ifdef HAVE_SYS_PRCTL_H
  1634. prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
  1635. #endif
  1636. }
  1637. #endif /* NETDATA_INTERNAL_CHECKS */
  1638. set_nofile_limit(&rlimit_nofile);
  1639. delta_startup_time("become daemon");
  1640. // fork, switch user, create pid file, set process priority
  1641. if(become_daemon(dont_fork, user) == -1)
  1642. fatal("Cannot daemonize myself.");
  1643. netdata_log_info("netdata started on pid %d.", getpid());
  1644. delta_startup_time("initialize threads after fork");
  1645. netdata_threads_init_after_fork((size_t)config_get_number(CONFIG_SECTION_GLOBAL, "pthread stack size", (long)default_stacksize));
  1646. // initialize internal registry
  1647. delta_startup_time("initialize registry");
  1648. registry_init();
  1649. // fork the spawn server
  1650. delta_startup_time("fork the spawn server");
  1651. spawn_init();
  1652. /*
  1653. * Libuv uv_spawn() uses SIGCHLD internally:
  1654. * https://github.com/libuv/libuv/blob/cc51217a317e96510fbb284721d5e6bc2af31e33/src/unix/process.c#L485
  1655. * and inadvertently replaces the netdata signal handler which was setup during initialization.
  1656. * Thusly, we must explicitly restore the signal handler for SIGCHLD.
  1657. * Warning: extreme care is needed when mixing and matching POSIX and libuv.
  1658. */
  1659. signals_restore_SIGCHLD();
  1660. // ------------------------------------------------------------------------
  1661. // initialize rrd, registry, health, rrdpush, etc.
  1662. delta_startup_time("collecting system info");
  1663. netdata_anonymous_statistics_enabled=-1;
  1664. struct rrdhost_system_info *system_info = callocz(1, sizeof(struct rrdhost_system_info));
  1665. __atomic_sub_fetch(&netdata_buffers_statistics.rrdhost_allocations_size, sizeof(struct rrdhost_system_info), __ATOMIC_RELAXED);
  1666. get_system_info(system_info, true);
  1667. (void) registry_get_this_machine_guid();
  1668. system_info->hops = 0;
  1669. get_install_type(&system_info->install_type, &system_info->prebuilt_arch, &system_info->prebuilt_dist);
  1670. delta_startup_time("initialize RRD structures");
  1671. if(rrd_init(netdata_configured_hostname, system_info, false)) {
  1672. set_late_global_environment(system_info);
  1673. fatal("Cannot initialize localhost instance with name '%s'.", netdata_configured_hostname);
  1674. }
  1675. delta_startup_time("check for incomplete shutdown");
  1676. char agent_crash_file[FILENAME_MAX + 1];
  1677. char agent_incomplete_shutdown_file[FILENAME_MAX + 1];
  1678. snprintfz(agent_incomplete_shutdown_file, FILENAME_MAX, "%s/.agent_incomplete_shutdown", netdata_configured_varlib_dir);
  1679. int incomplete_shutdown_detected = (unlink(agent_incomplete_shutdown_file) == 0);
  1680. snprintfz(agent_crash_file, FILENAME_MAX, "%s/.agent_crash", netdata_configured_varlib_dir);
  1681. int crash_detected = (unlink(agent_crash_file) == 0);
  1682. int fd = open(agent_crash_file, O_WRONLY | O_CREAT | O_TRUNC, 444);
  1683. if (fd >= 0)
  1684. close(fd);
  1685. // ------------------------------------------------------------------------
  1686. // Claim netdata agent to a cloud endpoint
  1687. delta_startup_time("collect claiming info");
  1688. if (claiming_pending_arguments)
  1689. claim_agent(claiming_pending_arguments, false, NULL);
  1690. load_claiming_state();
  1691. // ------------------------------------------------------------------------
  1692. // enable log flood protection
  1693. error_log_limit_reset();
  1694. // Load host labels
  1695. delta_startup_time("collect host labels");
  1696. reload_host_labels();
  1697. // ------------------------------------------------------------------------
  1698. // spawn the threads
  1699. delta_startup_time("start the static threads");
  1700. web_server_config_options();
  1701. netdata_zero_metrics_enabled = config_get_boolean_ondemand(CONFIG_SECTION_DB, "enable zero metrics", CONFIG_BOOLEAN_NO);
  1702. set_late_global_environment(system_info);
  1703. for (i = 0; static_threads[i].name != NULL ; i++) {
  1704. struct netdata_static_thread *st = &static_threads[i];
  1705. if(st->enabled) {
  1706. st->thread = mallocz(sizeof(netdata_thread_t));
  1707. netdata_log_debug(D_SYSTEM, "Starting thread %s.", st->name);
  1708. netdata_thread_create(st->thread, st->name, NETDATA_THREAD_OPTION_DEFAULT, st->start_routine, st);
  1709. }
  1710. else
  1711. netdata_log_debug(D_SYSTEM, "Not starting thread %s.", st->name);
  1712. }
  1713. ml_start_threads();
  1714. // ------------------------------------------------------------------------
  1715. // Initialize netdata agent command serving from cli and signals
  1716. delta_startup_time("initialize commands API");
  1717. commands_init();
  1718. delta_startup_time("ready");
  1719. usec_t ready_ut = now_monotonic_usec();
  1720. netdata_log_info("NETDATA STARTUP: completed in %llu ms. Enjoy real-time performance monitoring!", (ready_ut - started_ut) / USEC_PER_MS);
  1721. netdata_ready = true;
  1722. send_statistics("START", "-", "-");
  1723. if (crash_detected)
  1724. send_statistics("CRASH", "-", "-");
  1725. if (incomplete_shutdown_detected)
  1726. send_statistics("INCOMPLETE_SHUTDOWN", "-", "-");
  1727. //check if ANALYTICS needs to start
  1728. if (netdata_anonymous_statistics_enabled == 1) {
  1729. for (i = 0; static_threads[i].name != NULL; i++) {
  1730. if (!strncmp(static_threads[i].name, "ANALYTICS", 9)) {
  1731. struct netdata_static_thread *st = &static_threads[i];
  1732. st->thread = mallocz(sizeof(netdata_thread_t));
  1733. st->enabled = 1;
  1734. netdata_log_debug(D_SYSTEM, "Starting thread %s.", st->name);
  1735. netdata_thread_create(st->thread, st->name, NETDATA_THREAD_OPTION_DEFAULT, st->start_routine, st);
  1736. }
  1737. }
  1738. }
  1739. // ------------------------------------------------------------------------
  1740. // Report ACLK build failure
  1741. #ifndef ENABLE_ACLK
  1742. netdata_log_error("This agent doesn't have ACLK.");
  1743. char filename[FILENAME_MAX + 1];
  1744. snprintfz(filename, FILENAME_MAX, "%s/.aclk_report_sent", netdata_configured_varlib_dir);
  1745. if (netdata_anonymous_statistics_enabled > 0 && access(filename, F_OK)) { // -1 -> not initialized
  1746. send_statistics("ACLK_DISABLED", "-", "-");
  1747. int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 444);
  1748. if (fd == -1)
  1749. netdata_log_error("Cannot create file '%s'. Please fix this.", filename);
  1750. else
  1751. close(fd);
  1752. }
  1753. #endif
  1754. // ------------------------------------------------------------------------
  1755. // initialize WebRTC
  1756. webrtc_initialize();
  1757. // ------------------------------------------------------------------------
  1758. // unblock signals
  1759. signals_unblock();
  1760. // ------------------------------------------------------------------------
  1761. // Handle signals
  1762. signals_handle();
  1763. // should never reach this point
  1764. // but we need it for rpmlint #2752
  1765. return 1;
  1766. }