main.c 90 KB

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