main.c 89 KB

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