rrdhost.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #define NETDATA_RRD_INTERNALS
  3. #include "rrd.h"
  4. RRDHOST *localhost = NULL;
  5. size_t rrd_hosts_available = 0;
  6. netdata_rwlock_t rrd_rwlock = NETDATA_RWLOCK_INITIALIZER;
  7. time_t rrdset_free_obsolete_time = 3600;
  8. time_t rrdhost_free_orphan_time = 3600;
  9. // ----------------------------------------------------------------------------
  10. // RRDHOST index
  11. int rrdhost_compare(void* a, void* b) {
  12. if(((RRDHOST *)a)->hash_machine_guid < ((RRDHOST *)b)->hash_machine_guid) return -1;
  13. else if(((RRDHOST *)a)->hash_machine_guid > ((RRDHOST *)b)->hash_machine_guid) return 1;
  14. else return strcmp(((RRDHOST *)a)->machine_guid, ((RRDHOST *)b)->machine_guid);
  15. }
  16. avl_tree_lock rrdhost_root_index = {
  17. .avl_tree = { NULL, rrdhost_compare },
  18. .rwlock = AVL_LOCK_INITIALIZER
  19. };
  20. RRDHOST *rrdhost_find_by_guid(const char *guid, uint32_t hash) {
  21. debug(D_RRDHOST, "Searching in index for host with guid '%s'", guid);
  22. RRDHOST tmp;
  23. strncpyz(tmp.machine_guid, guid, GUID_LEN);
  24. tmp.hash_machine_guid = (hash)?hash:simple_hash(tmp.machine_guid);
  25. return (RRDHOST *)avl_search_lock(&(rrdhost_root_index), (avl_t *) &tmp);
  26. }
  27. RRDHOST *rrdhost_find_by_hostname(const char *hostname, uint32_t hash) {
  28. if(unlikely(!strcmp(hostname, "localhost")))
  29. return localhost;
  30. if(unlikely(!hash)) hash = simple_hash(hostname);
  31. rrd_rdlock();
  32. RRDHOST *host;
  33. rrdhost_foreach_read(host) {
  34. if(unlikely((hash == host->hash_hostname && !strcmp(hostname, host->hostname)))) {
  35. rrd_unlock();
  36. return host;
  37. }
  38. }
  39. rrd_unlock();
  40. return NULL;
  41. }
  42. #define rrdhost_index_add(rrdhost) (RRDHOST *)avl_insert_lock(&(rrdhost_root_index), (avl_t *)(rrdhost))
  43. #define rrdhost_index_del(rrdhost) (RRDHOST *)avl_remove_lock(&(rrdhost_root_index), (avl_t *)(rrdhost))
  44. // ----------------------------------------------------------------------------
  45. // RRDHOST - internal helpers
  46. static inline void rrdhost_init_tags(RRDHOST *host, const char *tags) {
  47. if(host->tags && tags && !strcmp(host->tags, tags))
  48. return;
  49. void *old = (void *)host->tags;
  50. host->tags = (tags && *tags)?strdupz(tags):NULL;
  51. freez(old);
  52. }
  53. static inline void rrdhost_init_hostname(RRDHOST *host, const char *hostname) {
  54. if(host->hostname && hostname && !strcmp(host->hostname, hostname))
  55. return;
  56. void *old = host->hostname;
  57. host->hostname = strdupz(hostname?hostname:"localhost");
  58. host->hash_hostname = simple_hash(host->hostname);
  59. freez(old);
  60. }
  61. static inline void rrdhost_init_os(RRDHOST *host, const char *os) {
  62. if(host->os && os && !strcmp(host->os, os))
  63. return;
  64. void *old = (void *)host->os;
  65. host->os = strdupz(os?os:"unknown");
  66. freez(old);
  67. }
  68. static inline void rrdhost_init_timezone(RRDHOST *host, const char *timezone, const char *abbrev_timezone, int32_t utc_offset) {
  69. if (host->timezone && timezone && !strcmp(host->timezone, timezone) && host->abbrev_timezone && abbrev_timezone &&
  70. !strcmp(host->abbrev_timezone, abbrev_timezone) && host->utc_offset == utc_offset)
  71. return;
  72. void *old = (void *)host->timezone;
  73. host->timezone = strdupz((timezone && *timezone)?timezone:"unknown");
  74. freez(old);
  75. old = (void *)host->abbrev_timezone;
  76. host->abbrev_timezone = strdupz((abbrev_timezone && *abbrev_timezone) ? abbrev_timezone : "UTC");
  77. freez(old);
  78. host->utc_offset = utc_offset;
  79. }
  80. static inline void rrdhost_init_machine_guid(RRDHOST *host, const char *machine_guid) {
  81. strncpy(host->machine_guid, machine_guid, GUID_LEN);
  82. host->machine_guid[GUID_LEN] = '\0';
  83. host->hash_machine_guid = simple_hash(host->machine_guid);
  84. }
  85. void set_host_properties(RRDHOST *host, int update_every, RRD_MEMORY_MODE memory_mode, const char *hostname,
  86. const char *registry_hostname, const char *guid, const char *os, const char *tags,
  87. const char *tzone, const char *abbrev_tzone, int32_t utc_offset, const char *program_name,
  88. const char *program_version)
  89. {
  90. host->rrd_update_every = update_every;
  91. host->rrd_memory_mode = memory_mode;
  92. rrdhost_init_hostname(host, hostname);
  93. rrdhost_init_machine_guid(host, guid);
  94. rrdhost_init_os(host, os);
  95. rrdhost_init_timezone(host, tzone, abbrev_tzone, utc_offset);
  96. rrdhost_init_tags(host, tags);
  97. host->program_name = strdupz((program_name && *program_name) ? program_name : "unknown");
  98. host->program_version = strdupz((program_version && *program_version) ? program_version : "unknown");
  99. host->registry_hostname = strdupz((registry_hostname && *registry_hostname) ? registry_hostname : host->hostname);
  100. }
  101. // ----------------------------------------------------------------------------
  102. // RRDHOST - add a host
  103. RRDHOST *rrdhost_create(const char *hostname,
  104. const char *registry_hostname,
  105. const char *guid,
  106. const char *os,
  107. const char *timezone,
  108. const char *abbrev_timezone,
  109. int32_t utc_offset,
  110. const char *tags,
  111. const char *program_name,
  112. const char *program_version,
  113. int update_every,
  114. long entries,
  115. RRD_MEMORY_MODE memory_mode,
  116. unsigned int health_enabled,
  117. unsigned int rrdpush_enabled,
  118. char *rrdpush_destination,
  119. char *rrdpush_api_key,
  120. char *rrdpush_send_charts_matching,
  121. struct rrdhost_system_info *system_info,
  122. int is_localhost
  123. ) {
  124. debug(D_RRDHOST, "Host '%s': adding with guid '%s'", hostname, guid);
  125. #ifdef ENABLE_DBENGINE
  126. int is_legacy = (memory_mode == RRD_MEMORY_MODE_DBENGINE) && is_legacy_child(guid);
  127. #else
  128. int is_legacy = 1;
  129. #endif
  130. rrd_check_wrlock();
  131. int is_in_multihost = (memory_mode == RRD_MEMORY_MODE_DBENGINE && !is_legacy);
  132. RRDHOST *host = callocz(1, sizeof(RRDHOST));
  133. set_host_properties(host, (update_every > 0)?update_every:1, memory_mode, hostname, registry_hostname, guid, os,
  134. tags, timezone, abbrev_timezone, utc_offset, program_name, program_version);
  135. host->rrd_history_entries = align_entries_to_pagesize(memory_mode, entries);
  136. host->health_enabled = ((memory_mode == RRD_MEMORY_MODE_NONE)) ? 0 : health_enabled;
  137. host->sender = mallocz(sizeof(*host->sender));
  138. sender_init(host->sender, host);
  139. netdata_mutex_init(&host->receiver_lock);
  140. host->rrdpush_send_enabled = (rrdpush_enabled && rrdpush_destination && *rrdpush_destination && rrdpush_api_key && *rrdpush_api_key) ? 1 : 0;
  141. host->rrdpush_send_destination = (host->rrdpush_send_enabled)?strdupz(rrdpush_destination):NULL;
  142. host->rrdpush_send_api_key = (host->rrdpush_send_enabled)?strdupz(rrdpush_api_key):NULL;
  143. host->rrdpush_send_charts_matching = simple_pattern_create(rrdpush_send_charts_matching, NULL, SIMPLE_PATTERN_EXACT);
  144. host->rrdpush_sender_pipe[0] = -1;
  145. host->rrdpush_sender_pipe[1] = -1;
  146. host->rrdpush_sender_socket = -1;
  147. //host->stream_version = STREAMING_PROTOCOL_CURRENT_VERSION; Unused?
  148. #ifdef ENABLE_HTTPS
  149. host->ssl.conn = NULL;
  150. host->ssl.flags = NETDATA_SSL_START;
  151. host->stream_ssl.conn = NULL;
  152. host->stream_ssl.flags = NETDATA_SSL_START;
  153. #endif
  154. netdata_rwlock_init(&host->rrdhost_rwlock);
  155. netdata_rwlock_init(&host->labels.labels_rwlock);
  156. netdata_mutex_init(&host->aclk_state_lock);
  157. host->system_info = system_info;
  158. avl_init_lock(&(host->rrdset_root_index), rrdset_compare);
  159. avl_init_lock(&(host->rrdset_root_index_name), rrdset_compare_name);
  160. avl_init_lock(&(host->rrdfamily_root_index), rrdfamily_compare);
  161. avl_init_lock(&(host->rrdvar_root_index), rrdvar_compare);
  162. if(config_get_boolean(CONFIG_SECTION_GLOBAL, "delete obsolete charts files", 1))
  163. rrdhost_flag_set(host, RRDHOST_FLAG_DELETE_OBSOLETE_CHARTS);
  164. if(config_get_boolean(CONFIG_SECTION_GLOBAL, "delete orphan hosts files", 1) && !is_localhost)
  165. rrdhost_flag_set(host, RRDHOST_FLAG_DELETE_ORPHAN_HOST);
  166. host->health_default_warn_repeat_every = config_get_duration(CONFIG_SECTION_HEALTH, "default repeat warning", "never");
  167. host->health_default_crit_repeat_every = config_get_duration(CONFIG_SECTION_HEALTH, "default repeat critical", "never");
  168. avl_init_lock(&(host->alarms_idx_health_log), alarm_compare_id);
  169. avl_init_lock(&(host->alarms_idx_name), alarm_compare_name);
  170. // ------------------------------------------------------------------------
  171. // initialize health variables
  172. host->health_log.next_log_id = 1;
  173. host->health_log.next_alarm_id = 1;
  174. host->health_log.max = 1000;
  175. host->health_log.next_log_id = (uint32_t)now_realtime_sec();
  176. host->health_log.next_alarm_id = 0;
  177. long n = config_get_number(CONFIG_SECTION_HEALTH, "in memory max health log entries", host->health_log.max);
  178. if(n < 10) {
  179. error("Host '%s': health configuration has invalid max log entries %ld. Using default %u", host->hostname, n, host->health_log.max);
  180. config_set_number(CONFIG_SECTION_HEALTH, "in memory max health log entries", (long)host->health_log.max);
  181. }
  182. else
  183. host->health_log.max = (unsigned int)n;
  184. netdata_rwlock_init(&host->health_log.alarm_log_rwlock);
  185. char filename[FILENAME_MAX + 1];
  186. if(is_localhost) {
  187. host->cache_dir = strdupz(netdata_configured_cache_dir);
  188. host->varlib_dir = strdupz(netdata_configured_varlib_dir);
  189. }
  190. else {
  191. // this is not localhost - append our GUID to localhost path
  192. if (is_in_multihost) { // don't append to cache dir in multihost
  193. host->cache_dir = strdupz(netdata_configured_cache_dir);
  194. } else {
  195. snprintfz(filename, FILENAME_MAX, "%s/%s", netdata_configured_cache_dir, host->machine_guid);
  196. host->cache_dir = strdupz(filename);
  197. }
  198. if((host->rrd_memory_mode == RRD_MEMORY_MODE_MAP || host->rrd_memory_mode == RRD_MEMORY_MODE_SAVE || (
  199. host->rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE && is_legacy))) {
  200. int r = mkdir(host->cache_dir, 0775);
  201. if(r != 0 && errno != EEXIST)
  202. error("Host '%s': cannot create directory '%s'", host->hostname, host->cache_dir);
  203. }
  204. snprintfz(filename, FILENAME_MAX, "%s/%s", netdata_configured_varlib_dir, host->machine_guid);
  205. host->varlib_dir = strdupz(filename);
  206. if(host->health_enabled) {
  207. int r = mkdir(host->varlib_dir, 0775);
  208. if(r != 0 && errno != EEXIST)
  209. error("Host '%s': cannot create directory '%s'", host->hostname, host->varlib_dir);
  210. }
  211. }
  212. if(host->health_enabled) {
  213. snprintfz(filename, FILENAME_MAX, "%s/health", host->varlib_dir);
  214. int r = mkdir(filename, 0775);
  215. if(r != 0 && errno != EEXIST)
  216. error("Host '%s': cannot create directory '%s'", host->hostname, filename);
  217. }
  218. snprintfz(filename, FILENAME_MAX, "%s/health/health-log.db", host->varlib_dir);
  219. host->health_log_filename = strdupz(filename);
  220. snprintfz(filename, FILENAME_MAX, "%s/alarm-notify.sh", netdata_configured_primary_plugins_dir);
  221. host->health_default_exec = strdupz(config_get(CONFIG_SECTION_HEALTH, "script to execute on alarm", filename));
  222. host->health_default_recipient = strdupz("root");
  223. // ------------------------------------------------------------------------
  224. // load health configuration
  225. if(host->health_enabled) {
  226. rrdhost_wrlock(host);
  227. health_readdir(host, health_user_config_dir(), health_stock_config_dir(), NULL);
  228. rrdhost_unlock(host);
  229. health_alarm_log_load(host);
  230. health_alarm_log_open(host);
  231. }
  232. RRDHOST *t = rrdhost_index_add(host);
  233. if(t != host) {
  234. error("Host '%s': cannot add host with machine guid '%s' to index. It already exists as host '%s' with machine guid '%s'.", host->hostname, host->machine_guid, t->hostname, t->machine_guid);
  235. rrdhost_free(host);
  236. return NULL;
  237. }
  238. if (likely(!uuid_parse(host->machine_guid, host->host_uuid))) {
  239. int rc = sql_store_host(&host->host_uuid, hostname, registry_hostname, update_every, os, timezone, tags);
  240. if (unlikely(rc))
  241. error_report("Failed to store machine GUID to the database");
  242. sql_load_node_id(host);
  243. }
  244. else
  245. error_report("Host machine GUID %s is not valid", host->machine_guid);
  246. if (host->rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE) {
  247. #ifdef ENABLE_DBENGINE
  248. char dbenginepath[FILENAME_MAX + 1];
  249. int ret;
  250. snprintfz(dbenginepath, FILENAME_MAX, "%s/dbengine", host->cache_dir);
  251. ret = mkdir(dbenginepath, 0775);
  252. if (ret != 0 && errno != EEXIST)
  253. error("Host '%s': cannot create directory '%s'", host->hostname, dbenginepath);
  254. else ret = 0; // succeed
  255. if (is_legacy) // initialize legacy dbengine instance as needed
  256. ret = rrdeng_init(host, &host->rrdeng_ctx, dbenginepath, default_rrdeng_page_cache_mb,
  257. default_rrdeng_disk_quota_mb); // may fail here for legacy dbengine initialization
  258. else
  259. host->rrdeng_ctx = &multidb_ctx;
  260. if (ret) { // check legacy or multihost initialization success
  261. error(
  262. "Host '%s': cannot initialize host with machine guid '%s'. Failed to initialize DB engine at '%s'.",
  263. host->hostname, host->machine_guid, host->cache_dir);
  264. rrdhost_free(host);
  265. host = NULL;
  266. //rrd_hosts_available++; //TODO: maybe we want this?
  267. return host;
  268. }
  269. #else
  270. fatal("RRD_MEMORY_MODE_DBENGINE is not supported in this platform.");
  271. #endif
  272. }
  273. else {
  274. #ifdef ENABLE_DBENGINE
  275. host->rrdeng_ctx = &multidb_ctx;
  276. #endif
  277. }
  278. // ------------------------------------------------------------------------
  279. // link it and add it to the index
  280. if(is_localhost) {
  281. host->next = localhost;
  282. localhost = host;
  283. }
  284. else {
  285. if(localhost) {
  286. host->next = localhost->next;
  287. localhost->next = host;
  288. }
  289. else localhost = host;
  290. }
  291. info("Host '%s' (at registry as '%s') with guid '%s' initialized"
  292. ", os '%s'"
  293. ", timezone '%s'"
  294. ", tags '%s'"
  295. ", program_name '%s'"
  296. ", program_version '%s'"
  297. ", update every %d"
  298. ", memory mode %s"
  299. ", history entries %ld"
  300. ", streaming %s"
  301. " (to '%s' with api key '%s')"
  302. ", health %s"
  303. ", cache_dir '%s'"
  304. ", varlib_dir '%s'"
  305. ", health_log '%s'"
  306. ", alarms default handler '%s'"
  307. ", alarms default recipient '%s'"
  308. , host->hostname
  309. , host->registry_hostname
  310. , host->machine_guid
  311. , host->os
  312. , host->timezone
  313. , (host->tags)?host->tags:""
  314. , host->program_name
  315. , host->program_version
  316. , host->rrd_update_every
  317. , rrd_memory_mode_name(host->rrd_memory_mode)
  318. , host->rrd_history_entries
  319. , host->rrdpush_send_enabled?"enabled":"disabled"
  320. , host->rrdpush_send_destination?host->rrdpush_send_destination:""
  321. , host->rrdpush_send_api_key?host->rrdpush_send_api_key:""
  322. , host->health_enabled?"enabled":"disabled"
  323. , host->cache_dir
  324. , host->varlib_dir
  325. , host->health_log_filename
  326. , host->health_default_exec
  327. , host->health_default_recipient
  328. );
  329. rrd_hosts_available++;
  330. return host;
  331. }
  332. void rrdhost_update(RRDHOST *host
  333. , const char *hostname
  334. , const char *registry_hostname
  335. , const char *guid
  336. , const char *os
  337. , const char *timezone
  338. , const char *abbrev_timezone
  339. , int32_t utc_offset
  340. , const char *tags
  341. , const char *program_name
  342. , const char *program_version
  343. , int update_every
  344. , long history
  345. , RRD_MEMORY_MODE mode
  346. , unsigned int health_enabled
  347. , unsigned int rrdpush_enabled
  348. , char *rrdpush_destination
  349. , char *rrdpush_api_key
  350. , char *rrdpush_send_charts_matching
  351. , struct rrdhost_system_info *system_info
  352. )
  353. {
  354. UNUSED(guid);
  355. UNUSED(rrdpush_enabled);
  356. UNUSED(rrdpush_destination);
  357. UNUSED(rrdpush_api_key);
  358. UNUSED(rrdpush_send_charts_matching);
  359. host->health_enabled = (mode == RRD_MEMORY_MODE_NONE) ? 0 : health_enabled;
  360. //host->stream_version = STREAMING_PROTOCOL_CURRENT_VERSION; Unused?
  361. rrdhost_system_info_free(host->system_info);
  362. host->system_info = system_info;
  363. rrdhost_init_os(host, os);
  364. rrdhost_init_timezone(host, timezone, abbrev_timezone, utc_offset);
  365. freez(host->registry_hostname);
  366. host->registry_hostname = strdupz((registry_hostname && *registry_hostname)?registry_hostname:hostname);
  367. if(strcmp(host->hostname, hostname) != 0) {
  368. info("Host '%s' has been renamed to '%s'. If this is not intentional it may mean multiple hosts are using the same machine_guid.", host->hostname, hostname);
  369. char *t = host->hostname;
  370. host->hostname = strdupz(hostname);
  371. host->hash_hostname = simple_hash(host->hostname);
  372. freez(t);
  373. }
  374. if(strcmp(host->program_name, program_name) != 0) {
  375. info("Host '%s' switched program name from '%s' to '%s'", host->hostname, host->program_name, program_name);
  376. char *t = host->program_name;
  377. host->program_name = strdupz(program_name);
  378. freez(t);
  379. }
  380. if(strcmp(host->program_version, program_version) != 0) {
  381. info("Host '%s' switched program version from '%s' to '%s'", host->hostname, host->program_version, program_version);
  382. char *t = host->program_version;
  383. host->program_version = strdupz(program_version);
  384. freez(t);
  385. }
  386. if(host->rrd_update_every != update_every)
  387. error("Host '%s' has an update frequency of %d seconds, but the wanted one is %d seconds. Restart netdata here to apply the new settings.", host->hostname, host->rrd_update_every, update_every);
  388. if(host->rrd_history_entries < history)
  389. error("Host '%s' has history of %ld entries, but the wanted one is %ld entries. Restart netdata here to apply the new settings.", host->hostname, host->rrd_history_entries, history);
  390. if(host->rrd_memory_mode != mode)
  391. error("Host '%s' has memory mode '%s', but the wanted one is '%s'. Restart netdata here to apply the new settings.", host->hostname, rrd_memory_mode_name(host->rrd_memory_mode), rrd_memory_mode_name(mode));
  392. // update host tags
  393. rrdhost_init_tags(host, tags);
  394. if (rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED)) {
  395. rrdhost_flag_clear(host, RRDHOST_FLAG_ARCHIVED);
  396. if(host->health_enabled) {
  397. int r;
  398. char filename[FILENAME_MAX + 1];
  399. if (host != localhost) {
  400. r = mkdir(host->varlib_dir, 0775);
  401. if (r != 0 && errno != EEXIST)
  402. error("Host '%s': cannot create directory '%s'", host->hostname, host->varlib_dir);
  403. }
  404. snprintfz(filename, FILENAME_MAX, "%s/health", host->varlib_dir);
  405. r = mkdir(filename, 0775);
  406. if(r != 0 && errno != EEXIST)
  407. error("Host '%s': cannot create directory '%s'", host->hostname, filename);
  408. rrdhost_wrlock(host);
  409. health_readdir(host, health_user_config_dir(), health_stock_config_dir(), NULL);
  410. rrdhost_unlock(host);
  411. health_alarm_log_load(host);
  412. health_alarm_log_open(host);
  413. }
  414. rrd_hosts_available++;
  415. info("Host %s is not in archived mode anymore", host->hostname);
  416. }
  417. return;
  418. }
  419. RRDHOST *rrdhost_find_or_create(
  420. const char *hostname
  421. , const char *registry_hostname
  422. , const char *guid
  423. , const char *os
  424. , const char *timezone
  425. , const char *abbrev_timezone
  426. , int32_t utc_offset
  427. , const char *tags
  428. , const char *program_name
  429. , const char *program_version
  430. , int update_every
  431. , long history
  432. , RRD_MEMORY_MODE mode
  433. , unsigned int health_enabled
  434. , unsigned int rrdpush_enabled
  435. , char *rrdpush_destination
  436. , char *rrdpush_api_key
  437. , char *rrdpush_send_charts_matching
  438. , struct rrdhost_system_info *system_info
  439. ) {
  440. debug(D_RRDHOST, "Searching for host '%s' with guid '%s'", hostname, guid);
  441. rrd_wrlock();
  442. RRDHOST *host = rrdhost_find_by_guid(guid, 0);
  443. if (unlikely(host && RRD_MEMORY_MODE_DBENGINE != mode && rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))) {
  444. /* If a legacy memory mode instantiates all dbengine state must be discarded to avoid inconsistencies */
  445. error("Archived host '%s' has memory mode '%s', but the wanted one is '%s'. Discarding archived state.",
  446. host->hostname, rrd_memory_mode_name(host->rrd_memory_mode), rrd_memory_mode_name(mode));
  447. rrdhost_free(host);
  448. host = NULL;
  449. }
  450. if(!host) {
  451. host = rrdhost_create(
  452. hostname
  453. , registry_hostname
  454. , guid
  455. , os
  456. , timezone
  457. , abbrev_timezone
  458. , utc_offset
  459. , tags
  460. , program_name
  461. , program_version
  462. , update_every
  463. , history
  464. , mode
  465. , health_enabled
  466. , rrdpush_enabled
  467. , rrdpush_destination
  468. , rrdpush_api_key
  469. , rrdpush_send_charts_matching
  470. , system_info
  471. , 0
  472. );
  473. }
  474. else {
  475. rrdhost_update(host
  476. , hostname
  477. , registry_hostname
  478. , guid
  479. , os
  480. , timezone
  481. , abbrev_timezone
  482. , utc_offset
  483. , tags
  484. , program_name
  485. , program_version
  486. , update_every
  487. , history
  488. , mode
  489. , health_enabled
  490. , rrdpush_enabled
  491. , rrdpush_destination
  492. , rrdpush_api_key
  493. , rrdpush_send_charts_matching
  494. , system_info);
  495. }
  496. if (host) {
  497. rrdhost_wrlock(host);
  498. rrdhost_flag_clear(host, RRDHOST_FLAG_ORPHAN);
  499. host->senders_disconnected_time = 0;
  500. rrdhost_unlock(host);
  501. }
  502. rrdhost_cleanup_orphan_hosts_nolock(host);
  503. rrd_unlock();
  504. return host;
  505. }
  506. inline int rrdhost_should_be_removed(RRDHOST *host, RRDHOST *protected_host, time_t now) {
  507. if(host != protected_host
  508. && host != localhost
  509. && rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN)
  510. && host->receiver
  511. && host->senders_disconnected_time
  512. && host->senders_disconnected_time + rrdhost_free_orphan_time < now)
  513. return 1;
  514. return 0;
  515. }
  516. void rrdhost_cleanup_orphan_hosts_nolock(RRDHOST *protected_host) {
  517. time_t now = now_realtime_sec();
  518. RRDHOST *host;
  519. restart_after_removal:
  520. rrdhost_foreach_write(host) {
  521. if(rrdhost_should_be_removed(host, protected_host, now)) {
  522. info("Host '%s' with machine guid '%s' is obsolete - cleaning up.", host->hostname, host->machine_guid);
  523. if (rrdhost_flag_check(host, RRDHOST_FLAG_DELETE_ORPHAN_HOST)
  524. #ifdef ENABLE_DBENGINE
  525. /* don't delete multi-host DB host files */
  526. && !(host->rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE && host->rrdeng_ctx == &multidb_ctx)
  527. #endif
  528. )
  529. rrdhost_delete_charts(host);
  530. else
  531. rrdhost_save_charts(host);
  532. rrdhost_free(host);
  533. goto restart_after_removal;
  534. }
  535. }
  536. }
  537. // ----------------------------------------------------------------------------
  538. // RRDHOST global / startup initialization
  539. int rrd_init(char *hostname, struct rrdhost_system_info *system_info) {
  540. rrdset_free_obsolete_time = config_get_number(CONFIG_SECTION_GLOBAL, "cleanup obsolete charts after seconds", rrdset_free_obsolete_time);
  541. // Current chart locking and invalidation scheme doesn't prevent Netdata from segmentaion faults if a short
  542. // cleanup delay is set. Extensive stress tests showed that 10 seconds is quite a safe delay. Look at
  543. // https://github.com/netdata/netdata/pull/11222#issuecomment-868367920 for more information.
  544. if (rrdset_free_obsolete_time < 10) {
  545. rrdset_free_obsolete_time = 10;
  546. info("The \"cleanup obsolete charts after seconds\" option was set to 10 seconds. A lower delay can potentially cause a segmentaion fault.");
  547. }
  548. gap_when_lost_iterations_above = (int)config_get_number(CONFIG_SECTION_GLOBAL, "gap when lost iterations above", gap_when_lost_iterations_above);
  549. if (gap_when_lost_iterations_above < 1)
  550. gap_when_lost_iterations_above = 1;
  551. if (unlikely(sql_init_database())) {
  552. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  553. fatal("Failed to initialize SQLite");
  554. info("Skipping SQLITE metadata initialization since memory mode is not db engine");
  555. }
  556. health_init();
  557. rrdpush_init();
  558. debug(D_RRDHOST, "Initializing localhost with hostname '%s'", hostname);
  559. rrd_wrlock();
  560. localhost = rrdhost_create(
  561. hostname
  562. , registry_get_this_machine_hostname()
  563. , registry_get_this_machine_guid()
  564. , os_type
  565. , netdata_configured_timezone
  566. , netdata_configured_abbrev_timezone
  567. , netdata_configured_utc_offset
  568. , config_get(CONFIG_SECTION_BACKEND, "host tags", "")
  569. , program_name
  570. , program_version
  571. , default_rrd_update_every
  572. , default_rrd_history_entries
  573. , default_rrd_memory_mode
  574. , default_health_enabled
  575. , default_rrdpush_enabled
  576. , default_rrdpush_destination
  577. , default_rrdpush_api_key
  578. , default_rrdpush_send_charts_matching
  579. , system_info
  580. , 1
  581. );
  582. if (unlikely(!localhost)) {
  583. rrd_unlock();
  584. return 1;
  585. }
  586. #ifdef ENABLE_DBENGINE
  587. char dbenginepath[FILENAME_MAX + 1];
  588. int ret;
  589. snprintfz(dbenginepath, FILENAME_MAX, "%s/dbengine", localhost->cache_dir);
  590. ret = mkdir(dbenginepath, 0775);
  591. if (ret != 0 && errno != EEXIST)
  592. error("Host '%s': cannot create directory '%s'", localhost->hostname, dbenginepath);
  593. else // Unconditionally create multihost db to support on demand host creation
  594. ret = rrdeng_init(NULL, NULL, dbenginepath, default_rrdeng_page_cache_mb, default_multidb_disk_quota_mb);
  595. if (ret) {
  596. error(
  597. "Host '%s' with machine guid '%s' failed to initialize multi-host DB engine instance at '%s'.",
  598. localhost->hostname, localhost->machine_guid, localhost->cache_dir);
  599. rrdhost_free(localhost);
  600. localhost = NULL;
  601. rrd_unlock();
  602. fatal("Failed to initialize dbengine");
  603. }
  604. #endif
  605. rrd_unlock();
  606. web_client_api_v1_management_init();
  607. return localhost==NULL;
  608. }
  609. // ----------------------------------------------------------------------------
  610. // RRDHOST - lock validations
  611. // there are only used when NETDATA_INTERNAL_CHECKS is set
  612. void __rrdhost_check_rdlock(RRDHOST *host, const char *file, const char *function, const unsigned long line) {
  613. debug(D_RRDHOST, "Checking read lock on host '%s'", host->hostname);
  614. int ret = netdata_rwlock_trywrlock(&host->rrdhost_rwlock);
  615. if(ret == 0)
  616. fatal("RRDHOST '%s' should be read-locked, but it is not, at function %s() at line %lu of file '%s'", host->hostname, function, line, file);
  617. }
  618. void __rrdhost_check_wrlock(RRDHOST *host, const char *file, const char *function, const unsigned long line) {
  619. debug(D_RRDHOST, "Checking write lock on host '%s'", host->hostname);
  620. int ret = netdata_rwlock_tryrdlock(&host->rrdhost_rwlock);
  621. if(ret == 0)
  622. fatal("RRDHOST '%s' should be write-locked, but it is not, at function %s() at line %lu of file '%s'", host->hostname, function, line, file);
  623. }
  624. void __rrd_check_rdlock(const char *file, const char *function, const unsigned long line) {
  625. debug(D_RRDHOST, "Checking read lock on all RRDs");
  626. int ret = netdata_rwlock_trywrlock(&rrd_rwlock);
  627. if(ret == 0)
  628. fatal("RRDs should be read-locked, but it are not, at function %s() at line %lu of file '%s'", function, line, file);
  629. }
  630. void __rrd_check_wrlock(const char *file, const char *function, const unsigned long line) {
  631. debug(D_RRDHOST, "Checking write lock on all RRDs");
  632. int ret = netdata_rwlock_tryrdlock(&rrd_rwlock);
  633. if(ret == 0)
  634. fatal("RRDs should be write-locked, but it are not, at function %s() at line %lu of file '%s'", function, line, file);
  635. }
  636. // ----------------------------------------------------------------------------
  637. // RRDHOST - free
  638. void rrdhost_system_info_free(struct rrdhost_system_info *system_info) {
  639. info("SYSTEM_INFO: free %p", system_info);
  640. if(likely(system_info)) {
  641. freez(system_info->host_os_name);
  642. freez(system_info->host_os_id);
  643. freez(system_info->host_os_id_like);
  644. freez(system_info->host_os_version);
  645. freez(system_info->host_os_version_id);
  646. freez(system_info->host_os_detection);
  647. freez(system_info->host_cores);
  648. freez(system_info->host_cpu_freq);
  649. freez(system_info->host_ram_total);
  650. freez(system_info->host_disk_space);
  651. freez(system_info->container_os_name);
  652. freez(system_info->container_os_id);
  653. freez(system_info->container_os_id_like);
  654. freez(system_info->container_os_version);
  655. freez(system_info->container_os_version_id);
  656. freez(system_info->container_os_detection);
  657. freez(system_info->kernel_name);
  658. freez(system_info->kernel_version);
  659. freez(system_info->architecture);
  660. freez(system_info->virtualization);
  661. freez(system_info->virt_detection);
  662. freez(system_info->container);
  663. freez(system_info->container_detection);
  664. freez(system_info->is_k8s_node);
  665. freez(system_info);
  666. }
  667. }
  668. void destroy_receiver_state(struct receiver_state *rpt);
  669. void rrdhost_free(RRDHOST *host) {
  670. if(!host) return;
  671. info("Freeing all memory for host '%s'...", host->hostname);
  672. rrd_check_wrlock(); // make sure the RRDs are write locked
  673. // ------------------------------------------------------------------------
  674. // clean up streaming
  675. rrdpush_sender_thread_stop(host); // stop a possibly running thread
  676. cbuffer_free(host->sender->buffer);
  677. buffer_free(host->sender->build);
  678. freez(host->sender);
  679. host->sender = NULL;
  680. if (netdata_exit) {
  681. netdata_mutex_lock(&host->receiver_lock);
  682. if (host->receiver) {
  683. if (!host->receiver->exited)
  684. netdata_thread_cancel(host->receiver->thread);
  685. netdata_mutex_unlock(&host->receiver_lock);
  686. struct receiver_state *rpt = host->receiver;
  687. while (host->receiver && !rpt->exited)
  688. sleep_usec(50 * USEC_PER_MS);
  689. // If the receiver detached from the host then its thread will destroy the state
  690. if (host->receiver == rpt)
  691. destroy_receiver_state(host->receiver);
  692. }
  693. else
  694. netdata_mutex_unlock(&host->receiver_lock);
  695. }
  696. rrdhost_wrlock(host); // lock this RRDHOST
  697. // ------------------------------------------------------------------------
  698. // release its children resources
  699. #ifdef ENABLE_DBENGINE
  700. if (host->rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE) {
  701. if (host->rrdeng_ctx != &multidb_ctx)
  702. rrdeng_prepare_exit(host->rrdeng_ctx);
  703. }
  704. #endif
  705. while(host->rrdset_root)
  706. rrdset_free(host->rrdset_root);
  707. freez(host->exporting_flags);
  708. while(host->alarms)
  709. rrdcalc_unlink_and_free(host, host->alarms);
  710. RRDCALC *rc,*nc;
  711. for(rc = host->alarms_with_foreach; rc ; rc = nc) {
  712. nc = rc->next;
  713. rrdcalc_free(rc);
  714. }
  715. host->alarms_with_foreach = NULL;
  716. while(host->templates)
  717. rrdcalctemplate_unlink_and_free(host, host->templates);
  718. RRDCALCTEMPLATE *rt,*next;
  719. for(rt = host->alarms_template_with_foreach; rt ; rt = next) {
  720. next = rt->next;
  721. rrdcalctemplate_free(rt);
  722. }
  723. host->alarms_template_with_foreach = NULL;
  724. debug(D_RRD_CALLS, "RRDHOST: Cleaning up remaining host variables for host '%s'", host->hostname);
  725. rrdvar_free_remaining_variables(host, &host->rrdvar_root_index);
  726. health_alarm_log_free(host);
  727. #ifdef ENABLE_DBENGINE
  728. if (host->rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE && host->rrdeng_ctx != &multidb_ctx)
  729. rrdeng_exit(host->rrdeng_ctx);
  730. #endif
  731. // ------------------------------------------------------------------------
  732. // remove it from the indexes
  733. if(rrdhost_index_del(host) != host)
  734. error("RRDHOST '%s' removed from index, deleted the wrong entry.", host->hostname);
  735. // ------------------------------------------------------------------------
  736. // unlink it from the host
  737. if(host == localhost) {
  738. localhost = host->next;
  739. }
  740. else {
  741. // find the previous one
  742. RRDHOST *h;
  743. for(h = localhost; h && h->next != host ; h = h->next) ;
  744. // bypass it
  745. if(h) h->next = host->next;
  746. else error("Request to free RRDHOST '%s': cannot find it", host->hostname);
  747. }
  748. // ------------------------------------------------------------------------
  749. // free it
  750. pthread_mutex_destroy(&host->aclk_state_lock);
  751. freez(host->aclk_state.claimed_id);
  752. freez((void *)host->tags);
  753. free_label_list(host->labels.head);
  754. freez((void *)host->os);
  755. freez((void *)host->timezone);
  756. freez((void *)host->abbrev_timezone);
  757. freez(host->program_version);
  758. freez(host->program_name);
  759. rrdhost_system_info_free(host->system_info);
  760. freez(host->cache_dir);
  761. freez(host->varlib_dir);
  762. freez(host->rrdpush_send_api_key);
  763. freez(host->rrdpush_send_destination);
  764. freez(host->health_default_exec);
  765. freez(host->health_default_recipient);
  766. freez(host->health_log_filename);
  767. freez(host->hostname);
  768. freez(host->registry_hostname);
  769. simple_pattern_free(host->rrdpush_send_charts_matching);
  770. rrdhost_unlock(host);
  771. netdata_rwlock_destroy(&host->labels.labels_rwlock);
  772. netdata_rwlock_destroy(&host->health_log.alarm_log_rwlock);
  773. netdata_rwlock_destroy(&host->rrdhost_rwlock);
  774. freez(host->node_id);
  775. freez(host);
  776. rrd_hosts_available--;
  777. }
  778. void rrdhost_free_all(void) {
  779. rrd_wrlock();
  780. /* Make sure child-hosts are released before the localhost. */
  781. while(localhost->next) rrdhost_free(localhost->next);
  782. rrdhost_free(localhost);
  783. rrd_unlock();
  784. }
  785. // ----------------------------------------------------------------------------
  786. // RRDHOST - save host files
  787. void rrdhost_save_charts(RRDHOST *host) {
  788. if(!host) return;
  789. info("Saving/Closing database of host '%s'...", host->hostname);
  790. RRDSET *st;
  791. // we get a write lock
  792. // to ensure only one thread is saving the database
  793. rrdhost_wrlock(host);
  794. rrdset_foreach_write(st, host) {
  795. rrdset_rdlock(st);
  796. rrdset_save(st);
  797. rrdset_unlock(st);
  798. }
  799. rrdhost_unlock(host);
  800. }
  801. static struct label *rrdhost_load_auto_labels(void)
  802. {
  803. struct label *label_list = NULL;
  804. if (localhost->system_info->host_os_name)
  805. label_list =
  806. add_label_to_list(label_list, "_os_name", localhost->system_info->host_os_name, LABEL_SOURCE_AUTO);
  807. if (localhost->system_info->host_os_version)
  808. label_list =
  809. add_label_to_list(label_list, "_os_version", localhost->system_info->host_os_version, LABEL_SOURCE_AUTO);
  810. if (localhost->system_info->kernel_version)
  811. label_list =
  812. add_label_to_list(label_list, "_kernel_version", localhost->system_info->kernel_version, LABEL_SOURCE_AUTO);
  813. if (localhost->system_info->host_cores)
  814. label_list =
  815. add_label_to_list(label_list, "_system_cores", localhost->system_info->host_cores, LABEL_SOURCE_AUTO);
  816. if (localhost->system_info->host_cpu_freq)
  817. label_list =
  818. add_label_to_list(label_list, "_system_cpu_freq", localhost->system_info->host_cpu_freq, LABEL_SOURCE_AUTO);
  819. if (localhost->system_info->host_ram_total)
  820. label_list =
  821. add_label_to_list(label_list, "_system_ram_total", localhost->system_info->host_ram_total, LABEL_SOURCE_AUTO);
  822. if (localhost->system_info->host_disk_space)
  823. label_list =
  824. add_label_to_list(label_list, "_system_disk_space", localhost->system_info->host_disk_space, LABEL_SOURCE_AUTO);
  825. if (localhost->system_info->architecture)
  826. label_list =
  827. add_label_to_list(label_list, "_architecture", localhost->system_info->architecture, LABEL_SOURCE_AUTO);
  828. if (localhost->system_info->virtualization)
  829. label_list =
  830. add_label_to_list(label_list, "_virtualization", localhost->system_info->virtualization, LABEL_SOURCE_AUTO);
  831. if (localhost->system_info->container)
  832. label_list =
  833. add_label_to_list(label_list, "_container", localhost->system_info->container, LABEL_SOURCE_AUTO);
  834. if (localhost->system_info->container_detection)
  835. label_list =
  836. add_label_to_list(label_list, "_container_detection", localhost->system_info->container_detection, LABEL_SOURCE_AUTO);
  837. if (localhost->system_info->virt_detection)
  838. label_list =
  839. add_label_to_list(label_list, "_virt_detection", localhost->system_info->virt_detection, LABEL_SOURCE_AUTO);
  840. if (localhost->system_info->is_k8s_node)
  841. label_list =
  842. add_label_to_list(label_list, "_is_k8s_node", localhost->system_info->is_k8s_node, LABEL_SOURCE_AUTO);
  843. label_list = add_aclk_host_labels(label_list);
  844. label_list = add_label_to_list(
  845. label_list, "_is_parent", (localhost->next || configured_as_parent()) ? "true" : "false", LABEL_SOURCE_AUTO);
  846. if (localhost->rrdpush_send_destination)
  847. label_list =
  848. add_label_to_list(label_list, "_streams_to", localhost->rrdpush_send_destination, LABEL_SOURCE_AUTO);
  849. return label_list;
  850. }
  851. static inline int rrdhost_is_valid_label_config_option(char *name, char *value)
  852. {
  853. return (is_valid_label_key(name) && is_valid_label_value(value) && strcmp(name, "from environment") &&
  854. strcmp(name, "from kubernetes pods"));
  855. }
  856. static struct label *rrdhost_load_config_labels()
  857. {
  858. int status = config_load(NULL, 1, CONFIG_SECTION_HOST_LABEL);
  859. if(!status) {
  860. char *filename = CONFIG_DIR "/" CONFIG_FILENAME;
  861. error("LABEL: Cannot reload the configuration file '%s', using labels in memory", filename);
  862. }
  863. struct label *l = NULL;
  864. struct section *co = appconfig_get_section(&netdata_config, CONFIG_SECTION_HOST_LABEL);
  865. if(co) {
  866. config_section_wrlock(co);
  867. struct config_option *cv;
  868. for(cv = co->values; cv ; cv = cv->next) {
  869. if(rrdhost_is_valid_label_config_option(cv->name, cv->value)) {
  870. l = add_label_to_list(l, cv->name, cv->value, LABEL_SOURCE_NETDATA_CONF);
  871. cv->flags |= CONFIG_VALUE_USED;
  872. } else {
  873. error("LABELS: It was not possible to create the label '%s' because it contains invalid character(s) or values."
  874. , cv->name);
  875. }
  876. }
  877. config_section_unlock(co);
  878. }
  879. return l;
  880. }
  881. struct label *parse_simple_tags(
  882. struct label *label_list,
  883. const char *tags,
  884. char key_value_separator,
  885. char label_separator,
  886. STRIP_QUOTES_OPTION strip_quotes_from_key,
  887. STRIP_QUOTES_OPTION strip_quotes_from_value,
  888. SKIP_ESCAPED_CHARACTERS_OPTION skip_escaped_characters)
  889. {
  890. const char *end = tags;
  891. while (*end) {
  892. const char *start = end;
  893. char key[CONFIG_MAX_VALUE + 1];
  894. char value[CONFIG_MAX_VALUE + 1];
  895. while (*end && *end != key_value_separator)
  896. end++;
  897. strncpyz(key, start, end - start);
  898. if (*end)
  899. start = ++end;
  900. while (*end && *end != label_separator)
  901. end++;
  902. strncpyz(value, start, end - start);
  903. label_list = add_label_to_list(
  904. label_list,
  905. strip_quotes_from_key ? strip_double_quotes(trim(key), skip_escaped_characters) : trim(key),
  906. strip_quotes_from_value ? strip_double_quotes(trim(value), skip_escaped_characters) : trim(value),
  907. LABEL_SOURCE_NETDATA_CONF);
  908. if (*end)
  909. end++;
  910. }
  911. return label_list;
  912. }
  913. struct label *parse_json_tags(struct label *label_list, const char *tags)
  914. {
  915. char tags_buf[CONFIG_MAX_VALUE + 1];
  916. strncpy(tags_buf, tags, CONFIG_MAX_VALUE);
  917. char *str = tags_buf;
  918. switch (*str) {
  919. case '{':
  920. str++;
  921. strip_last_symbol(str, '}', SKIP_ESCAPED_CHARACTERS);
  922. label_list = parse_simple_tags(label_list, str, ':', ',', STRIP_QUOTES, STRIP_QUOTES, SKIP_ESCAPED_CHARACTERS);
  923. break;
  924. case '[':
  925. str++;
  926. strip_last_symbol(str, ']', SKIP_ESCAPED_CHARACTERS);
  927. char *end = str + strlen(str);
  928. size_t i = 0;
  929. while (str < end) {
  930. char key[CONFIG_MAX_VALUE + 1];
  931. snprintfz(key, CONFIG_MAX_VALUE, "host_tag%zu", i);
  932. str = strip_double_quotes(trim(str), SKIP_ESCAPED_CHARACTERS);
  933. label_list = add_label_to_list(label_list, key, str, LABEL_SOURCE_NETDATA_CONF);
  934. // skip to the next element in the array
  935. str += strlen(str) + 1;
  936. while (*str && *str != ',')
  937. str++;
  938. str++;
  939. i++;
  940. }
  941. break;
  942. case '"':
  943. label_list = add_label_to_list(
  944. label_list, "host_tag", strip_double_quotes(str, SKIP_ESCAPED_CHARACTERS), LABEL_SOURCE_NETDATA_CONF);
  945. break;
  946. default:
  947. label_list = add_label_to_list(label_list, "host_tag", str, LABEL_SOURCE_NETDATA_CONF);
  948. break;
  949. }
  950. return label_list;
  951. }
  952. static struct label *rrdhost_load_labels_from_tags(void)
  953. {
  954. if (!localhost->tags)
  955. return NULL;
  956. struct label *label_list = NULL;
  957. BACKEND_TYPE type = BACKEND_TYPE_UNKNOWN;
  958. if (config_exists(CONFIG_SECTION_BACKEND, "enabled")) {
  959. if (config_get_boolean(CONFIG_SECTION_BACKEND, "enabled", CONFIG_BOOLEAN_NO) != CONFIG_BOOLEAN_NO) {
  960. const char *type_name = config_get(CONFIG_SECTION_BACKEND, "type", "graphite");
  961. type = backend_select_type(type_name);
  962. }
  963. }
  964. switch (type) {
  965. case BACKEND_TYPE_GRAPHITE:
  966. label_list = parse_simple_tags(
  967. label_list, localhost->tags, '=', ';', DO_NOT_STRIP_QUOTES, DO_NOT_STRIP_QUOTES,
  968. DO_NOT_SKIP_ESCAPED_CHARACTERS);
  969. break;
  970. case BACKEND_TYPE_OPENTSDB_USING_TELNET:
  971. label_list = parse_simple_tags(
  972. label_list, localhost->tags, '=', ' ', DO_NOT_STRIP_QUOTES, DO_NOT_STRIP_QUOTES,
  973. DO_NOT_SKIP_ESCAPED_CHARACTERS);
  974. break;
  975. case BACKEND_TYPE_OPENTSDB_USING_HTTP:
  976. label_list = parse_simple_tags(
  977. label_list, localhost->tags, ':', ',', STRIP_QUOTES, STRIP_QUOTES,
  978. DO_NOT_SKIP_ESCAPED_CHARACTERS);
  979. break;
  980. case BACKEND_TYPE_JSON:
  981. label_list = parse_json_tags(label_list, localhost->tags);
  982. break;
  983. default:
  984. label_list = parse_simple_tags(
  985. label_list, localhost->tags, '=', ',', DO_NOT_STRIP_QUOTES, STRIP_QUOTES,
  986. DO_NOT_SKIP_ESCAPED_CHARACTERS);
  987. break;
  988. }
  989. return label_list;
  990. }
  991. static struct label *rrdhost_load_kubernetes_labels(void)
  992. {
  993. struct label *l=NULL;
  994. char *label_script = mallocz(sizeof(char) * (strlen(netdata_configured_primary_plugins_dir) + strlen("get-kubernetes-labels.sh") + 2));
  995. sprintf(label_script, "%s/%s", netdata_configured_primary_plugins_dir, "get-kubernetes-labels.sh");
  996. if (unlikely(access(label_script, R_OK) != 0)) {
  997. error("Kubernetes pod label fetching script %s not found.",label_script);
  998. freez(label_script);
  999. } else {
  1000. pid_t command_pid;
  1001. debug(D_RRDHOST, "Attempting to fetch external labels via %s", label_script);
  1002. FILE *fp = mypopen(label_script, &command_pid);
  1003. if(fp) {
  1004. int MAX_LINE_SIZE=300;
  1005. char buffer[MAX_LINE_SIZE + 1];
  1006. while (fgets(buffer, MAX_LINE_SIZE, fp) != NULL) {
  1007. char *name=buffer;
  1008. char *value=buffer;
  1009. while (*value && *value != ':') value++;
  1010. if (*value == ':') {
  1011. *value = '\0';
  1012. value++;
  1013. }
  1014. char *eos=value;
  1015. while (*eos && *eos != '\n') eos++;
  1016. if (*eos == '\n') *eos = '\0';
  1017. if (strlen(value)>0) {
  1018. if (is_valid_label_key(name)){
  1019. l = add_label_to_list(l, name, value, LABEL_SOURCE_KUBERNETES);
  1020. } else {
  1021. info("Ignoring invalid label name '%s'", name);
  1022. }
  1023. } else {
  1024. error("%s outputted unexpected result: '%s'", label_script, name);
  1025. }
  1026. };
  1027. // Non-zero exit code means that all the script output is error messages. We've shown already any message that didn't include a ':'
  1028. // Here we'll inform with an ERROR that the script failed, show whatever (if anything) was added to the list of labels, free the memory and set the return to null
  1029. int retcode=mypclose(fp, command_pid);
  1030. if (retcode) {
  1031. error("%s exited abnormally. No kubernetes labels will be added to the host.", label_script);
  1032. struct label *ll=l;
  1033. while (ll != NULL) {
  1034. info("Ignoring Label [source id=%s]: \"%s\" -> \"%s\"\n", translate_label_source(ll->label_source), ll->key, ll->value);
  1035. ll = ll->next;
  1036. freez(l);
  1037. l=ll;
  1038. }
  1039. }
  1040. }
  1041. freez(label_script);
  1042. }
  1043. return l;
  1044. }
  1045. void reload_host_labels(void)
  1046. {
  1047. struct label *from_auto = rrdhost_load_auto_labels();
  1048. struct label *from_k8s = rrdhost_load_kubernetes_labels();
  1049. struct label *from_config = rrdhost_load_config_labels();
  1050. struct label *from_tags = rrdhost_load_labels_from_tags();
  1051. struct label *new_labels = merge_label_lists(from_auto, from_k8s);
  1052. new_labels = merge_label_lists(new_labels, from_tags);
  1053. new_labels = merge_label_lists(new_labels, from_config);
  1054. rrdhost_rdlock(localhost);
  1055. replace_label_list(&localhost->labels, new_labels);
  1056. health_label_log_save(localhost);
  1057. rrdhost_unlock(localhost);
  1058. /* TODO-GAPS - fix this so that it looks properly at the state and version of the sender
  1059. if(localhost->rrdpush_send_enabled && localhost->rrdpush_sender_buffer){
  1060. localhost->labels.labels_flag |= LABEL_FLAG_UPDATE_STREAM;
  1061. rrdpush_send_labels(localhost);
  1062. }
  1063. */
  1064. health_reload();
  1065. }
  1066. // ----------------------------------------------------------------------------
  1067. // RRDHOST - delete host files
  1068. void rrdhost_delete_charts(RRDHOST *host) {
  1069. if(!host) return;
  1070. info("Deleting database of host '%s'...", host->hostname);
  1071. RRDSET *st;
  1072. // we get a write lock
  1073. // to ensure only one thread is saving the database
  1074. rrdhost_wrlock(host);
  1075. rrdset_foreach_write(st, host) {
  1076. rrdset_rdlock(st);
  1077. rrdset_delete(st);
  1078. rrdset_unlock(st);
  1079. }
  1080. recursively_delete_dir(host->cache_dir, "left over host");
  1081. rrdhost_unlock(host);
  1082. }
  1083. // ----------------------------------------------------------------------------
  1084. // RRDHOST - cleanup host files
  1085. void rrdhost_cleanup_charts(RRDHOST *host) {
  1086. if(!host) return;
  1087. info("Cleaning up database of host '%s'...", host->hostname);
  1088. RRDSET *st;
  1089. uint32_t rrdhost_delete_obsolete_charts = rrdhost_flag_check(host, RRDHOST_FLAG_DELETE_OBSOLETE_CHARTS);
  1090. // we get a write lock
  1091. // to ensure only one thread is saving the database
  1092. rrdhost_wrlock(host);
  1093. rrdset_foreach_write(st, host) {
  1094. rrdset_rdlock(st);
  1095. if(rrdhost_delete_obsolete_charts && rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE))
  1096. rrdset_delete(st);
  1097. else if(rrdhost_delete_obsolete_charts && rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE_DIMENSIONS))
  1098. rrdset_delete_obsolete_dimensions(st);
  1099. else
  1100. rrdset_save(st);
  1101. rrdset_unlock(st);
  1102. }
  1103. rrdhost_unlock(host);
  1104. }
  1105. // ----------------------------------------------------------------------------
  1106. // RRDHOST - save all hosts to disk
  1107. void rrdhost_save_all(void) {
  1108. info("Saving database [%zu hosts(s)]...", rrd_hosts_available);
  1109. rrd_rdlock();
  1110. RRDHOST *host;
  1111. rrdhost_foreach_read(host)
  1112. rrdhost_save_charts(host);
  1113. rrd_unlock();
  1114. }
  1115. // ----------------------------------------------------------------------------
  1116. // RRDHOST - save or delete all hosts from disk
  1117. void rrdhost_cleanup_all(void) {
  1118. info("Cleaning up database [%zu hosts(s)]...", rrd_hosts_available);
  1119. rrd_rdlock();
  1120. RRDHOST *host;
  1121. rrdhost_foreach_read(host) {
  1122. if (host != localhost && rrdhost_flag_check(host, RRDHOST_FLAG_DELETE_ORPHAN_HOST) && !host->receiver
  1123. #ifdef ENABLE_DBENGINE
  1124. /* don't delete multi-host DB host files */
  1125. && !(host->rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE && host->rrdeng_ctx == &multidb_ctx)
  1126. #endif
  1127. )
  1128. rrdhost_delete_charts(host);
  1129. else
  1130. rrdhost_cleanup_charts(host);
  1131. }
  1132. rrd_unlock();
  1133. }
  1134. // ----------------------------------------------------------------------------
  1135. // RRDHOST - save or delete all the host charts from disk
  1136. void rrdhost_cleanup_obsolete_charts(RRDHOST *host) {
  1137. time_t now = now_realtime_sec();
  1138. RRDSET *st;
  1139. uint32_t rrdhost_delete_obsolete_charts = rrdhost_flag_check(host, RRDHOST_FLAG_DELETE_OBSOLETE_CHARTS);
  1140. restart_after_removal:
  1141. rrdset_foreach_write(st, host) {
  1142. if(unlikely(rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)
  1143. && st->last_accessed_time + rrdset_free_obsolete_time < now
  1144. && st->last_updated.tv_sec + rrdset_free_obsolete_time < now
  1145. && st->last_collected_time.tv_sec + rrdset_free_obsolete_time < now
  1146. )) {
  1147. st->rrdhost->obsolete_charts_count--;
  1148. #ifdef ENABLE_DBENGINE
  1149. if(st->rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE) {
  1150. RRDDIM *rd, *last;
  1151. rrdset_flag_set(st, RRDSET_FLAG_ARCHIVED);
  1152. while (st->variables) rrdsetvar_free(st->variables);
  1153. while (st->alarms) rrdsetcalc_unlink(st->alarms);
  1154. rrdset_wrlock(st);
  1155. for (rd = st->dimensions, last = NULL ; likely(rd) ; ) {
  1156. if (rrddim_flag_check(rd, RRDDIM_FLAG_ARCHIVED)) {
  1157. last = rd;
  1158. rd = rd->next;
  1159. continue;
  1160. }
  1161. rrddim_flag_set(rd, RRDDIM_FLAG_ARCHIVED);
  1162. while (rd->variables)
  1163. rrddimvar_free(rd->variables);
  1164. if (rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)) {
  1165. rrddim_flag_clear(rd, RRDDIM_FLAG_OBSOLETE);
  1166. /* only a collector can mark a chart as obsolete, so we must remove the reference */
  1167. uint8_t can_delete_metric = rd->state->collect_ops.finalize(rd);
  1168. if (can_delete_metric) {
  1169. /* This metric has no data and no references */
  1170. delete_dimension_uuid(&rd->state->metric_uuid);
  1171. rrddim_free(st, rd);
  1172. if (unlikely(!last)) {
  1173. rd = st->dimensions;
  1174. }
  1175. else {
  1176. rd = last->next;
  1177. }
  1178. continue;
  1179. }
  1180. }
  1181. last = rd;
  1182. rd = rd->next;
  1183. }
  1184. rrdset_unlock(st);
  1185. debug(D_RRD_CALLS, "RRDSET: Cleaning up remaining chart variables for host '%s', chart '%s'", host->hostname, st->id);
  1186. rrdvar_free_remaining_variables(host, &st->rrdvar_root_index);
  1187. rrdset_flag_clear(st, RRDSET_FLAG_OBSOLETE);
  1188. if (st->dimensions) {
  1189. /* If the chart still has dimensions don't delete it from the metadata log */
  1190. continue;
  1191. }
  1192. }
  1193. #endif
  1194. rrdset_rdlock(st);
  1195. if(rrdhost_delete_obsolete_charts)
  1196. rrdset_delete(st);
  1197. else
  1198. rrdset_save(st);
  1199. rrdset_unlock(st);
  1200. rrdset_free(st);
  1201. goto restart_after_removal;
  1202. }
  1203. }
  1204. }
  1205. void rrd_cleanup_obsolete_charts()
  1206. {
  1207. rrd_rdlock();
  1208. RRDHOST *host;
  1209. rrdhost_foreach_read(host)
  1210. {
  1211. if (host->obsolete_charts_count) {
  1212. rrdhost_wrlock(host);
  1213. #ifdef ENABLE_ACLK
  1214. host->deleted_charts_count = 0;
  1215. #endif
  1216. rrdhost_cleanup_obsolete_charts(host);
  1217. #ifdef ENABLE_ACLK
  1218. if (host->deleted_charts_count)
  1219. aclk_update_chart(host, "dummy-chart", 0);
  1220. #endif
  1221. rrdhost_unlock(host);
  1222. }
  1223. }
  1224. rrd_unlock();
  1225. }
  1226. // ----------------------------------------------------------------------------
  1227. // RRDHOST - set system info from environment variables
  1228. // system_info fields must be heap allocated or NULL
  1229. int rrdhost_set_system_info_variable(struct rrdhost_system_info *system_info, char *name, char *value) {
  1230. int res = 0;
  1231. if (!strcmp(name, "NETDATA_PROTOCOL_VERSION"))
  1232. return res;
  1233. else if(!strcmp(name, "NETDATA_CONTAINER_OS_NAME")){
  1234. freez(system_info->container_os_name);
  1235. system_info->container_os_name = strdupz(value);
  1236. }
  1237. else if(!strcmp(name, "NETDATA_CONTAINER_OS_ID")){
  1238. freez(system_info->container_os_id);
  1239. system_info->container_os_id = strdupz(value);
  1240. }
  1241. else if(!strcmp(name, "NETDATA_CONTAINER_OS_ID_LIKE")){
  1242. freez(system_info->container_os_id_like);
  1243. system_info->container_os_id_like = strdupz(value);
  1244. }
  1245. else if(!strcmp(name, "NETDATA_CONTAINER_OS_VERSION")){
  1246. freez(system_info->container_os_version);
  1247. system_info->container_os_version = strdupz(value);
  1248. }
  1249. else if(!strcmp(name, "NETDATA_CONTAINER_OS_VERSION_ID")){
  1250. freez(system_info->container_os_version_id);
  1251. system_info->container_os_version_id = strdupz(value);
  1252. }
  1253. else if(!strcmp(name, "NETDATA_CONTAINER_OS_DETECTION")){
  1254. freez(system_info->host_os_detection);
  1255. system_info->host_os_detection = strdupz(value);
  1256. }
  1257. else if(!strcmp(name, "NETDATA_HOST_OS_NAME")){
  1258. freez(system_info->host_os_name);
  1259. system_info->host_os_name = strdupz(value);
  1260. }
  1261. else if(!strcmp(name, "NETDATA_HOST_OS_ID")){
  1262. freez(system_info->host_os_id);
  1263. system_info->host_os_id = strdupz(value);
  1264. }
  1265. else if(!strcmp(name, "NETDATA_HOST_OS_ID_LIKE")){
  1266. freez(system_info->host_os_id_like);
  1267. system_info->host_os_id_like = strdupz(value);
  1268. }
  1269. else if(!strcmp(name, "NETDATA_HOST_OS_VERSION")){
  1270. freez(system_info->host_os_version);
  1271. system_info->host_os_version = strdupz(value);
  1272. }
  1273. else if(!strcmp(name, "NETDATA_HOST_OS_VERSION_ID")){
  1274. freez(system_info->host_os_version_id);
  1275. system_info->host_os_version_id = strdupz(value);
  1276. }
  1277. else if(!strcmp(name, "NETDATA_HOST_OS_DETECTION")){
  1278. freez(system_info->host_os_detection);
  1279. system_info->host_os_detection = strdupz(value);
  1280. }
  1281. else if(!strcmp(name, "NETDATA_SYSTEM_KERNEL_NAME")){
  1282. freez(system_info->kernel_name);
  1283. system_info->kernel_name = strdupz(value);
  1284. }
  1285. else if(!strcmp(name, "NETDATA_SYSTEM_CPU_LOGICAL_CPU_COUNT")){
  1286. freez(system_info->host_cores);
  1287. system_info->host_cores = strdupz(value);
  1288. }
  1289. else if(!strcmp(name, "NETDATA_SYSTEM_CPU_FREQ")){
  1290. freez(system_info->host_cpu_freq);
  1291. system_info->host_cpu_freq = strdupz(value);
  1292. }
  1293. else if(!strcmp(name, "NETDATA_SYSTEM_TOTAL_RAM")){
  1294. freez(system_info->host_ram_total);
  1295. system_info->host_ram_total = strdupz(value);
  1296. }
  1297. else if(!strcmp(name, "NETDATA_SYSTEM_TOTAL_DISK_SIZE")){
  1298. freez(system_info->host_disk_space);
  1299. system_info->host_disk_space = strdupz(value);
  1300. }
  1301. else if(!strcmp(name, "NETDATA_SYSTEM_KERNEL_VERSION")){
  1302. freez(system_info->kernel_version);
  1303. system_info->kernel_version = strdupz(value);
  1304. }
  1305. else if(!strcmp(name, "NETDATA_SYSTEM_ARCHITECTURE")){
  1306. freez(system_info->architecture);
  1307. system_info->architecture = strdupz(value);
  1308. }
  1309. else if(!strcmp(name, "NETDATA_SYSTEM_VIRTUALIZATION")){
  1310. freez(system_info->virtualization);
  1311. system_info->virtualization = strdupz(value);
  1312. }
  1313. else if(!strcmp(name, "NETDATA_SYSTEM_VIRT_DETECTION")){
  1314. freez(system_info->virt_detection);
  1315. system_info->virt_detection = strdupz(value);
  1316. }
  1317. else if(!strcmp(name, "NETDATA_SYSTEM_CONTAINER")){
  1318. freez(system_info->container);
  1319. system_info->container = strdupz(value);
  1320. }
  1321. else if(!strcmp(name, "NETDATA_SYSTEM_CONTAINER_DETECTION")){
  1322. freez(system_info->container_detection);
  1323. system_info->container_detection = strdupz(value);
  1324. }
  1325. else if(!strcmp(name, "NETDATA_HOST_IS_K8S_NODE")){
  1326. freez(system_info->is_k8s_node);
  1327. system_info->is_k8s_node = strdupz(value);
  1328. }
  1329. else if (!strcmp(name, "NETDATA_SYSTEM_CPU_VENDOR"))
  1330. return res;
  1331. else if (!strcmp(name, "NETDATA_SYSTEM_CPU_MODEL"))
  1332. return res;
  1333. else if (!strcmp(name, "NETDATA_SYSTEM_CPU_DETECTION"))
  1334. return res;
  1335. else if (!strcmp(name, "NETDATA_SYSTEM_RAM_DETECTION"))
  1336. return res;
  1337. else if (!strcmp(name, "NETDATA_SYSTEM_DISK_DETECTION"))
  1338. return res;
  1339. else {
  1340. res = 1;
  1341. }
  1342. return res;
  1343. }
  1344. /**
  1345. * Alarm Compare ID
  1346. *
  1347. * Callback function used with the binary trees to compare the id of RRDCALC
  1348. *
  1349. * @param a a pointer to the RRDCAL item to insert,compare or update the binary tree
  1350. * @param b the pointer to the binary tree.
  1351. *
  1352. * @return It returns 0 case the values are equal, 1 case a is bigger than b and -1 case a is smaller than b.
  1353. */
  1354. int alarm_compare_id(void *a, void *b) {
  1355. register uint32_t hash1 = ((RRDCALC *)a)->id;
  1356. register uint32_t hash2 = ((RRDCALC *)b)->id;
  1357. if(hash1 < hash2) return -1;
  1358. else if(hash1 > hash2) return 1;
  1359. return 0;
  1360. }
  1361. /**
  1362. * Alarm Compare NAME
  1363. *
  1364. * Callback function used with the binary trees to compare the name of RRDCALC
  1365. *
  1366. * @param a a pointer to the RRDCAL item to insert,compare or update the binary tree
  1367. * @param b the pointer to the binary tree.
  1368. *
  1369. * @return It returns 0 case the values are equal, 1 case a is bigger than b and -1 case a is smaller than b.
  1370. */
  1371. int alarm_compare_name(void *a, void *b) {
  1372. RRDCALC *in1 = (RRDCALC *)a;
  1373. RRDCALC *in2 = (RRDCALC *)b;
  1374. if(in1->hash < in2->hash) return -1;
  1375. else if(in1->hash > in2->hash) return 1;
  1376. return strcmp(in1->name,in2->name);
  1377. }
  1378. // Added for gap-filling, if this proves to be a bottleneck in large-scale systems then we will need to cache
  1379. // the last entry times as the metric updates, but let's see if it is a problem first.
  1380. time_t rrdhost_last_entry_t(RRDHOST *h) {
  1381. rrdhost_rdlock(h);
  1382. RRDSET *st;
  1383. time_t result = 0;
  1384. rrdset_foreach_read(st, h) {
  1385. time_t st_last = rrdset_last_entry_t(st);
  1386. if (st_last > result)
  1387. result = st_last;
  1388. }
  1389. rrdhost_unlock(h);
  1390. return result;
  1391. }