health.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "health.h"
  3. #define WORKER_HEALTH_JOB_RRD_LOCK 0
  4. #define WORKER_HEALTH_JOB_HOST_LOCK 1
  5. #define WORKER_HEALTH_JOB_DB_QUERY 2
  6. #define WORKER_HEALTH_JOB_CALC_EVAL 3
  7. #define WORKER_HEALTH_JOB_WARNING_EVAL 4
  8. #define WORKER_HEALTH_JOB_CRITICAL_EVAL 5
  9. #define WORKER_HEALTH_JOB_ALARM_LOG_ENTRY 6
  10. #define WORKER_HEALTH_JOB_ALARM_LOG_PROCESS 7
  11. #define WORKER_HEALTH_JOB_DELAYED_INIT_RRDSET 8
  12. #define WORKER_HEALTH_JOB_DELAYED_INIT_RRDDIM 9
  13. #if WORKER_UTILIZATION_MAX_JOB_TYPES < 10
  14. #error WORKER_UTILIZATION_MAX_JOB_TYPES has to be at least 10
  15. #endif
  16. unsigned int default_health_enabled = 1;
  17. char *silencers_filename;
  18. SIMPLE_PATTERN *conf_enabled_alarms = NULL;
  19. DICTIONARY *health_rrdvars;
  20. static bool prepare_command(BUFFER *wb,
  21. const char *exec,
  22. const char *recipient,
  23. const char *registry_hostname,
  24. uint32_t unique_id,
  25. uint32_t alarm_id,
  26. uint32_t alarm_event_id,
  27. uint32_t when,
  28. const char *alert_name,
  29. const char *alert_chart_name,
  30. const char *alert_family,
  31. const char *new_status,
  32. const char *old_status,
  33. NETDATA_DOUBLE new_value,
  34. NETDATA_DOUBLE old_value,
  35. const char *alert_source,
  36. uint32_t duration,
  37. uint32_t non_clear_duration,
  38. const char *alert_units,
  39. const char *alert_info,
  40. const char *new_value_string,
  41. const char *old_value_string,
  42. const char *source,
  43. const char *error_msg,
  44. int n_warn,
  45. int n_crit,
  46. const char *warn_alarms,
  47. const char *crit_alarms,
  48. const char *classification,
  49. const char *edit_command,
  50. const char *machine_guid)
  51. {
  52. char buf[8192];
  53. size_t n = 8192 - 1;
  54. buffer_strcat(wb, "exec");
  55. if (!sanitize_command_argument_string(buf, exec, n))
  56. return false;
  57. buffer_sprintf(wb, " '%s'", buf);
  58. if (!sanitize_command_argument_string(buf, recipient, n))
  59. return false;
  60. buffer_sprintf(wb, " '%s'", buf);
  61. if (!sanitize_command_argument_string(buf, registry_hostname, n))
  62. return false;
  63. buffer_sprintf(wb, " '%s'", buf);
  64. buffer_sprintf(wb, " '%u'", unique_id);
  65. buffer_sprintf(wb, " '%u'", alarm_id);
  66. buffer_sprintf(wb, " '%u'", alarm_event_id);
  67. buffer_sprintf(wb, " '%u'", when);
  68. if (!sanitize_command_argument_string(buf, alert_name, n))
  69. return false;
  70. buffer_sprintf(wb, " '%s'", buf);
  71. if (!sanitize_command_argument_string(buf, alert_chart_name, n))
  72. return false;
  73. buffer_sprintf(wb, " '%s'", buf);
  74. if (!sanitize_command_argument_string(buf, alert_family, n))
  75. return false;
  76. buffer_sprintf(wb, " '%s'", buf);
  77. if (!sanitize_command_argument_string(buf, new_status, n))
  78. return false;
  79. buffer_sprintf(wb, " '%s'", buf);
  80. if (!sanitize_command_argument_string(buf, old_status, n))
  81. return false;
  82. buffer_sprintf(wb, " '%s'", buf);
  83. buffer_sprintf(wb, " '" NETDATA_DOUBLE_FORMAT_ZERO "'", new_value);
  84. buffer_sprintf(wb, " '" NETDATA_DOUBLE_FORMAT_ZERO "'", old_value);
  85. if (!sanitize_command_argument_string(buf, alert_source, n))
  86. return false;
  87. buffer_sprintf(wb, " '%s'", buf);
  88. buffer_sprintf(wb, " '%u'", duration);
  89. buffer_sprintf(wb, " '%u'", non_clear_duration);
  90. if (!sanitize_command_argument_string(buf, alert_units, n))
  91. return false;
  92. buffer_sprintf(wb, " '%s'", buf);
  93. if (!sanitize_command_argument_string(buf, alert_info, n))
  94. return false;
  95. buffer_sprintf(wb, " '%s'", buf);
  96. if (!sanitize_command_argument_string(buf, new_value_string, n))
  97. return false;
  98. buffer_sprintf(wb, " '%s'", buf);
  99. if (!sanitize_command_argument_string(buf, old_value_string, n))
  100. return false;
  101. buffer_sprintf(wb, " '%s'", buf);
  102. if (!sanitize_command_argument_string(buf, source, n))
  103. return false;
  104. buffer_sprintf(wb, " '%s'", buf);
  105. if (!sanitize_command_argument_string(buf, error_msg, n))
  106. return false;
  107. buffer_sprintf(wb, " '%s'", buf);
  108. buffer_sprintf(wb, " '%d'", n_warn);
  109. buffer_sprintf(wb, " '%d'", n_crit);
  110. if (!sanitize_command_argument_string(buf, warn_alarms, n))
  111. return false;
  112. buffer_sprintf(wb, " '%s'", buf);
  113. if (!sanitize_command_argument_string(buf, crit_alarms, n))
  114. return false;
  115. buffer_sprintf(wb, " '%s'", buf);
  116. if (!sanitize_command_argument_string(buf, classification, n))
  117. return false;
  118. buffer_sprintf(wb, " '%s'", buf);
  119. if (!sanitize_command_argument_string(buf, edit_command, n))
  120. return false;
  121. buffer_sprintf(wb, " '%s'", buf);
  122. if (!sanitize_command_argument_string(buf, machine_guid, n))
  123. return false;
  124. buffer_sprintf(wb, " '%s'", buf);
  125. return true;
  126. }
  127. // the queue of executed alarm notifications that haven't been waited for yet
  128. static struct {
  129. ALARM_ENTRY *head; // oldest
  130. ALARM_ENTRY *tail; // latest
  131. } alarm_notifications_in_progress = {NULL, NULL};
  132. typedef struct active_alerts {
  133. char *name;
  134. time_t last_status_change;
  135. RRDCALC_STATUS status;
  136. } active_alerts_t;
  137. static inline void enqueue_alarm_notify_in_progress(ALARM_ENTRY *ae)
  138. {
  139. ae->prev_in_progress = NULL;
  140. ae->next_in_progress = NULL;
  141. if (NULL != alarm_notifications_in_progress.tail) {
  142. ae->prev_in_progress = alarm_notifications_in_progress.tail;
  143. alarm_notifications_in_progress.tail->next_in_progress = ae;
  144. }
  145. if (NULL == alarm_notifications_in_progress.head) {
  146. alarm_notifications_in_progress.head = ae;
  147. }
  148. alarm_notifications_in_progress.tail = ae;
  149. }
  150. static inline void unlink_alarm_notify_in_progress(ALARM_ENTRY *ae)
  151. {
  152. struct alarm_entry *prev = ae->prev_in_progress;
  153. struct alarm_entry *next = ae->next_in_progress;
  154. if (NULL != prev) {
  155. prev->next_in_progress = next;
  156. }
  157. if (NULL != next) {
  158. next->prev_in_progress = prev;
  159. }
  160. if (ae == alarm_notifications_in_progress.head) {
  161. alarm_notifications_in_progress.head = next;
  162. }
  163. if (ae == alarm_notifications_in_progress.tail) {
  164. alarm_notifications_in_progress.tail = prev;
  165. }
  166. }
  167. // ----------------------------------------------------------------------------
  168. // health initialization
  169. /**
  170. * User Config directory
  171. *
  172. * Get the config directory for health and return it.
  173. *
  174. * @return a pointer to the user config directory
  175. */
  176. inline char *health_user_config_dir(void) {
  177. char buffer[FILENAME_MAX + 1];
  178. snprintfz(buffer, FILENAME_MAX, "%s/health.d", netdata_configured_user_config_dir);
  179. return config_get(CONFIG_SECTION_DIRECTORIES, "health config", buffer);
  180. }
  181. /**
  182. * Stock Config Directory
  183. *
  184. * Get the Stock config directory and return it.
  185. *
  186. * @return a pointer to the stock config directory.
  187. */
  188. inline char *health_stock_config_dir(void) {
  189. char buffer[FILENAME_MAX + 1];
  190. snprintfz(buffer, FILENAME_MAX, "%s/health.d", netdata_configured_stock_config_dir);
  191. return config_get(CONFIG_SECTION_DIRECTORIES, "stock health config", buffer);
  192. }
  193. /**
  194. * Silencers init
  195. *
  196. * Function used to initialize the silencer structure.
  197. */
  198. static void health_silencers_init(void) {
  199. FILE *fd = fopen(silencers_filename, "r");
  200. if (fd) {
  201. fseek(fd, 0 , SEEK_END);
  202. off_t length = (off_t) ftell(fd);
  203. fseek(fd, 0 , SEEK_SET);
  204. if (length > 0 && length < HEALTH_SILENCERS_MAX_FILE_LEN) {
  205. char *str = mallocz((length+1)* sizeof(char));
  206. if(str) {
  207. size_t copied;
  208. copied = fread(str, sizeof(char), length, fd);
  209. if (copied == (length* sizeof(char))) {
  210. str[length] = 0x00;
  211. json_parse(str, NULL, health_silencers_json_read_callback);
  212. info("Parsed health silencers file %s", silencers_filename);
  213. } else {
  214. error("Cannot read the data from health silencers file %s", silencers_filename);
  215. }
  216. freez(str);
  217. }
  218. } else {
  219. error(
  220. "Health silencers file %s has the size %" PRId64 " that is out of range[ 1 , %d ]. Aborting read.",
  221. silencers_filename,
  222. (int64_t)length,
  223. HEALTH_SILENCERS_MAX_FILE_LEN);
  224. }
  225. fclose(fd);
  226. } else {
  227. info("Cannot open the file %s, so Netdata will work with the default health configuration.",silencers_filename);
  228. }
  229. }
  230. /**
  231. * Health Init
  232. *
  233. * Initialize the health thread.
  234. */
  235. void health_init(void) {
  236. debug(D_HEALTH, "Health configuration initializing");
  237. if(!(default_health_enabled = (unsigned int)config_get_boolean(CONFIG_SECTION_HEALTH, "enabled", default_health_enabled))) {
  238. debug(D_HEALTH, "Health is disabled.");
  239. return;
  240. }
  241. health_silencers_init();
  242. }
  243. // ----------------------------------------------------------------------------
  244. // re-load health configuration
  245. /**
  246. * Reload host
  247. *
  248. * Reload configuration for a specific host.
  249. *
  250. * @param host the structure of the host that the function will reload the configuration.
  251. */
  252. static void health_reload_host(RRDHOST *host) {
  253. if(unlikely(!host->health.health_enabled) && !rrdhost_flag_check(host, RRDHOST_FLAG_INITIALIZED_HEALTH))
  254. return;
  255. log_health("[%s]: Reloading health.", rrdhost_hostname(host));
  256. char *user_path = health_user_config_dir();
  257. char *stock_path = health_stock_config_dir();
  258. // free all running alarms
  259. rrdcalc_delete_all(host);
  260. rrdcalctemplate_delete_all(host);
  261. // invalidate all previous entries in the alarm log
  262. netdata_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
  263. ALARM_ENTRY *t;
  264. for(t = host->health_log.alarms ; t ; t = t->next) {
  265. if(t->new_status != RRDCALC_STATUS_REMOVED)
  266. t->flags |= HEALTH_ENTRY_FLAG_UPDATED;
  267. }
  268. netdata_rwlock_unlock(&host->health_log.alarm_log_rwlock);
  269. // reset all thresholds to all charts
  270. RRDSET *st;
  271. rrdset_foreach_read(st, host) {
  272. st->green = NAN;
  273. st->red = NAN;
  274. }
  275. rrdset_foreach_done(st);
  276. // load the new alarms
  277. health_readdir(host, user_path, stock_path, NULL);
  278. //Discard alarms with labels that do not apply to host
  279. rrdcalc_delete_alerts_not_matching_host_labels_from_this_host(host);
  280. // link the loaded alarms to their charts
  281. rrdset_foreach_write(st, host) {
  282. if (rrdset_flag_check(st, RRDSET_FLAG_ARCHIVED))
  283. continue;
  284. rrdcalc_link_matching_alerts_to_rrdset(st);
  285. rrdcalctemplate_link_matching_templates_to_rrdset(st);
  286. }
  287. rrdset_foreach_done(st);
  288. #ifdef ENABLE_ACLK
  289. if (netdata_cloud_setting) {
  290. struct aclk_sync_host_config *wc = (struct aclk_sync_host_config *)host->aclk_sync_host_config;
  291. if (likely(wc)) {
  292. wc->alert_queue_removed = SEND_REMOVED_AFTER_HEALTH_LOOPS;
  293. }
  294. }
  295. #endif
  296. }
  297. /**
  298. * Reload
  299. *
  300. * Reload the host configuration for all hosts.
  301. */
  302. void health_reload(void) {
  303. sql_refresh_hashes();
  304. RRDHOST *host;
  305. dfe_start_reentrant(rrdhost_root_index, host){
  306. health_reload_host(host);
  307. }
  308. dfe_done(host);
  309. }
  310. // ----------------------------------------------------------------------------
  311. // health main thread and friends
  312. static inline RRDCALC_STATUS rrdcalc_value2status(NETDATA_DOUBLE n) {
  313. if(isnan(n) || isinf(n)) return RRDCALC_STATUS_UNDEFINED;
  314. if(n) return RRDCALC_STATUS_RAISED;
  315. return RRDCALC_STATUS_CLEAR;
  316. }
  317. #define ACTIVE_ALARMS_LIST_EXAMINE 500
  318. #define ACTIVE_ALARMS_LIST 15
  319. static inline int compare_active_alerts(const void * a, const void * b) {
  320. active_alerts_t *active_alerts_a = (active_alerts_t *)a;
  321. active_alerts_t *active_alerts_b = (active_alerts_t *)b;
  322. return ( active_alerts_b->last_status_change - active_alerts_a->last_status_change );
  323. }
  324. static inline void health_alarm_execute(RRDHOST *host, ALARM_ENTRY *ae) {
  325. ae->flags |= HEALTH_ENTRY_FLAG_PROCESSED;
  326. if(unlikely(ae->new_status < RRDCALC_STATUS_CLEAR)) {
  327. // do not send notifications for internal statuses
  328. debug(D_HEALTH, "Health not sending notification for alarm '%s.%s' status %s (internal statuses)", ae_chart_name(ae), ae_name(ae), rrdcalc_status2string(ae->new_status));
  329. goto done;
  330. }
  331. if(unlikely(ae->new_status <= RRDCALC_STATUS_CLEAR && (ae->flags & HEALTH_ENTRY_FLAG_NO_CLEAR_NOTIFICATION))) {
  332. // do not send notifications for disabled statuses
  333. debug(D_HEALTH, "Health not sending notification for alarm '%s.%s' status %s (it has no-clear-notification enabled)", ae_chart_name(ae), ae_name(ae), rrdcalc_status2string(ae->new_status));
  334. log_health("[%s]: Health not sending notification for alarm '%s.%s' status %s (it has no-clear-notification enabled)", rrdhost_hostname(host), ae_chart_name(ae), ae_name(ae), rrdcalc_status2string(ae->new_status));
  335. // mark it as run, so that we will send the same alarm if it happens again
  336. goto done;
  337. }
  338. // find the previous notification for the same alarm
  339. // which we have run the exec script
  340. // exception: alarms with HEALTH_ENTRY_FLAG_NO_CLEAR_NOTIFICATION set
  341. if(likely(!(ae->flags & HEALTH_ENTRY_FLAG_NO_CLEAR_NOTIFICATION))) {
  342. uint32_t id = ae->alarm_id;
  343. ALARM_ENTRY *t;
  344. for(t = ae->next; t ; t = t->next) {
  345. if(t->alarm_id == id && t->flags & HEALTH_ENTRY_FLAG_EXEC_RUN)
  346. break;
  347. }
  348. if(likely(t)) {
  349. // we have executed this alarm notification in the past
  350. if(t && t->new_status == ae->new_status) {
  351. // don't send the notification for the same status again
  352. debug(D_HEALTH, "Health not sending again notification for alarm '%s.%s' status %s", ae_chart_name(ae), ae_name(ae)
  353. , rrdcalc_status2string(ae->new_status));
  354. log_health("[%s]: Health not sending again notification for alarm '%s.%s' status %s", rrdhost_hostname(host), ae_chart_name(ae), ae_name(ae)
  355. , rrdcalc_status2string(ae->new_status));
  356. goto done;
  357. }
  358. }
  359. else {
  360. // we have not executed this alarm notification in the past
  361. // so, don't send CLEAR notifications
  362. if(unlikely(ae->new_status == RRDCALC_STATUS_CLEAR)) {
  363. if((!(ae->flags & HEALTH_ENTRY_RUN_ONCE)) || (ae->flags & HEALTH_ENTRY_RUN_ONCE && ae->old_status < RRDCALC_STATUS_RAISED) ) {
  364. debug(D_HEALTH, "Health not sending notification for first initialization of alarm '%s.%s' status %s"
  365. , ae_chart_name(ae), ae_name(ae), rrdcalc_status2string(ae->new_status));
  366. goto done;
  367. }
  368. }
  369. }
  370. }
  371. // Check if alarm notifications are silenced
  372. if (ae->flags & HEALTH_ENTRY_FLAG_SILENCED) {
  373. log_health("[%s]: Health not sending notification for alarm '%s.%s' status %s (command API has disabled notifications)", rrdhost_hostname(host), ae_chart_name(ae), ae_name(ae), rrdcalc_status2string(ae->new_status));
  374. goto done;
  375. }
  376. log_health("[%s]: Sending notification for alarm '%s.%s' status %s.", rrdhost_hostname(host), ae_chart_name(ae), ae_name(ae), rrdcalc_status2string(ae->new_status));
  377. const char *exec = (ae->exec) ? ae_exec(ae) : string2str(host->health.health_default_exec);
  378. const char *recipient = (ae->recipient) ? ae_recipient(ae) : string2str(host->health.health_default_recipient);
  379. int n_warn=0, n_crit=0;
  380. RRDCALC *rc;
  381. EVAL_EXPRESSION *expr=NULL;
  382. BUFFER *warn_alarms, *crit_alarms;
  383. active_alerts_t *active_alerts = callocz(ACTIVE_ALARMS_LIST_EXAMINE, sizeof(active_alerts_t));
  384. warn_alarms = buffer_create(NETDATA_WEB_RESPONSE_INITIAL_SIZE, &netdata_buffers_statistics.buffers_health);
  385. crit_alarms = buffer_create(NETDATA_WEB_RESPONSE_INITIAL_SIZE, &netdata_buffers_statistics.buffers_health);
  386. foreach_rrdcalc_in_rrdhost_read(host, rc) {
  387. if(unlikely(!rc->rrdset || !rc->rrdset->last_collected_time.tv_sec))
  388. continue;
  389. if(unlikely((n_warn + n_crit) >= ACTIVE_ALARMS_LIST_EXAMINE))
  390. break;
  391. if (unlikely(rc->status == RRDCALC_STATUS_WARNING)) {
  392. if (likely(ae->alarm_id != rc->id) || likely(ae->alarm_event_id != rc->next_event_id - 1)) {
  393. active_alerts[n_warn+n_crit].name = (char *)rrdcalc_name(rc);
  394. active_alerts[n_warn+n_crit].last_status_change = rc->last_status_change;
  395. active_alerts[n_warn+n_crit].status = rc->status;
  396. n_warn++;
  397. } else if (ae->alarm_id == rc->id)
  398. expr = rc->warning;
  399. } else if (unlikely(rc->status == RRDCALC_STATUS_CRITICAL)) {
  400. if (likely(ae->alarm_id != rc->id) || likely(ae->alarm_event_id != rc->next_event_id - 1)) {
  401. active_alerts[n_warn+n_crit].name = (char *)rrdcalc_name(rc);
  402. active_alerts[n_warn+n_crit].last_status_change = rc->last_status_change;
  403. active_alerts[n_warn+n_crit].status = rc->status;
  404. n_crit++;
  405. } else if (ae->alarm_id == rc->id)
  406. expr = rc->critical;
  407. } else if (unlikely(rc->status == RRDCALC_STATUS_CLEAR)) {
  408. if (ae->alarm_id == rc->id)
  409. expr = rc->warning;
  410. }
  411. }
  412. foreach_rrdcalc_in_rrdhost_done(rc);
  413. if (n_warn+n_crit>1)
  414. qsort (active_alerts, n_warn+n_crit, sizeof(active_alerts_t), compare_active_alerts);
  415. int count_w = 0, count_c = 0;
  416. while (count_w + count_c < n_warn + n_crit && count_w + count_c < ACTIVE_ALARMS_LIST) {
  417. if (active_alerts[count_w+count_c].status == RRDCALC_STATUS_WARNING) {
  418. if (count_w)
  419. buffer_strcat(warn_alarms, ",");
  420. buffer_strcat(warn_alarms, active_alerts[count_w+count_c].name);
  421. buffer_strcat(warn_alarms, "=");
  422. buffer_snprintf(warn_alarms, 11, "%"PRId64"", (int64_t)active_alerts[count_w+count_c].last_status_change);
  423. count_w++;
  424. }
  425. else if (active_alerts[count_w+count_c].status == RRDCALC_STATUS_CRITICAL) {
  426. if (count_c)
  427. buffer_strcat(crit_alarms, ",");
  428. buffer_strcat(crit_alarms, active_alerts[count_w+count_c].name);
  429. buffer_strcat(crit_alarms, "=");
  430. buffer_snprintf(crit_alarms, 11, "%"PRId64"", (int64_t)active_alerts[count_w+count_c].last_status_change);
  431. count_c++;
  432. }
  433. }
  434. char *edit_command = ae->source ? health_edit_command_from_source(ae_source(ae)) : strdupz("UNKNOWN=0=UNKNOWN");
  435. BUFFER *wb = buffer_create(8192, &netdata_buffers_statistics.buffers_health);
  436. bool ok = prepare_command(wb,
  437. exec,
  438. recipient,
  439. rrdhost_registry_hostname(host),
  440. ae->unique_id,
  441. ae->alarm_id,
  442. ae->alarm_event_id,
  443. (unsigned long)ae->when,
  444. ae_name(ae),
  445. ae->chart?ae_chart_name(ae):"NOCHART",
  446. ae->family?ae_family(ae):"NOFAMILY",
  447. rrdcalc_status2string(ae->new_status),
  448. rrdcalc_status2string(ae->old_status),
  449. ae->new_value,
  450. ae->old_value,
  451. ae->source?ae_source(ae):"UNKNOWN",
  452. (uint32_t)ae->duration,
  453. (uint32_t)ae->non_clear_duration,
  454. ae_units(ae),
  455. ae_info(ae),
  456. ae_new_value_string(ae),
  457. ae_old_value_string(ae),
  458. (expr && expr->source)?expr->source:"NOSOURCE",
  459. (expr && expr->error_msg)?buffer_tostring(expr->error_msg):"NOERRMSG",
  460. n_warn,
  461. n_crit,
  462. buffer_tostring(warn_alarms),
  463. buffer_tostring(crit_alarms),
  464. ae->classification?ae_classification(ae):"Unknown",
  465. edit_command,
  466. host != localhost ? host->machine_guid:"");
  467. const char *command_to_run = buffer_tostring(wb);
  468. if (ok) {
  469. ae->flags |= HEALTH_ENTRY_FLAG_EXEC_RUN;
  470. ae->exec_run_timestamp = now_realtime_sec(); /* will be updated by real time after spawning */
  471. debug(D_HEALTH, "executing command '%s'", command_to_run);
  472. ae->flags |= HEALTH_ENTRY_FLAG_EXEC_IN_PROGRESS;
  473. ae->exec_spawn_serial = spawn_enq_cmd(command_to_run);
  474. enqueue_alarm_notify_in_progress(ae);
  475. } else {
  476. error("Failed to format command arguments");
  477. }
  478. buffer_free(wb);
  479. freez(edit_command);
  480. buffer_free(warn_alarms);
  481. buffer_free(crit_alarms);
  482. freez(active_alerts);
  483. return; //health_alarm_wait_for_execution
  484. done:
  485. health_alarm_log_save(host, ae);
  486. }
  487. static inline void health_alarm_wait_for_execution(ALARM_ENTRY *ae) {
  488. if (!(ae->flags & HEALTH_ENTRY_FLAG_EXEC_IN_PROGRESS))
  489. return;
  490. spawn_wait_cmd(ae->exec_spawn_serial, &ae->exec_code, &ae->exec_run_timestamp);
  491. debug(D_HEALTH, "done executing command - returned with code %d", ae->exec_code);
  492. ae->flags &= ~HEALTH_ENTRY_FLAG_EXEC_IN_PROGRESS;
  493. if(ae->exec_code != 0)
  494. ae->flags |= HEALTH_ENTRY_FLAG_EXEC_FAILED;
  495. unlink_alarm_notify_in_progress(ae);
  496. }
  497. static inline void health_process_notifications(RRDHOST *host, ALARM_ENTRY *ae) {
  498. debug(D_HEALTH, "Health alarm '%s.%s' = " NETDATA_DOUBLE_FORMAT_AUTO " - changed status from %s to %s",
  499. ae->chart?ae_chart_name(ae):"NOCHART", ae_name(ae),
  500. ae->new_value,
  501. rrdcalc_status2string(ae->old_status),
  502. rrdcalc_status2string(ae->new_status)
  503. );
  504. health_alarm_execute(host, ae);
  505. }
  506. static inline void health_alarm_log_process(RRDHOST *host) {
  507. uint32_t first_waiting = (host->health_log.alarms)?host->health_log.alarms->unique_id:0;
  508. time_t now = now_realtime_sec();
  509. netdata_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
  510. ALARM_ENTRY *ae;
  511. for(ae = host->health_log.alarms; ae && ae->unique_id >= host->health_last_processed_id; ae = ae->next) {
  512. if(likely(!(ae->flags & HEALTH_ENTRY_FLAG_IS_REPEATING))) {
  513. if(unlikely(
  514. !(ae->flags & HEALTH_ENTRY_FLAG_PROCESSED) &&
  515. !(ae->flags & HEALTH_ENTRY_FLAG_UPDATED)
  516. )) {
  517. if(unlikely(ae->unique_id < first_waiting))
  518. first_waiting = ae->unique_id;
  519. if(likely(now >= ae->delay_up_to_timestamp))
  520. health_process_notifications(host, ae);
  521. }
  522. }
  523. }
  524. netdata_rwlock_unlock(&host->health_log.alarm_log_rwlock);
  525. // remember this for the next iteration
  526. host->health_last_processed_id = first_waiting;
  527. bool cleanup_excess_log_entries = host->health_log.count > host->health_log.max;
  528. if (!cleanup_excess_log_entries)
  529. return;
  530. // cleanup excess entries in the log
  531. netdata_rwlock_wrlock(&host->health_log.alarm_log_rwlock);
  532. ALARM_ENTRY *last = NULL;
  533. unsigned int count = host->health_log.max * 2 / 3;
  534. for(ae = host->health_log.alarms; ae && count ; count--, last = ae, ae = ae->next) ;
  535. if(ae && last && last->next == ae)
  536. last->next = NULL;
  537. else
  538. ae = NULL;
  539. while(ae) {
  540. debug(D_HEALTH, "Health removing alarm log entry with id: %u", ae->unique_id);
  541. ALARM_ENTRY *t = ae->next;
  542. if(likely(!(ae->flags & HEALTH_ENTRY_FLAG_IS_REPEATING))) {
  543. health_alarm_wait_for_execution(ae);
  544. health_alarm_log_free_one_nochecks_nounlink(ae);
  545. host->health_log.count--;
  546. }
  547. ae = t;
  548. }
  549. netdata_rwlock_unlock(&host->health_log.alarm_log_rwlock);
  550. }
  551. static inline int rrdcalc_isrunnable(RRDCALC *rc, time_t now, time_t *next_run) {
  552. if(unlikely(!rc->rrdset)) {
  553. debug(D_HEALTH, "Health not running alarm '%s.%s'. It is not linked to a chart.", rrdcalc_chart_name(rc), rrdcalc_name(rc));
  554. return 0;
  555. }
  556. if(unlikely(rc->next_update > now)) {
  557. if (unlikely(*next_run > rc->next_update)) {
  558. // update the next_run time of the main loop
  559. // to run this alarm precisely the time required
  560. *next_run = rc->next_update;
  561. }
  562. debug(D_HEALTH, "Health not examining alarm '%s.%s' yet (will do in %d secs).", rrdcalc_chart_name(rc), rrdcalc_name(rc), (int) (rc->next_update - now));
  563. return 0;
  564. }
  565. if(unlikely(!rc->update_every)) {
  566. debug(D_HEALTH, "Health not running alarm '%s.%s'. It does not have an update frequency", rrdcalc_chart_name(rc), rrdcalc_name(rc));
  567. return 0;
  568. }
  569. if(unlikely(rrdset_flag_check(rc->rrdset, RRDSET_FLAG_OBSOLETE))) {
  570. debug(D_HEALTH, "Health not running alarm '%s.%s'. The chart has been marked as obsolete", rrdcalc_chart_name(rc), rrdcalc_name(rc));
  571. return 0;
  572. }
  573. if(unlikely(rrdset_flag_check(rc->rrdset, RRDSET_FLAG_ARCHIVED))) {
  574. debug(D_HEALTH, "Health not running alarm '%s.%s'. The chart has been marked as archived", rrdcalc_chart_name(rc), rrdcalc_name(rc));
  575. return 0;
  576. }
  577. if(unlikely(!rc->rrdset->last_collected_time.tv_sec || rc->rrdset->counter_done < 2)) {
  578. debug(D_HEALTH, "Health not running alarm '%s.%s'. Chart is not fully collected yet.", rrdcalc_chart_name(rc), rrdcalc_name(rc));
  579. return 0;
  580. }
  581. int update_every = rc->rrdset->update_every;
  582. time_t first = rrdset_first_entry_s(rc->rrdset);
  583. time_t last = rrdset_last_entry_s(rc->rrdset);
  584. if(unlikely(now + update_every < first /* || now - update_every > last */)) {
  585. debug(D_HEALTH
  586. , "Health not examining alarm '%s.%s' yet (wanted time is out of bounds - we need %lu but got %lu - %lu)."
  587. , rrdcalc_chart_name(rc), rrdcalc_name(rc), (unsigned long) now, (unsigned long) first
  588. , (unsigned long) last);
  589. return 0;
  590. }
  591. if(RRDCALC_HAS_DB_LOOKUP(rc)) {
  592. time_t needed = now + rc->before + rc->after;
  593. if(needed + update_every < first || needed - update_every > last) {
  594. debug(D_HEALTH
  595. , "Health not examining alarm '%s.%s' yet (not enough data yet - we need %lu but got %lu - %lu)."
  596. , rrdcalc_chart_name(rc), rrdcalc_name(rc), (unsigned long) needed, (unsigned long) first
  597. , (unsigned long) last);
  598. return 0;
  599. }
  600. }
  601. return 1;
  602. }
  603. static inline int check_if_resumed_from_suspension(void) {
  604. static usec_t last_realtime = 0, last_monotonic = 0;
  605. usec_t realtime = now_realtime_usec(), monotonic = now_monotonic_usec();
  606. int ret = 0;
  607. // detect if monotonic and realtime have twice the difference
  608. // in which case we assume the system was just waken from hibernation
  609. if(last_realtime && last_monotonic && realtime - last_realtime > 2 * (monotonic - last_monotonic))
  610. ret = 1;
  611. last_realtime = realtime;
  612. last_monotonic = monotonic;
  613. return ret;
  614. }
  615. static void health_main_cleanup(void *ptr) {
  616. worker_unregister();
  617. struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
  618. static_thread->enabled = NETDATA_MAIN_THREAD_EXITING;
  619. info("cleaning up...");
  620. static_thread->enabled = NETDATA_MAIN_THREAD_EXITED;
  621. log_health("Health thread ended.");
  622. }
  623. static void initialize_health(RRDHOST *host)
  624. {
  625. if(!host->health.health_enabled ||
  626. rrdhost_flag_check(host, RRDHOST_FLAG_INITIALIZED_HEALTH) ||
  627. !service_running(SERVICE_HEALTH))
  628. return;
  629. rrdhost_flag_set(host, RRDHOST_FLAG_INITIALIZED_HEALTH);
  630. log_health("[%s]: Initializing health.", rrdhost_hostname(host));
  631. host->health.health_default_warn_repeat_every = config_get_duration(CONFIG_SECTION_HEALTH, "default repeat warning", "never");
  632. host->health.health_default_crit_repeat_every = config_get_duration(CONFIG_SECTION_HEALTH, "default repeat critical", "never");
  633. host->health_log.next_log_id = 1;
  634. host->health_log.next_alarm_id = 1;
  635. host->health_log.max = 1000;
  636. host->health_log.next_log_id = (uint32_t)now_realtime_sec();
  637. host->health_log.next_alarm_id = 0;
  638. long n = config_get_number(CONFIG_SECTION_HEALTH, "in memory max health log entries", host->health_log.max);
  639. if(n < 10) {
  640. error("Host '%s': health configuration has invalid max log entries %ld. Using default %u", rrdhost_hostname(host), n, host->health_log.max);
  641. config_set_number(CONFIG_SECTION_HEALTH, "in memory max health log entries", (long)host->health_log.max);
  642. }
  643. else
  644. host->health_log.max = (unsigned int)n;
  645. conf_enabled_alarms = simple_pattern_create(config_get(CONFIG_SECTION_HEALTH, "enabled alarms", "*"), NULL,
  646. SIMPLE_PATTERN_EXACT, true);
  647. netdata_rwlock_init(&host->health_log.alarm_log_rwlock);
  648. char filename[FILENAME_MAX + 1];
  649. snprintfz(filename, FILENAME_MAX, "%s/alarm-notify.sh", netdata_configured_primary_plugins_dir);
  650. host->health.health_default_exec = string_strdupz(config_get(CONFIG_SECTION_HEALTH, "script to execute on alarm", filename));
  651. host->health.health_default_recipient = string_strdupz("root");
  652. // TODO: This needs to go to the metadata thread
  653. // Health should wait before accessing the table (needs to be created by the metadata thread)
  654. sql_create_health_log_table(host);
  655. sql_health_alarm_log_load(host);
  656. // ------------------------------------------------------------------------
  657. // load health configuration
  658. health_readdir(host, health_user_config_dir(), health_stock_config_dir(), NULL);
  659. // link the loaded alarms to their charts
  660. RRDSET *st;
  661. rrdset_foreach_reentrant(st, host) {
  662. if (rrdset_flag_check(st, RRDSET_FLAG_ARCHIVED))
  663. continue;
  664. rrdcalc_link_matching_alerts_to_rrdset(st);
  665. rrdcalctemplate_link_matching_templates_to_rrdset(st);
  666. }
  667. rrdset_foreach_done(st);
  668. //Discard alarms with labels that do not apply to host
  669. rrdcalc_delete_alerts_not_matching_host_labels_from_this_host(host);
  670. }
  671. static void health_sleep(time_t next_run, unsigned int loop __maybe_unused) {
  672. time_t now = now_realtime_sec();
  673. if(now < next_run) {
  674. worker_is_idle();
  675. debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration in %d secs", loop, (int) (next_run - now));
  676. while (now < next_run && service_running(SERVICE_HEALTH)) {
  677. sleep_usec(USEC_PER_SEC);
  678. now = now_realtime_sec();
  679. }
  680. }
  681. else {
  682. debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration now", loop);
  683. }
  684. }
  685. static SILENCE_TYPE check_silenced(RRDCALC *rc, const char *host, SILENCERS *silencers) {
  686. SILENCER *s;
  687. debug(D_HEALTH, "Checking if alarm was silenced via the command API. Alarm info name:%s context:%s chart:%s host:%s family:%s",
  688. rrdcalc_name(rc), (rc->rrdset)?rrdset_context(rc->rrdset):"", rrdcalc_chart_name(rc), host, (rc->rrdset)?rrdset_family(rc->rrdset):"");
  689. for (s = silencers->silencers; s!=NULL; s=s->next){
  690. if (
  691. (!s->alarms_pattern || (rc->name && s->alarms_pattern && simple_pattern_matches_string(s->alarms_pattern, rc->name))) &&
  692. (!s->contexts_pattern || (rc->rrdset && rc->rrdset->context && s->contexts_pattern && simple_pattern_matches_string(s->contexts_pattern, rc->rrdset->context))) &&
  693. (!s->hosts_pattern || (host && s->hosts_pattern && simple_pattern_matches(s->hosts_pattern, host))) &&
  694. (!s->charts_pattern || (rc->chart && s->charts_pattern && simple_pattern_matches_string(s->charts_pattern, rc->chart))) &&
  695. (!s->families_pattern || (rc->rrdset && rc->rrdset->family && s->families_pattern && simple_pattern_matches_string(s->families_pattern, rc->rrdset->family)))
  696. ) {
  697. debug(D_HEALTH, "Alarm matches command API silence entry %s:%s:%s:%s:%s", s->alarms,s->charts, s->contexts, s->hosts, s->families);
  698. if (unlikely(silencers->stype == STYPE_NONE)) {
  699. debug(D_HEALTH, "Alarm %s matched a silence entry, but no SILENCE or DISABLE command was issued via the command API. The match has no effect.", rrdcalc_name(rc));
  700. } else {
  701. debug(D_HEALTH, "Alarm %s via the command API - name:%s context:%s chart:%s host:%s family:%s"
  702. , (silencers->stype == STYPE_DISABLE_ALARMS)?"Disabled":"Silenced"
  703. , rrdcalc_name(rc)
  704. , (rc->rrdset)?rrdset_context(rc->rrdset):""
  705. , rrdcalc_chart_name(rc)
  706. , host
  707. , (rc->rrdset)?rrdset_family(rc->rrdset):""
  708. );
  709. }
  710. return silencers->stype;
  711. }
  712. }
  713. return STYPE_NONE;
  714. }
  715. /**
  716. * Update Disabled Silenced
  717. *
  718. * Update the variable rrdcalc_flags of the structure RRDCALC according with the values of the host structure
  719. *
  720. * @param host structure that contains information about the host monitored.
  721. * @param rc structure with information about the alarm
  722. *
  723. * @return It returns 1 case rrdcalc_flags is DISABLED or 0 otherwise
  724. */
  725. static int update_disabled_silenced(RRDHOST *host, RRDCALC *rc) {
  726. uint32_t rrdcalc_flags_old = rc->run_flags;
  727. // Clear the flags
  728. rc->run_flags &= ~(RRDCALC_FLAG_DISABLED | RRDCALC_FLAG_SILENCED);
  729. if (unlikely(silencers->all_alarms)) {
  730. if (silencers->stype == STYPE_DISABLE_ALARMS) rc->run_flags |= RRDCALC_FLAG_DISABLED;
  731. else if (silencers->stype == STYPE_SILENCE_NOTIFICATIONS) rc->run_flags |= RRDCALC_FLAG_SILENCED;
  732. } else {
  733. SILENCE_TYPE st = check_silenced(rc, rrdhost_hostname(host), silencers);
  734. if (st == STYPE_DISABLE_ALARMS) rc->run_flags |= RRDCALC_FLAG_DISABLED;
  735. else if (st == STYPE_SILENCE_NOTIFICATIONS) rc->run_flags |= RRDCALC_FLAG_SILENCED;
  736. }
  737. if (rrdcalc_flags_old != rc->run_flags) {
  738. info("Alarm silencing changed for host '%s' alarm '%s': Disabled %s->%s Silenced %s->%s",
  739. rrdhost_hostname(host),
  740. rrdcalc_name(rc),
  741. (rrdcalc_flags_old & RRDCALC_FLAG_DISABLED)?"true":"false",
  742. (rc->run_flags & RRDCALC_FLAG_DISABLED)?"true":"false",
  743. (rrdcalc_flags_old & RRDCALC_FLAG_SILENCED)?"true":"false",
  744. (rc->run_flags & RRDCALC_FLAG_SILENCED)?"true":"false"
  745. );
  746. }
  747. if (rc->run_flags & RRDCALC_FLAG_DISABLED)
  748. return 1;
  749. else
  750. return 0;
  751. }
  752. static void health_execute_delayed_initializations(RRDHOST *host) {
  753. RRDSET *st;
  754. if (!rrdhost_flag_check(host, RRDHOST_FLAG_PENDING_HEALTH_INITIALIZATION)) return;
  755. rrdhost_flag_clear(host, RRDHOST_FLAG_PENDING_HEALTH_INITIALIZATION);
  756. rrdset_foreach_reentrant(st, host) {
  757. if(!rrdset_flag_check(st, RRDSET_FLAG_PENDING_HEALTH_INITIALIZATION)) continue;
  758. rrdset_flag_clear(st, RRDSET_FLAG_PENDING_HEALTH_INITIALIZATION);
  759. worker_is_busy(WORKER_HEALTH_JOB_DELAYED_INIT_RRDSET);
  760. rrdcalc_link_matching_alerts_to_rrdset(st);
  761. rrdcalctemplate_link_matching_templates_to_rrdset(st);
  762. RRDDIM *rd;
  763. rrddim_foreach_read(rd, st) {
  764. if(!rrddim_flag_check(rd, RRDDIM_FLAG_PENDING_HEALTH_INITIALIZATION)) continue;
  765. rrddim_flag_clear(rd, RRDDIM_FLAG_PENDING_HEALTH_INITIALIZATION);
  766. worker_is_busy(WORKER_HEALTH_JOB_DELAYED_INIT_RRDDIM);
  767. RRDCALCTEMPLATE *rt;
  768. foreach_rrdcalctemplate_read(host, rt) {
  769. if(!rt->foreach_dimension_pattern)
  770. continue;
  771. if(rrdcalctemplate_check_rrdset_conditions(rt, st, host)) {
  772. rrdcalctemplate_check_rrddim_conditions_and_link(rt, st, rd, host);
  773. }
  774. }
  775. foreach_rrdcalctemplate_done(rt);
  776. if (health_variable_check(health_rrdvars, st, rd))
  777. rrdvar_store_for_chart(host, st);
  778. }
  779. rrddim_foreach_done(rd);
  780. }
  781. rrdset_foreach_done(st);
  782. }
  783. /**
  784. * Health Main
  785. *
  786. * The main thread of the health system. In this function all the alarms will be processed.
  787. *
  788. * @param ptr is a pointer to the netdata_static_thread structure.
  789. *
  790. * @return It always returns NULL
  791. */
  792. void *health_main(void *ptr) {
  793. worker_register("HEALTH");
  794. worker_register_job_name(WORKER_HEALTH_JOB_RRD_LOCK, "rrd lock");
  795. worker_register_job_name(WORKER_HEALTH_JOB_HOST_LOCK, "host lock");
  796. worker_register_job_name(WORKER_HEALTH_JOB_DB_QUERY, "db lookup");
  797. worker_register_job_name(WORKER_HEALTH_JOB_CALC_EVAL, "calc eval");
  798. worker_register_job_name(WORKER_HEALTH_JOB_WARNING_EVAL, "warning eval");
  799. worker_register_job_name(WORKER_HEALTH_JOB_CRITICAL_EVAL, "critical eval");
  800. worker_register_job_name(WORKER_HEALTH_JOB_ALARM_LOG_ENTRY, "alarm log entry");
  801. worker_register_job_name(WORKER_HEALTH_JOB_ALARM_LOG_PROCESS, "alarm log process");
  802. worker_register_job_name(WORKER_HEALTH_JOB_DELAYED_INIT_RRDSET, "rrdset init");
  803. worker_register_job_name(WORKER_HEALTH_JOB_DELAYED_INIT_RRDDIM, "rrddim init");
  804. netdata_thread_cleanup_push(health_main_cleanup, ptr);
  805. int min_run_every = (int)config_get_number(CONFIG_SECTION_HEALTH, "run at least every seconds", 10);
  806. if(min_run_every < 1) min_run_every = 1;
  807. time_t hibernation_delay = config_get_number(CONFIG_SECTION_HEALTH, "postpone alarms during hibernation for seconds", 60);
  808. bool health_running_logged = false;
  809. rrdcalc_delete_alerts_not_matching_host_labels_from_all_hosts();
  810. unsigned int loop = 0;
  811. while(service_running(SERVICE_HEALTH)) {
  812. loop++;
  813. debug(D_HEALTH, "Health monitoring iteration no %u started", loop);
  814. time_t now = now_realtime_sec();
  815. int runnable = 0, apply_hibernation_delay = 0;
  816. time_t next_run = now + min_run_every;
  817. RRDCALC *rc;
  818. RRDHOST *host;
  819. if (unlikely(check_if_resumed_from_suspension())) {
  820. apply_hibernation_delay = 1;
  821. log_health(
  822. "Postponing alarm checks for %"PRId64" seconds, "
  823. "because it seems that the system was just resumed from suspension.",
  824. (int64_t)hibernation_delay);
  825. }
  826. if (unlikely(silencers->all_alarms && silencers->stype == STYPE_DISABLE_ALARMS)) {
  827. static int logged=0;
  828. if (!logged) {
  829. log_health("Skipping health checks, because all alarms are disabled via a %s command.",
  830. HEALTH_CMDAPI_CMD_DISABLEALL);
  831. logged = 1;
  832. }
  833. }
  834. worker_is_busy(WORKER_HEALTH_JOB_RRD_LOCK);
  835. dfe_start_reentrant(rrdhost_root_index, host) {
  836. if(unlikely(!service_running(SERVICE_HEALTH)))
  837. break;
  838. if (unlikely(!host->health.health_enabled))
  839. continue;
  840. if (unlikely(!rrdhost_flag_check(host, RRDHOST_FLAG_INITIALIZED_HEALTH)))
  841. initialize_health(host);
  842. health_execute_delayed_initializations(host);
  843. rrdcalc_delete_alerts_not_matching_host_labels_from_this_host(host);
  844. if (unlikely(apply_hibernation_delay)) {
  845. log_health(
  846. "[%s]: Postponing health checks for %"PRId64" seconds.",
  847. rrdhost_hostname(host),
  848. (int64_t)hibernation_delay);
  849. host->health.health_delay_up_to = now + hibernation_delay;
  850. }
  851. if (unlikely(host->health.health_delay_up_to)) {
  852. if (unlikely(now < host->health.health_delay_up_to)) {
  853. continue;
  854. }
  855. log_health("[%s]: Resuming health checks after delay.", rrdhost_hostname(host));
  856. host->health.health_delay_up_to = 0;
  857. }
  858. // wait until cleanup of obsolete charts on children is complete
  859. if (host != localhost) {
  860. if (unlikely(host->trigger_chart_obsoletion_check == 1)) {
  861. log_health("[%s]: Waiting for chart obsoletion check.", rrdhost_hostname(host));
  862. continue;
  863. }
  864. }
  865. if (!health_running_logged) {
  866. log_health("[%s]: Health is running.", rrdhost_hostname(host));
  867. health_running_logged = true;
  868. }
  869. worker_is_busy(WORKER_HEALTH_JOB_HOST_LOCK);
  870. // the first loop is to lookup values from the db
  871. foreach_rrdcalc_in_rrdhost_read(host, rc) {
  872. if(unlikely(!service_running(SERVICE_HEALTH)))
  873. break;
  874. rrdcalc_update_info_using_rrdset_labels(rc);
  875. if (update_disabled_silenced(host, rc))
  876. continue;
  877. // create an alert removed event if the chart is obsolete and
  878. // has stopped being collected for 60 seconds
  879. if (unlikely(rc->rrdset && rc->status != RRDCALC_STATUS_REMOVED &&
  880. rrdset_flag_check(rc->rrdset, RRDSET_FLAG_OBSOLETE) &&
  881. now > (rc->rrdset->last_collected_time.tv_sec + 60))) {
  882. if (!rrdcalc_isrepeating(rc)) {
  883. worker_is_busy(WORKER_HEALTH_JOB_ALARM_LOG_ENTRY);
  884. time_t now = now_realtime_sec();
  885. ALARM_ENTRY *ae = health_create_alarm_entry(
  886. host,
  887. rc->id,
  888. rc->next_event_id++,
  889. rc->config_hash_id,
  890. now,
  891. rc->name,
  892. rc->rrdset->id,
  893. rc->rrdset->context,
  894. rc->rrdset->family,
  895. rc->classification,
  896. rc->component,
  897. rc->type,
  898. rc->exec,
  899. rc->recipient,
  900. now - rc->last_status_change,
  901. rc->value,
  902. NAN,
  903. rc->status,
  904. RRDCALC_STATUS_REMOVED,
  905. rc->source,
  906. rc->units,
  907. rc->info,
  908. 0,
  909. rrdcalc_isrepeating(rc)?HEALTH_ENTRY_FLAG_IS_REPEATING:0);
  910. if (ae) {
  911. health_alarm_log_add_entry(host, ae);
  912. rc->old_status = rc->status;
  913. rc->status = RRDCALC_STATUS_REMOVED;
  914. rc->last_status_change = now;
  915. rc->last_updated = now;
  916. rc->value = NAN;
  917. #ifdef ENABLE_ACLK
  918. if (netdata_cloud_setting)
  919. sql_queue_alarm_to_aclk(host, ae, 1);
  920. #endif
  921. }
  922. }
  923. }
  924. if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run))) {
  925. if (unlikely(rc->run_flags & RRDCALC_FLAG_RUNNABLE))
  926. rc->run_flags &= ~RRDCALC_FLAG_RUNNABLE;
  927. continue;
  928. }
  929. runnable++;
  930. rc->old_value = rc->value;
  931. rc->run_flags |= RRDCALC_FLAG_RUNNABLE;
  932. // ------------------------------------------------------------
  933. // if there is database lookup, do it
  934. if (unlikely(RRDCALC_HAS_DB_LOOKUP(rc))) {
  935. worker_is_busy(WORKER_HEALTH_JOB_DB_QUERY);
  936. /* time_t old_db_timestamp = rc->db_before; */
  937. int value_is_null = 0;
  938. int ret = rrdset2value_api_v1(rc->rrdset, NULL, &rc->value, rrdcalc_dimensions(rc), 1,
  939. rc->after, rc->before, rc->group, NULL,
  940. 0, rc->options,
  941. &rc->db_after,&rc->db_before,
  942. NULL, NULL, NULL,
  943. &value_is_null, NULL, 0, 0,
  944. QUERY_SOURCE_HEALTH, STORAGE_PRIORITY_LOW);
  945. if (unlikely(ret != 200)) {
  946. // database lookup failed
  947. rc->value = NAN;
  948. rc->run_flags |= RRDCALC_FLAG_DB_ERROR;
  949. debug(D_HEALTH, "Health on host '%s', alarm '%s.%s': database lookup returned error %d",
  950. rrdhost_hostname(host), rrdcalc_chart_name(rc), rrdcalc_name(rc), ret
  951. );
  952. } else
  953. rc->run_flags &= ~RRDCALC_FLAG_DB_ERROR;
  954. if (unlikely(value_is_null)) {
  955. // collected value is null
  956. rc->value = NAN;
  957. rc->run_flags |= RRDCALC_FLAG_DB_NAN;
  958. debug(D_HEALTH,
  959. "Health on host '%s', alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
  960. rrdhost_hostname(host), rrdcalc_chart_name(rc), rrdcalc_name(rc)
  961. );
  962. } else
  963. rc->run_flags &= ~RRDCALC_FLAG_DB_NAN;
  964. debug(D_HEALTH, "Health on host '%s', alarm '%s.%s': database lookup gave value " NETDATA_DOUBLE_FORMAT,
  965. rrdhost_hostname(host), rrdcalc_chart_name(rc), rrdcalc_name(rc), rc->value
  966. );
  967. }
  968. // ------------------------------------------------------------
  969. // if there is calculation expression, run it
  970. if (unlikely(rc->calculation)) {
  971. worker_is_busy(WORKER_HEALTH_JOB_CALC_EVAL);
  972. if (unlikely(!expression_evaluate(rc->calculation))) {
  973. // calculation failed
  974. rc->value = NAN;
  975. rc->run_flags |= RRDCALC_FLAG_CALC_ERROR;
  976. debug(D_HEALTH, "Health on host '%s', alarm '%s.%s': expression '%s' failed: %s",
  977. rrdhost_hostname(host), rrdcalc_chart_name(rc), rrdcalc_name(rc),
  978. rc->calculation->parsed_as, buffer_tostring(rc->calculation->error_msg)
  979. );
  980. } else {
  981. rc->run_flags &= ~RRDCALC_FLAG_CALC_ERROR;
  982. debug(D_HEALTH, "Health on host '%s', alarm '%s.%s': expression '%s' gave value "
  983. NETDATA_DOUBLE_FORMAT
  984. ": %s (source: %s)", rrdhost_hostname(host), rrdcalc_chart_name(rc), rrdcalc_name(rc),
  985. rc->calculation->parsed_as, rc->calculation->result,
  986. buffer_tostring(rc->calculation->error_msg), rrdcalc_source(rc)
  987. );
  988. rc->value = rc->calculation->result;
  989. }
  990. }
  991. }
  992. foreach_rrdcalc_in_rrdhost_done(rc);
  993. if (unlikely(runnable && service_running(SERVICE_HEALTH))) {
  994. foreach_rrdcalc_in_rrdhost_read(host, rc) {
  995. if(unlikely(!service_running(SERVICE_HEALTH)))
  996. break;
  997. if (unlikely(!(rc->run_flags & RRDCALC_FLAG_RUNNABLE)))
  998. continue;
  999. if (rc->run_flags & RRDCALC_FLAG_DISABLED) {
  1000. continue;
  1001. }
  1002. RRDCALC_STATUS warning_status = RRDCALC_STATUS_UNDEFINED;
  1003. RRDCALC_STATUS critical_status = RRDCALC_STATUS_UNDEFINED;
  1004. // --------------------------------------------------------
  1005. // check the warning expression
  1006. if (likely(rc->warning)) {
  1007. worker_is_busy(WORKER_HEALTH_JOB_WARNING_EVAL);
  1008. if (unlikely(!expression_evaluate(rc->warning))) {
  1009. // calculation failed
  1010. rc->run_flags |= RRDCALC_FLAG_WARN_ERROR;
  1011. debug(D_HEALTH,
  1012. "Health on host '%s', alarm '%s.%s': warning expression failed with error: %s",
  1013. rrdhost_hostname(host), rrdcalc_chart_name(rc), rrdcalc_name(rc),
  1014. buffer_tostring(rc->warning->error_msg)
  1015. );
  1016. } else {
  1017. rc->run_flags &= ~RRDCALC_FLAG_WARN_ERROR;
  1018. debug(D_HEALTH, "Health on host '%s', alarm '%s.%s': warning expression gave value "
  1019. NETDATA_DOUBLE_FORMAT
  1020. ": %s (source: %s)", rrdhost_hostname(host), rrdcalc_chart_name(rc),
  1021. rrdcalc_name(rc), rc->warning->result, buffer_tostring(rc->warning->error_msg), rrdcalc_source(rc)
  1022. );
  1023. warning_status = rrdcalc_value2status(rc->warning->result);
  1024. }
  1025. }
  1026. // --------------------------------------------------------
  1027. // check the critical expression
  1028. if (likely(rc->critical)) {
  1029. worker_is_busy(WORKER_HEALTH_JOB_CRITICAL_EVAL);
  1030. if (unlikely(!expression_evaluate(rc->critical))) {
  1031. // calculation failed
  1032. rc->run_flags |= RRDCALC_FLAG_CRIT_ERROR;
  1033. debug(D_HEALTH,
  1034. "Health on host '%s', alarm '%s.%s': critical expression failed with error: %s",
  1035. rrdhost_hostname(host), rrdcalc_chart_name(rc), rrdcalc_name(rc),
  1036. buffer_tostring(rc->critical->error_msg)
  1037. );
  1038. } else {
  1039. rc->run_flags &= ~RRDCALC_FLAG_CRIT_ERROR;
  1040. debug(D_HEALTH, "Health on host '%s', alarm '%s.%s': critical expression gave value "
  1041. NETDATA_DOUBLE_FORMAT
  1042. ": %s (source: %s)", rrdhost_hostname(host), rrdcalc_chart_name(rc),
  1043. rrdcalc_name(rc), rc->critical->result, buffer_tostring(rc->critical->error_msg),
  1044. rrdcalc_source(rc)
  1045. );
  1046. critical_status = rrdcalc_value2status(rc->critical->result);
  1047. }
  1048. }
  1049. // --------------------------------------------------------
  1050. // decide the final alarm status
  1051. RRDCALC_STATUS status = RRDCALC_STATUS_UNDEFINED;
  1052. switch (warning_status) {
  1053. case RRDCALC_STATUS_CLEAR:
  1054. status = RRDCALC_STATUS_CLEAR;
  1055. break;
  1056. case RRDCALC_STATUS_RAISED:
  1057. status = RRDCALC_STATUS_WARNING;
  1058. break;
  1059. default:
  1060. break;
  1061. }
  1062. switch (critical_status) {
  1063. case RRDCALC_STATUS_CLEAR:
  1064. if (status == RRDCALC_STATUS_UNDEFINED)
  1065. status = RRDCALC_STATUS_CLEAR;
  1066. break;
  1067. case RRDCALC_STATUS_RAISED:
  1068. status = RRDCALC_STATUS_CRITICAL;
  1069. break;
  1070. default:
  1071. break;
  1072. }
  1073. // --------------------------------------------------------
  1074. // check if the new status and the old differ
  1075. if (status != rc->status) {
  1076. worker_is_busy(WORKER_HEALTH_JOB_ALARM_LOG_ENTRY);
  1077. int delay = 0;
  1078. // apply trigger hysteresis
  1079. if (now > rc->delay_up_to_timestamp) {
  1080. rc->delay_up_current = rc->delay_up_duration;
  1081. rc->delay_down_current = rc->delay_down_duration;
  1082. rc->delay_last = 0;
  1083. rc->delay_up_to_timestamp = 0;
  1084. } else {
  1085. rc->delay_up_current = (int) (rc->delay_up_current * rc->delay_multiplier);
  1086. if (rc->delay_up_current > rc->delay_max_duration)
  1087. rc->delay_up_current = rc->delay_max_duration;
  1088. rc->delay_down_current = (int) (rc->delay_down_current * rc->delay_multiplier);
  1089. if (rc->delay_down_current > rc->delay_max_duration)
  1090. rc->delay_down_current = rc->delay_max_duration;
  1091. }
  1092. if (status > rc->status)
  1093. delay = rc->delay_up_current;
  1094. else
  1095. delay = rc->delay_down_current;
  1096. // COMMENTED: because we do need to send raising alarms
  1097. // if(now + delay < rc->delay_up_to_timestamp)
  1098. // delay = (int)(rc->delay_up_to_timestamp - now);
  1099. rc->delay_last = delay;
  1100. rc->delay_up_to_timestamp = now + delay;
  1101. ALARM_ENTRY *ae = health_create_alarm_entry(
  1102. host,
  1103. rc->id,
  1104. rc->next_event_id++,
  1105. rc->config_hash_id,
  1106. now,
  1107. rc->name,
  1108. rc->rrdset->id,
  1109. rc->rrdset->context,
  1110. rc->rrdset->family,
  1111. rc->classification,
  1112. rc->component,
  1113. rc->type,
  1114. rc->exec,
  1115. rc->recipient,
  1116. now - rc->last_status_change,
  1117. rc->old_value,
  1118. rc->value,
  1119. rc->status,
  1120. status,
  1121. rc->source,
  1122. rc->units,
  1123. rc->info,
  1124. rc->delay_last,
  1125. (
  1126. ((rc->options & RRDCALC_OPTION_NO_CLEAR_NOTIFICATION)? HEALTH_ENTRY_FLAG_NO_CLEAR_NOTIFICATION : 0) |
  1127. ((rc->run_flags & RRDCALC_FLAG_SILENCED)? HEALTH_ENTRY_FLAG_SILENCED : 0) |
  1128. (rrdcalc_isrepeating(rc)?HEALTH_ENTRY_FLAG_IS_REPEATING:0)
  1129. )
  1130. );
  1131. health_alarm_log_add_entry(host, ae);
  1132. log_health("[%s]: Alert event for [%s.%s], value [%s], status [%s].", rrdhost_hostname(host), ae_chart_name(ae), ae_name(ae), ae_new_value_string(ae), rrdcalc_status2string(ae->new_status));
  1133. rc->last_status_change = now;
  1134. rc->old_status = rc->status;
  1135. rc->status = status;
  1136. }
  1137. rc->last_updated = now;
  1138. rc->next_update = now + rc->update_every;
  1139. if (next_run > rc->next_update)
  1140. next_run = rc->next_update;
  1141. }
  1142. foreach_rrdcalc_in_rrdhost_done(rc);
  1143. // process repeating alarms
  1144. foreach_rrdcalc_in_rrdhost_read(host, rc) {
  1145. if(unlikely(!service_running(SERVICE_HEALTH)))
  1146. break;
  1147. int repeat_every = 0;
  1148. if(unlikely(rrdcalc_isrepeating(rc) && rc->delay_up_to_timestamp <= now)) {
  1149. if(unlikely(rc->status == RRDCALC_STATUS_WARNING)) {
  1150. rc->run_flags &= ~RRDCALC_FLAG_RUN_ONCE;
  1151. repeat_every = rc->warn_repeat_every;
  1152. } else if(unlikely(rc->status == RRDCALC_STATUS_CRITICAL)) {
  1153. rc->run_flags &= ~RRDCALC_FLAG_RUN_ONCE;
  1154. repeat_every = rc->crit_repeat_every;
  1155. } else if(unlikely(rc->status == RRDCALC_STATUS_CLEAR)) {
  1156. if(!(rc->run_flags & RRDCALC_FLAG_RUN_ONCE)) {
  1157. if(rc->old_status == RRDCALC_STATUS_CRITICAL) {
  1158. repeat_every = 1;
  1159. } else if (rc->old_status == RRDCALC_STATUS_WARNING) {
  1160. repeat_every = 1;
  1161. }
  1162. }
  1163. }
  1164. } else {
  1165. continue;
  1166. }
  1167. if(unlikely(repeat_every > 0 && (rc->last_repeat + repeat_every) <= now)) {
  1168. worker_is_busy(WORKER_HEALTH_JOB_ALARM_LOG_ENTRY);
  1169. rc->last_repeat = now;
  1170. if (likely(rc->times_repeat < UINT32_MAX)) rc->times_repeat++;
  1171. ALARM_ENTRY *ae = health_create_alarm_entry(
  1172. host,
  1173. rc->id,
  1174. rc->next_event_id++,
  1175. rc->config_hash_id,
  1176. now,
  1177. rc->name,
  1178. rc->rrdset->id,
  1179. rc->rrdset->context,
  1180. rc->rrdset->family,
  1181. rc->classification,
  1182. rc->component,
  1183. rc->type,
  1184. rc->exec,
  1185. rc->recipient,
  1186. now - rc->last_status_change,
  1187. rc->old_value,
  1188. rc->value,
  1189. rc->old_status,
  1190. rc->status,
  1191. rc->source,
  1192. rc->units,
  1193. rc->info,
  1194. rc->delay_last,
  1195. (
  1196. ((rc->options & RRDCALC_OPTION_NO_CLEAR_NOTIFICATION)? HEALTH_ENTRY_FLAG_NO_CLEAR_NOTIFICATION : 0) |
  1197. ((rc->run_flags & RRDCALC_FLAG_SILENCED)? HEALTH_ENTRY_FLAG_SILENCED : 0) |
  1198. (rrdcalc_isrepeating(rc)?HEALTH_ENTRY_FLAG_IS_REPEATING:0)
  1199. )
  1200. );
  1201. ae->last_repeat = rc->last_repeat;
  1202. if (!(rc->run_flags & RRDCALC_FLAG_RUN_ONCE) && rc->status == RRDCALC_STATUS_CLEAR) {
  1203. ae->flags |= HEALTH_ENTRY_RUN_ONCE;
  1204. }
  1205. rc->run_flags |= RRDCALC_FLAG_RUN_ONCE;
  1206. health_process_notifications(host, ae);
  1207. debug(D_HEALTH, "Notification sent for the repeating alarm %u.", ae->alarm_id);
  1208. health_alarm_wait_for_execution(ae);
  1209. health_alarm_log_free_one_nochecks_nounlink(ae);
  1210. }
  1211. }
  1212. foreach_rrdcalc_in_rrdhost_done(rc);
  1213. }
  1214. if (unlikely(!service_running(SERVICE_HEALTH)))
  1215. break;
  1216. // execute notifications
  1217. // and cleanup
  1218. worker_is_busy(WORKER_HEALTH_JOB_ALARM_LOG_PROCESS);
  1219. health_alarm_log_process(host);
  1220. if (unlikely(!service_running(SERVICE_HEALTH))) {
  1221. // wait for all notifications to finish before allowing health to be cleaned up
  1222. ALARM_ENTRY *ae;
  1223. while (NULL != (ae = alarm_notifications_in_progress.head)) {
  1224. if(unlikely(!service_running(SERVICE_HEALTH)))
  1225. break;
  1226. health_alarm_wait_for_execution(ae);
  1227. }
  1228. break;
  1229. }
  1230. #ifdef ENABLE_ACLK
  1231. if (netdata_cloud_setting) {
  1232. struct aclk_sync_host_config *wc = (struct aclk_sync_host_config *)host->aclk_sync_host_config;
  1233. if (unlikely(!wc)) {
  1234. continue;
  1235. }
  1236. if (wc->alert_queue_removed == 1) {
  1237. sql_queue_removed_alerts_to_aclk(host);
  1238. } else if (wc->alert_queue_removed > 1) {
  1239. wc->alert_queue_removed--;
  1240. }
  1241. if (wc->alert_checkpoint_req == 1) {
  1242. aclk_push_alarm_checkpoint(host);
  1243. } else if (wc->alert_checkpoint_req > 1) {
  1244. wc->alert_checkpoint_req--;
  1245. }
  1246. }
  1247. #endif
  1248. }
  1249. dfe_done(host);
  1250. // wait for all notifications to finish before allowing health to be cleaned up
  1251. ALARM_ENTRY *ae;
  1252. while (NULL != (ae = alarm_notifications_in_progress.head)) {
  1253. if(unlikely(!service_running(SERVICE_HEALTH)))
  1254. break;
  1255. health_alarm_wait_for_execution(ae);
  1256. }
  1257. if(unlikely(!service_running(SERVICE_HEALTH)))
  1258. break;
  1259. health_sleep(next_run, loop);
  1260. } // forever
  1261. netdata_thread_cleanup_pop(1);
  1262. return NULL;
  1263. }
  1264. void health_add_host_labels(void) {
  1265. DICTIONARY *labels = localhost->rrdlabels;
  1266. // The source should be CONF, but when it is set, these labels are exported by default ('send configured labels' in exporting.conf).
  1267. // Their export seems to break exporting to Graphite, see https://github.com/netdata/netdata/issues/14084.
  1268. int is_ephemeral = appconfig_get_boolean(&netdata_config, CONFIG_SECTION_HEALTH, "is ephemeral", CONFIG_BOOLEAN_NO);
  1269. rrdlabels_add(labels, "_is_ephemeral", is_ephemeral ? "true" : "false", RRDLABEL_SRC_AUTO);
  1270. int has_unstable_connection = appconfig_get_boolean(&netdata_config, CONFIG_SECTION_HEALTH, "has unstable connection", CONFIG_BOOLEAN_NO);
  1271. rrdlabels_add(labels, "_has_unstable_connection", has_unstable_connection ? "true" : "false", RRDLABEL_SRC_AUTO);
  1272. }