]> arthur.barton.de Git - netdata.git/blob - src/health.c
renamed alarm.sh to alarm-email.sh
[netdata.git] / src / health.c
1 #include "common.h"
2
3 #define RRDVAR_MAX_LENGTH 1024
4
5 static const char *health_default_exec = PLUGINS_DIR "/alarm-email.sh";
6 int health_enabled = 1;
7
8 ALARM_LOG health_log = {
9         .nextid = 0,
10         .count = 0,
11         .max = 1000,
12         .alarms = NULL
13 };
14
15 // ----------------------------------------------------------------------------
16 // RRDVAR management
17
18 static inline int rrdvar_fix_name(char *variable) {
19     int fixed = 0;
20     while(*variable) {
21         if (!isalnum(*variable) && *variable != '.' && *variable != '_') {
22             *variable++ = '_';
23             fixed++;
24         }
25         else
26             variable++;
27     }
28
29     return fixed;
30 }
31
32 int rrdvar_compare(void* a, void* b) {
33     if(((RRDVAR *)a)->hash < ((RRDVAR *)b)->hash) return -1;
34     else if(((RRDVAR *)a)->hash > ((RRDVAR *)b)->hash) return 1;
35     else return strcmp(((RRDVAR *)a)->name, ((RRDVAR *)b)->name);
36 }
37
38 static inline RRDVAR *rrdvar_index_add(avl_tree_lock *tree, RRDVAR *rv) {
39     RRDVAR *ret = (RRDVAR *)avl_insert_lock(tree, (avl *)(rv));
40     if(ret != rv)
41         debug(D_VARIABLES, "Request to insert RRDVAR '%s' into index failed. Already exists.", rv->name);
42
43     return ret;
44 }
45
46 static inline RRDVAR *rrdvar_index_del(avl_tree_lock *tree, RRDVAR *rv) {
47     RRDVAR *ret = (RRDVAR *)avl_remove_lock(tree, (avl *)(rv));
48     if(!ret)
49         error("Request to remove RRDVAR '%s' from index failed. Not Found.", rv->name);
50
51     return ret;
52 }
53
54 static inline RRDVAR *rrdvar_index_find(avl_tree_lock *tree, const char *name, uint32_t hash) {
55     RRDVAR tmp;
56     tmp.name = (char *)name;
57     tmp.hash = (hash)?hash:simple_hash(tmp.name);
58
59     return (RRDVAR *)avl_search_lock(tree, (avl *)&tmp);
60 }
61
62 static inline void rrdvar_free(RRDHOST *host, avl_tree_lock *tree, RRDVAR *rv) {
63     (void)host;
64
65     if(!rv) return;
66
67     if(tree)
68         rrdvar_index_del(tree, rv);
69
70     freez(rv->name);
71     freez(rv);
72 }
73
74 static inline RRDVAR *rrdvar_create_and_index(const char *scope, avl_tree_lock *tree, const char *name, int type, calculated_number *value) {
75     char *variable = strdupz(name);
76     rrdvar_fix_name(variable);
77     uint32_t hash = simple_hash(variable);
78
79     RRDVAR *rv = rrdvar_index_find(tree, variable, hash);
80     if(unlikely(!rv)) {
81         debug(D_VARIABLES, "Variable '%s' not found in scope '%s'. Creating a new one.", variable, scope);
82
83         rv = callocz(1, sizeof(RRDVAR));
84         rv->name = variable;
85         rv->hash = hash;
86         rv->type = type;
87         rv->value = value;
88
89         RRDVAR *ret = rrdvar_index_add(tree, rv);
90         if(unlikely(ret != rv)) {
91             debug(D_VARIABLES, "Variable '%s' in scope '%s' already exists", variable, scope);
92             rrdvar_free(NULL, NULL, rv);
93             rv = NULL;
94         }
95         else
96             debug(D_VARIABLES, "Variable '%s' created in scope '%s'", variable, scope);
97     }
98     else {
99         // already exists
100         freez(variable);
101         rv = NULL;
102     }
103
104     return rv;
105 }
106
107 // ----------------------------------------------------------------------------
108 // RRDVAR lookup
109
110 calculated_number rrdvar2number(RRDVAR *rv) {
111     switch(rv->type) {
112         case RRDVAR_TYPE_CALCULATED: {
113             calculated_number *n = (calculated_number *)rv->value;
114             return *n;
115         }
116
117         case RRDVAR_TYPE_TIME_T: {
118             time_t *n = (time_t *)rv->value;
119             return *n;
120         }
121
122         case RRDVAR_TYPE_COLLECTED: {
123             collected_number *n = (collected_number *)rv->value;
124             return *n;
125         }
126
127         case RRDVAR_TYPE_TOTAL: {
128             total_number *n = (total_number *)rv->value;
129             return *n;
130         }
131
132         case RRDVAR_TYPE_INT: {
133             int *n = (int *)rv->value;
134             return *n;
135         }
136
137         default:
138             error("I don't know how to convert RRDVAR type %d to calculated_number", rv->type);
139             return NAN;
140     }
141 }
142
143 void dump_variable(void *data) {
144     RRDVAR *rv = (RRDVAR *)data;
145     debug(D_HEALTH, "%50s : %20.5Lf", rv->name, rrdvar2number(rv));
146 }
147
148 int health_variable_lookup(const char *variable, uint32_t hash, RRDCALC *rc, calculated_number *result) {
149     RRDSET *st = rc->rrdset;
150     RRDVAR *rv;
151
152     if(!st) return 0;
153
154     rv = rrdvar_index_find(&st->variables_root_index, variable, hash);
155     if(rv) {
156         *result = rrdvar2number(rv);
157         return 1;
158     }
159
160     rv = rrdvar_index_find(&st->rrdfamily->variables_root_index, variable, hash);
161     if(rv) {
162         *result = rrdvar2number(rv);
163         return 1;
164     }
165
166     rv = rrdvar_index_find(&st->rrdhost->variables_root_index, variable, hash);
167     if(rv) {
168         *result = rrdvar2number(rv);
169         return 1;
170     }
171
172     debug(D_HEALTH, "Available local chart '%s' variables:", st->id);
173     avl_traverse_lock(&st->variables_root_index, dump_variable);
174
175     debug(D_HEALTH, "Available family '%s' variables:", st->rrdfamily->family);
176     avl_traverse_lock(&st->rrdfamily->variables_root_index, dump_variable);
177
178     debug(D_HEALTH, "Available host '%s' variables:", st->rrdhost->hostname);
179     avl_traverse_lock(&st->rrdhost->variables_root_index, dump_variable);
180
181     return 0;
182 }
183
184 // ----------------------------------------------------------------------------
185 // RRDSETVAR management
186
187 RRDSETVAR *rrdsetvar_create(RRDSET *st, const char *variable, int type, void *value, uint32_t options) {
188     debug(D_VARIABLES, "RRDVARSET create for chart id '%s' name '%s' with variable name '%s'", st->id, st->name, variable);
189     RRDSETVAR *rs = (RRDSETVAR *)callocz(1, sizeof(RRDSETVAR));
190
191     char buffer[RRDVAR_MAX_LENGTH + 1];
192     snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->id, variable);
193     rs->fullid = strdupz(buffer);
194
195     snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->name, variable);
196     rs->fullname = strdupz(buffer);
197
198     rs->variable = strdupz(variable);
199
200     rs->type = type;
201     rs->value = value;
202     rs->options = options;
203     rs->rrdset = st;
204
205     rs->local       = rrdvar_create_and_index("local",  &st->variables_root_index, rs->variable, rs->type, rs->value);
206     rs->family      = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullid, rs->type, rs->value);
207     rs->host        = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullid, rs->type, rs->value);
208     rs->family_name = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullname, rs->type, rs->value);
209     rs->host_name   = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullname, rs->type, rs->value);
210
211     rs->next = st->variables;
212     st->variables = rs;
213
214     return rs;
215 }
216
217 void rrdsetvar_rename_all(RRDSET *st) {
218     debug(D_VARIABLES, "RRDSETVAR rename for chart id '%s' name '%s'", st->id, st->name);
219
220     // only these 2 can change name
221     // rs->family_name
222     // rs->host_name
223
224     char buffer[RRDVAR_MAX_LENGTH + 1];
225     RRDSETVAR *rs, *next = st->variables;
226     while((rs = next)) {
227         next = rs->next;
228
229         snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->name, rs->variable);
230
231         if (strcmp(buffer, rs->fullname)) {
232             // name changed
233             rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
234             rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_name);
235
236             freez(rs->fullname);
237             rs->fullname = strdupz(st->name);
238             rs->family_name = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullname, rs->type, rs->value);
239             rs->host_name   = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullname, rs->type, rs->value);
240         }
241     }
242
243     rrdsetcalc_link_matching(st);
244 }
245
246 void rrdsetvar_free(RRDSETVAR *rs) {
247     RRDSET *st = rs->rrdset;
248     debug(D_VARIABLES, "RRDSETVAR free for chart id '%s' name '%s', variable '%s'", st->id, st->name, rs->variable);
249
250     rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local);
251     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family);
252     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host);
253     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
254     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_name);
255
256     if(st->variables == rs) {
257         st->variables = rs->next;
258     }
259     else {
260         RRDSETVAR *t;
261         for (t = st->variables; t && t->next != rs; t = t->next);
262         if(!t) error("RRDSETVAR '%s' not found in chart '%s' variables linked list", rs->fullname, st->id);
263         else t->next = rs->next;
264     }
265
266     freez(rs->fullid);
267     freez(rs->fullname);
268     freez(rs->variable);
269     freez(rs);
270 }
271
272 // ----------------------------------------------------------------------------
273 // RRDDIMVAR management
274
275 #define RRDDIMVAR_ID_MAX 1024
276
277 RRDDIMVAR *rrddimvar_create(RRDDIM *rd, int type, const char *prefix, const char *suffix, void *value, uint32_t options) {
278     RRDSET *st = rd->rrdset;
279
280     debug(D_VARIABLES, "RRDDIMSET create for chart id '%s' name '%s', dimension id '%s', name '%s%s%s'", st->id, st->name, rd->id, (prefix)?prefix:"", rd->name, (suffix)?suffix:"");
281
282     if(!prefix) prefix = "";
283     if(!suffix) suffix = "";
284
285     char buffer[RRDDIMVAR_ID_MAX + 1];
286     RRDDIMVAR *rs = (RRDDIMVAR *)callocz(1, sizeof(RRDDIMVAR));
287
288     rs->prefix = strdupz(prefix);
289     rs->suffix = strdupz(suffix);
290
291     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->id, rs->suffix);
292     rs->id = strdupz(buffer);
293
294     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->name, rs->suffix);
295     rs->name = strdupz(buffer);
296
297     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->id, rs->id);
298     rs->fullidid = strdupz(buffer);
299
300     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->id, rs->name);
301     rs->fullidname = strdupz(buffer);
302
303     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->name, rs->id);
304     rs->fullnameid = strdupz(buffer);
305
306     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->name, rs->name);
307     rs->fullnamename = strdupz(buffer);
308
309     rs->type = type;
310     rs->value = value;
311     rs->options = options;
312     rs->rrddim = rd;
313
314     rs->local_id     = rrdvar_create_and_index("local", &st->variables_root_index, rs->id, rs->type, rs->value);
315     rs->local_name   = rrdvar_create_and_index("local", &st->variables_root_index, rs->name, rs->type, rs->value);
316
317     rs->family_id    = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->id, rs->type, rs->value);
318     rs->family_name  = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->name, rs->type, rs->value);
319
320     rs->host_fullidid     = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullidid, rs->type, rs->value);
321     rs->host_fullidname   = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullidname, rs->type, rs->value);
322     rs->host_fullnameid   = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullnameid, rs->type, rs->value);
323     rs->host_fullnamename = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullnamename, rs->type, rs->value);
324
325     rs->next = rd->variables;
326     rd->variables = rs;
327
328     return rs;
329 }
330
331 void rrddimvar_rename_all(RRDDIM *rd) {
332     RRDSET *st = rd->rrdset;
333     debug(D_VARIABLES, "RRDDIMSET rename for chart id '%s' name '%s', dimension id '%s', name '%s'", st->id, st->name, rd->id, rd->name);
334
335     RRDDIMVAR *rs, *next = rd->variables;
336     while((rs = next)) {
337         next = rs->next;
338
339         if (strcmp(rd->name, rs->name)) {
340             char buffer[RRDDIMVAR_ID_MAX + 1];
341             // name changed
342
343             // name
344             rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_name);
345             freez(rs->name);
346             snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->name, rs->suffix);
347             rs->name = strdupz(buffer);
348             rs->local_name = rrdvar_create_and_index("local", &st->variables_root_index, rs->name, rs->type, rs->value);
349
350             rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidname);
351             freez(rs->fullidname);
352             snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->id, rs->name);
353             rs->fullidname = strdupz(buffer);
354             rs->host_fullidname = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
355                                                              rs->fullidname, rs->type, rs->value);
356
357             // fullnameid
358             rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnameid);
359             freez(rs->fullnameid);
360             snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->name, rs->id);
361             rs->fullnameid = strdupz(buffer);
362             rs->host_fullnameid = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
363                                                           rs->fullnameid, rs->type, rs->value);
364
365             // fullnamename
366             rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnamename);
367             freez(rs->fullnamename);
368             snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->name, rs->name);
369             rs->fullnamename = strdupz(buffer);
370             rs->host_fullnamename = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
371                                                           rs->fullnamename, rs->type, rs->value);
372         }
373     }
374 }
375
376 void rrddimvar_free(RRDDIMVAR *rs) {
377     RRDDIM *rd = rs->rrddim;
378     RRDSET *st = rd->rrdset;
379     debug(D_VARIABLES, "RRDDIMSET free for chart id '%s' name '%s', dimension id '%s', name '%s', prefix='%s', suffix='%s'", st->id, st->name, rd->id, rd->name, rs->prefix, rs->suffix);
380
381     rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_id);
382     rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_name);
383
384     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_id);
385     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
386
387     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidid);
388     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidname);
389     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnameid);
390     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnamename);
391
392     if(rd->variables == rs) {
393         debug(D_VARIABLES, "RRDDIMSET removing first entry for chart id '%s' name '%s', dimension id '%s', name '%s'", st->id, st->name, rd->id, rd->name);
394         rd->variables = rs->next;
395     }
396     else {
397         debug(D_VARIABLES, "RRDDIMSET removing non-first entry for chart id '%s' name '%s', dimension id '%s', name '%s'", st->id, st->name, rd->id, rd->name);
398         RRDDIMVAR *t;
399         for (t = rd->variables; t && t->next != rs; t = t->next) ;
400         if(!t) error("RRDDIMVAR '%s' not found in dimension '%s/%s' variables linked list", rs->name, st->id, rd->id);
401         else t->next = rs->next;
402     }
403
404     freez(rs->prefix);
405     freez(rs->suffix);
406     freez(rs->id);
407     freez(rs->name);
408     freez(rs->fullidid);
409     freez(rs->fullidname);
410     freez(rs->fullnameid);
411     freez(rs->fullnamename);
412     freez(rs);
413 }
414
415 // ----------------------------------------------------------------------------
416 // RRDCALC management
417
418 static void rrdsetcalc_link(RRDSET *st, RRDCALC *rc) {
419     debug(D_HEALTH, "Health linking alarm '%s.%s' to chart '%s' of host '%s'", rc->chart?rc->chart:"NOCHART", rc->name, st->id, st->rrdhost->hostname);
420
421     rc->rrdset = st;
422
423     if(rc->update_every < rc->rrdset->update_every) {
424         error("Health alarm '%s.%s' has update every %d, less than chart update every %d. Setting alarm update frequency to %d.", rc->rrdset->id, rc->name, rc->update_every, rc->rrdset->update_every, rc->rrdset->update_every);
425         rc->update_every = rc->rrdset->update_every;
426     }
427
428     if(!isnan(rc->green) && isnan(st->green)) {
429         debug(D_HEALTH, "Health alarm '%s.%s' green threshold set from %Lf to %Lf.", rc->rrdset->id, rc->name, rc->rrdset->green, rc->green);
430         st->green = rc->green;
431     }
432
433     if(!isnan(rc->red) && isnan(st->red)) {
434         debug(D_HEALTH, "Health alarm '%s.%s' red threshold set from %Lf to %Lf.", rc->rrdset->id, rc->name, rc->rrdset->red, rc->red);
435         st->red = rc->red;
436     }
437
438     rc->local  = rrdvar_create_and_index("local",  &st->variables_root_index, rc->name, RRDVAR_TYPE_CALCULATED, &rc->value);
439     rc->family = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rc->name, RRDVAR_TYPE_CALCULATED, &rc->value);
440
441     char fullname[RRDVAR_MAX_LENGTH + 1];
442     snprintfz(fullname, RRDVAR_MAX_LENGTH, "%s.%s", st->id, rc->name);
443     rc->hostid   = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, fullname, RRDVAR_TYPE_CALCULATED, &rc->value);
444
445     snprintfz(fullname, RRDVAR_MAX_LENGTH, "%s.%s", st->name, rc->name);
446     rc->hostname = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, fullname, RRDVAR_TYPE_CALCULATED, &rc->value);
447 }
448
449 static inline int rrdcalc_is_matching_this_rrdset(RRDCALC *rc, RRDSET *st) {
450     if(     (rc->hash_chart == st->hash      && !strcmp(rc->chart, st->id)) ||
451             (rc->hash_chart == st->hash_name && !strcmp(rc->chart, st->name)))
452         return 1;
453
454     return 0;
455 }
456
457 // this has to be called while the RRDHOST is locked
458 inline void rrdsetcalc_link_matching(RRDSET *st) {
459     // debug(D_HEALTH, "find matching alarms for chart '%s'", st->id);
460
461     RRDCALC *rc;
462     for(rc = st->rrdhost->alarms; rc ; rc = rc->next) {
463         if(rc->rrdset) continue;
464
465         if(rrdcalc_is_matching_this_rrdset(rc, st))
466             rrdsetcalc_link(st, rc);
467     }
468 }
469
470 // this has to be called while the RRDHOST is locked
471 inline void rrdsetcalc_unlink(RRDCALC *rc) {
472     RRDSET *st = rc->rrdset;
473
474     if(!st) {
475         error("Requested to unlink RRDCALC '%s.%s' which is not linked to any RRDSET", rc->chart?rc->chart:"NOCHART", rc->name);
476         return;
477     }
478
479     RRDHOST *host = st->rrdhost;
480
481     debug(D_HEALTH, "Health unlinking alarm '%s.%s' from chart '%s' of host '%s'", rc->chart?rc->chart:"NOCHART", rc->name, st->id, host->hostname);
482
483     // unlink it
484     if(rc->rrdset_prev)
485         rc->rrdset_prev->rrdset_next = rc->rrdset_next;
486
487     if(rc->rrdset_next)
488         rc->rrdset_next->rrdset_prev = rc->rrdset_prev;
489
490     if(st->alarms == rc)
491         st->alarms = rc->rrdset_next;
492
493     rc->rrdset_prev = rc->rrdset_next = NULL;
494
495     rrdvar_free(st->rrdhost, &st->variables_root_index, rc->local);
496     rc->local = NULL;
497
498     rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rc->family);
499     rc->family = NULL;
500
501     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rc->hostid);
502     rc->hostid = NULL;
503
504     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rc->hostname);
505     rc->hostname = NULL;
506
507     rc->rrdset = NULL;
508
509     // RRDCALC will remain in RRDHOST
510     // so that if the matching chart is found in the future
511     // it will be applied automatically
512 }
513
514 static inline int rrdcalc_exists(RRDHOST *host, const char *name, uint32_t hash) {
515     RRDCALC *rc;
516
517     // make sure it does not already exist
518     for(rc = host->alarms; rc ; rc = rc->next) {
519         if (rc->hash == hash && !strcmp(name, rc->name)) {
520             error("Health alarm '%s' already exists in host '%s'.", name, host->hostname);
521             return 1;
522         }
523     }
524
525     return 0;
526 }
527
528 static inline void rrdcalc_create_part2(RRDHOST *host, RRDCALC *rc) {
529     rrdhost_check_rdlock(host);
530
531     if(rc->calculation) {
532         rc->calculation->this = &rc->value;
533         rc->calculation->rrdcalc = rc;
534     }
535
536     if(rc->warning) {
537         rc->warning->this = &rc->value;
538         rc->warning->rrdcalc = rc;
539     }
540
541     if(rc->critical) {
542         rc->critical->this = &rc->value;
543         rc->critical->rrdcalc = rc;
544     }
545
546     // link it to the host
547     rc->next = host->alarms;
548     host->alarms = rc;
549
550     // link it to its chart
551     RRDSET *st;
552     for(st = host->rrdset_root; st ; st = st->next) {
553         if(rrdcalc_is_matching_this_rrdset(rc, st)) {
554             rrdsetcalc_link(st, rc);
555             break;
556         }
557     }
558 }
559
560 static inline uint32_t rrdcalc_fullname(char *fullname, size_t len, const char *chart, const char *name) {
561     snprintfz(fullname, len - 1, "%s%s%s", chart?chart:"", chart?".":"", name);
562     rrdvar_fix_name(fullname);
563     return simple_hash(fullname);
564 }
565
566 static inline RRDCALC *rrdcalc_create(RRDHOST *host, const char *name, const char *chart, const char *dimensions, int group_method,
567                         int after, int before, int update_every, uint32_t options,
568                         calculated_number green, calculated_number red,
569                         const char *exec, const char *source,
570                         const char *calc, const char *warn, const char *crit) {
571
572     char fullname[RRDVAR_MAX_LENGTH + 1];
573     uint32_t hash = rrdcalc_fullname(fullname, RRDVAR_MAX_LENGTH + 1, chart, name);
574
575     if(rrdcalc_exists(host, fullname, hash))
576         return NULL;
577
578     RRDCALC *rc = callocz(1, sizeof(RRDCALC));
579
580     rc->name = strdupz(name);
581     rc->hash = simple_hash(rc->name);
582
583     rc->chart = strdupz(chart);
584     rc->hash_chart = simple_hash(rc->chart);
585
586     if(dimensions) rc->dimensions = strdupz(dimensions);
587
588     rc->green = green;
589     rc->red = red;
590     rc->value = NAN;
591     rc->old_value = NAN;
592
593     rc->group = group_method;
594     rc->after = after;
595     rc->before = before;
596     rc->update_every = update_every;
597     rc->options = options;
598
599     if(exec) rc->exec = strdupz(exec);
600     if(source) rc->source = strdupz(source);
601
602     if(calc) {
603         rc->calculation = expression_parse(calc, NULL, NULL);
604         if(!rc->calculation)
605             error("Health alarm '%s.%s': failed to parse calculation expression '%s'", chart, name, calc);
606     }
607     if(warn) {
608         rc->warning = expression_parse(warn, NULL, NULL);
609         if(!rc->warning)
610             error("Health alarm '%s.%s': failed to re-parse warning expression '%s'", chart, name, warn);
611     }
612     if(crit) {
613         rc->critical = expression_parse(crit, NULL, NULL);
614         if(!rc->critical)
615             error("Health alarm '%s.%s': failed to re-parse critical expression '%s'", chart, name, crit);
616     }
617
618     debug(D_HEALTH, "Health runtime added alarm '%s.%s': exec '%s', green %Lf, red %Lf, lookup: group %d, after %d, before %d, options %u, dimensions '%s', update every %d, calculation '%s', warning '%s', critical '%s', source '%s",
619           (rc->chart)?rc->chart:"NOCHART",
620           rc->name,
621           (rc->exec)?rc->exec:"DEFAULT",
622           rc->green,
623           rc->red,
624           rc->group,
625           rc->after,
626           rc->before,
627           rc->options,
628           (rc->dimensions)?rc->dimensions:"NONE",
629           rc->update_every,
630           (rc->calculation)?rc->calculation->parsed_as:"NONE",
631           (rc->warning)?rc->warning->parsed_as:"NONE",
632           (rc->critical)?rc->critical->parsed_as:"NONE",
633           rc->source
634     );
635
636     rrdcalc_create_part2(host, rc);
637     return rc;
638 }
639
640 void rrdcalc_free(RRDHOST *host, RRDCALC *rc) {
641     if(!rc) return;
642
643     debug(D_HEALTH, "Health removing alarm '%s.%s' of host '%s'", rc->chart?rc->chart:"NOCHART", rc->name, host->hostname);
644
645     // unlink it from RRDSET
646     if(rc->rrdset) rrdsetcalc_unlink(rc);
647
648     // unlink it from RRDHOST
649     if(rc == host->alarms)
650         host->alarms = rc->next;
651
652     else if(host->alarms) {
653         RRDCALC *t, *last = host->alarms;
654
655         for(t = last->next; t && t != rc; last = t, t = t->next) ;
656         if(last && last->next == rc)
657             last->next = rc->next;
658         else
659             error("Cannot unlink alarm '%s.%s' from host '%s': not found", rc->chart?rc->chart:"NOCHART", rc->name, host->hostname);
660     }
661     else
662         error("Cannot unlink unlink '%s.%s' from host '%s': This host does not have any calculations", rc->chart?rc->chart:"NOCHART", rc->name, host->hostname);
663
664     expression_free(rc->calculation);
665     expression_free(rc->warning);
666     expression_free(rc->critical);
667
668     freez(rc->source);
669     freez(rc->name);
670     freez(rc->chart);
671     freez(rc->dimensions);
672     freez(rc->exec);
673     freez(rc);
674 }
675
676 // ----------------------------------------------------------------------------
677 // RRDCALCTEMPLATE management
678
679 void rrdcalctemplate_link_matching(RRDSET *st) {
680     RRDCALCTEMPLATE *rt;
681
682     for(rt = st->rrdhost->templates; rt ; rt = rt->next) {
683         if(rt->hash_context == st->hash_context && !strcmp(rt->context, st->context)) {
684
685             RRDCALC *rc = rrdcalc_create(st->rrdhost, rt->name, st->id,
686                            rt->dimensions, rt->group, rt->after, rt->before, rt->update_every, rt->options,
687                            rt->green, rt->red, rt->exec, rt->source,
688                            (rt->calculation)?rt->calculation->source:NULL,
689                            (rt->warning)?rt->warning->source:NULL,
690                            (rt->critical)?rt->critical->source:NULL);
691
692             if(!rc)
693                 error("Health tried to create alarm from template '%s', but it failed", rt->name);
694
695 #ifdef NETDATA_INTERNAL_CHECKS
696             else if(rc->rrdset != st)
697                 error("Health alarm '%s.%s' should be linked to chart '%s', but it is not", rc->chart?rc->chart:"NOCHART", rc->name, st->id);
698 #else
699             (void)rc;
700 #endif
701         }
702     }
703 }
704
705 static inline void rrdcalctemplate_free(RRDHOST *host, RRDCALCTEMPLATE *rt) {
706     debug(D_HEALTH, "Health removing template '%s' of host '%s'", rt->name, host->hostname);
707
708     if(host->templates) {
709         if(host->templates == rt) {
710             host->templates = rt->next;
711         }
712         else {
713             RRDCALCTEMPLATE *t, *last = host->templates;
714             for (t = last->next; t && t != rt; last = t, t = t->next ) ;
715             if(last && last->next == rt) {
716                 last->next = rt->next;
717                 rt->next = NULL;
718             }
719             else
720                 error("Cannot find RRDCALCTEMPLATE '%s' linked in host '%s'", rt->name, host->hostname);
721         }
722     }
723
724     expression_free(rt->calculation);
725     expression_free(rt->warning);
726     expression_free(rt->critical);
727
728     freez(rt->dimensions);
729     freez(rt->context);
730     freez(rt->name);
731     freez(rt->exec);
732     freez(rt->source);
733     freez(rt);
734 }
735
736 // ----------------------------------------------------------------------------
737 // load health configuration
738
739 #define HEALTH_CONF_MAX_LINE 4096
740
741 #define HEALTH_ALARM_KEY "alarm"
742 #define HEALTH_TEMPLATE_KEY "template"
743 #define HEALTH_ON_KEY "on"
744 #define HEALTH_LOOKUP_KEY "lookup"
745 #define HEALTH_CALC_KEY "calc"
746 #define HEALTH_EVERY_KEY "every"
747 #define HEALTH_GREEN_KEY "green"
748 #define HEALTH_RED_KEY "red"
749 #define HEALTH_WARN_KEY "warn"
750 #define HEALTH_CRIT_KEY "crit"
751 #define HEALTH_EXEC_KEY "exec"
752
753 static inline int rrdcalc_add_alarm_from_config(RRDHOST *host, RRDCALC *rc) {
754     {
755         char fullname[RRDVAR_MAX_LENGTH + 1];
756         uint32_t hash = rrdcalc_fullname(fullname, RRDVAR_MAX_LENGTH + 1, rc->chart, rc->name);
757
758         if (rrdcalc_exists(host, fullname, hash))
759             return 0;
760     }
761
762     if(!rc->chart) {
763         error("Health configuration for alarm '%s' does not have a chart", rc->name);
764         return 0;
765     }
766
767     if(!rc->update_every) {
768         error("Health configuration for alarm '%s.%s' has no frequency (parameter 'every'). Ignoring it.", rc->chart?rc->chart:"NOCHART", rc->name);
769         return 0;
770     }
771
772     if(!RRDCALC_HAS_DB_LOOKUP(rc) && !rc->warning && !rc->critical) {
773         error("Health configuration for alarm '%s.%s' is useless (no calculation, no warning and no critical evaluation)", rc->chart?rc->chart:"NOCHART", rc->name);
774         return 0;
775     }
776
777     debug(D_HEALTH, "Health configuration adding alarm '%s.%s': exec '%s', green %Lf, red %Lf, lookup: group %d, after %d, before %d, options %u, dimensions '%s', update every %d, calculation '%s', warning '%s', critical '%s', source '%s",
778           rc->chart?rc->chart:"NOCHART",
779           rc->name,
780           (rc->exec)?rc->exec:"DEFAULT",
781           rc->green,
782           rc->red,
783           rc->group,
784           rc->after,
785           rc->before,
786           rc->options,
787           (rc->dimensions)?rc->dimensions:"NONE",
788           rc->update_every,
789           (rc->calculation)?rc->calculation->parsed_as:"NONE",
790           (rc->warning)?rc->warning->parsed_as:"NONE",
791           (rc->critical)?rc->critical->parsed_as:"NONE",
792           rc->source
793     );
794
795     rrdcalc_create_part2(host, rc);
796     return 1;
797 }
798
799 static inline int rrdcalctemplate_add_template_from_config(RRDHOST *host, RRDCALCTEMPLATE *rt) {
800     if(!rt->context) {
801         error("Health configuration for template '%s' does not have a context", rt->name);
802         return 0;
803     }
804
805     if(!rt->update_every) {
806         error("Health configuration for template '%s' has no frequency (parameter 'every'). Ignoring it.", rt->name);
807         return 0;
808     }
809
810     if(!RRDCALCTEMPLATE_HAS_CALCULATION(rt) && !rt->warning && !rt->critical) {
811         error("Health configuration for template '%s' is useless (no calculation, no warning and no critical evaluation)", rt->name);
812         return 0;
813     }
814
815     RRDCALCTEMPLATE *t;
816     for (t = host->templates; t ; t = t->next) {
817         if(t->hash_name == rt->hash_name && !strcmp(t->name, rt->name)) {
818             error("Health configuration template '%s' already exists for host '%s'.", rt->name, host->hostname);
819             return 0;
820         }
821     }
822
823     debug(D_HEALTH, "Health configuration adding template '%s': context '%s', exec '%s', green %Lf, red %Lf, lookup: group %d, after %d, before %d, options %u, dimensions '%s', update every %d, calculation '%s', warning '%s', critical '%s', source '%s'",
824           rt->name,
825           (rt->context)?rt->context:"NONE",
826           (rt->exec)?rt->exec:"DEFAULT",
827           rt->green,
828           rt->red,
829           rt->group,
830           rt->after,
831           rt->before,
832           rt->options,
833           (rt->dimensions)?rt->dimensions:"NONE",
834           rt->update_every,
835           (rt->calculation)?rt->calculation->parsed_as:"NONE",
836           (rt->warning)?rt->warning->parsed_as:"NONE",
837           (rt->critical)?rt->critical->parsed_as:"NONE",
838           rt->source
839     );
840
841     rt->next = host->templates;
842     host->templates = rt;
843     return 1;
844 }
845
846 static inline int health_parse_duration(char *string, int *result) {
847     // make sure it is a number
848     if(!*string || !(isdigit(*string) || *string == '+' || *string == '-')) {
849         *result = 0;
850         return 0;
851     }
852
853     char *e = NULL;
854     calculated_number n = strtold(string, &e);
855     if(e && *e) {
856         switch (*e) {
857             case 'Y':
858                 *result = (int) (n * 86400 * 365);
859                 break;
860             case 'M':
861                 *result = (int) (n * 86400 * 30);
862                 break;
863             case 'w':
864                 *result = (int) (n * 86400 * 7);
865                 break;
866             case 'd':
867                 *result = (int) (n * 86400);
868                 break;
869             case 'h':
870                 *result = (int) (n * 3600);
871                 break;
872             case 'm':
873                 *result = (int) (n * 60);
874                 break;
875
876             default:
877             case 's':
878                 *result = (int) (n);
879                 break;
880         }
881     }
882     else
883        *result = (int)(n);
884
885     return 1;
886 }
887
888 static inline int health_parse_db_lookup(
889         size_t line, const char *path, const char *file, char *string,
890         int *group_method, int *after, int *before, int *every,
891         uint32_t *options, char **dimensions
892 ) {
893     debug(D_HEALTH, "Health configuration parsing database lookup %zu@%s/%s: %s", line, path, file, string);
894
895     if(*dimensions) freez(*dimensions);
896     *dimensions = NULL;
897     *after = 0;
898     *before = 0;
899     *every = 0;
900     *options = 0;
901
902     char *s = string, *key;
903
904     // first is the group method
905     key = s;
906     while(*s && !isspace(*s)) s++;
907     while(*s && isspace(*s)) *s++ = '\0';
908     if(!*s) {
909         error("Health configuration invalid chart calculation at line %zu of file '%s/%s': expected group method followed by the 'after' time, but got '%s'",
910               line, path, file, key);
911         return 0;
912     }
913
914     if((*group_method = web_client_api_request_v1_data_group(key, -1)) == -1) {
915         error("Health configuration at line %zu of file '%s/%s': invalid group method '%s'",
916               line, path, file, key);
917         return 0;
918     }
919
920     // then is the 'after' time
921     key = s;
922     while(*s && !isspace(*s)) s++;
923     while(*s && isspace(*s)) *s++ = '\0';
924
925     if(!health_parse_duration(key, after)) {
926         error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' after group method",
927               line, path, file, key);
928         return 0;
929     }
930
931     // sane defaults
932     *every = abs(*after);
933
934     // now we may have optional parameters
935     while(*s) {
936         key = s;
937         while(*s && !isspace(*s)) s++;
938         while(*s && isspace(*s)) *s++ = '\0';
939         if(!*key) break;
940
941         if(!strcasecmp(key, "at")) {
942             char *value = s;
943             while(*s && !isspace(*s)) s++;
944             while(*s && isspace(*s)) *s++ = '\0';
945
946             if (!health_parse_duration(value, before)) {
947                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
948                       line, path, file, value, key);
949             }
950         }
951         else if(!strcasecmp(key, HEALTH_EVERY_KEY)) {
952             char *value = s;
953             while(*s && !isspace(*s)) s++;
954             while(*s && isspace(*s)) *s++ = '\0';
955
956             if (!health_parse_duration(value, every)) {
957                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
958                       line, path, file, value, key);
959             }
960         }
961         else if(!strcasecmp(key, "absolute") || !strcasecmp(key, "abs") || !strcasecmp(key, "absolute_sum")) {
962             *options |= RRDR_OPTION_ABSOLUTE;
963         }
964         else if(!strcasecmp(key, "min2max")) {
965             *options |= RRDR_OPTION_MIN2MAX;
966         }
967         else if(!strcasecmp(key, "null2zero")) {
968             *options |= RRDR_OPTION_NULL2ZERO;
969         }
970         else if(!strcasecmp(key, "percentage")) {
971             *options |= RRDR_OPTION_PERCENTAGE;
972         }
973         else if(!strcasecmp(key, "unaligned")) {
974             *options |= RRDR_OPTION_NOT_ALIGNED;
975         }
976         else if(!strcasecmp(key, "of")) {
977             if(*s && strcasecmp(s, "all"))
978                *dimensions = strdupz(s);
979             break;
980         }
981         else {
982             error("Health configuration at line %zu of file '%s/%s': unknown keyword '%s'",
983                   line, path, file, key);
984         }
985     }
986
987     return 1;
988 }
989
990 static inline char *health_source_file(size_t line, const char *path, const char *filename) {
991     char buffer[FILENAME_MAX + 1];
992     snprintfz(buffer, FILENAME_MAX, "%zu@%s/%s", line, path, filename);
993     return strdupz(buffer);
994 }
995
996 int health_readfile(const char *path, const char *filename) {
997     debug(D_HEALTH, "Health configuration reading file '%s/%s'", path, filename);
998
999     static uint32_t hash_alarm = 0, hash_template = 0, hash_on = 0, hash_calc = 0, hash_green = 0, hash_red = 0, hash_warn = 0, hash_crit = 0, hash_exec = 0, hash_every = 0, hash_lookup = 0;
1000     char buffer[HEALTH_CONF_MAX_LINE + 1];
1001
1002     if(unlikely(!hash_alarm)) {
1003         hash_alarm = simple_uhash(HEALTH_ALARM_KEY);
1004         hash_template = simple_uhash(HEALTH_TEMPLATE_KEY);
1005         hash_on = simple_uhash(HEALTH_ON_KEY);
1006         hash_calc = simple_uhash(HEALTH_CALC_KEY);
1007         hash_lookup = simple_uhash(HEALTH_LOOKUP_KEY);
1008         hash_green = simple_uhash(HEALTH_GREEN_KEY);
1009         hash_red = simple_uhash(HEALTH_RED_KEY);
1010         hash_warn = simple_uhash(HEALTH_WARN_KEY);
1011         hash_crit = simple_uhash(HEALTH_CRIT_KEY);
1012         hash_exec = simple_uhash(HEALTH_EXEC_KEY);
1013         hash_every = simple_uhash(HEALTH_EVERY_KEY);
1014     }
1015
1016     snprintfz(buffer, HEALTH_CONF_MAX_LINE, "%s/%s", path, filename);
1017     FILE *fp = fopen(buffer, "r");
1018     if(!fp) {
1019         error("Health configuration cannot read file '%s'.", buffer);
1020         return 0;
1021     }
1022
1023     RRDCALC *rc = NULL;
1024     RRDCALCTEMPLATE *rt = NULL;
1025
1026     size_t line = 0, append = 0;
1027     char *s;
1028     while((s = fgets(&buffer[append], (int)(HEALTH_CONF_MAX_LINE - append), fp)) || append) {
1029         int stop_appending = !s;
1030         line++;
1031         // info("Line %zu of file '%s/%s': '%s'", line, path, filename, s);
1032         s = trim(buffer);
1033         if(!s) continue;
1034         // info("Trimmed line %zu of file '%s/%s': '%s'", line, path, filename, s);
1035
1036         append = strlen(s);
1037         if(!stop_appending && s[append - 1] == '\\') {
1038             s[append - 1] = ' ';
1039             append = &s[append] - buffer;
1040             if(append < HEALTH_CONF_MAX_LINE)
1041                 continue;
1042             continue;
1043         }
1044         append = 0;
1045
1046         char *key = s;
1047         while(*s && *s != ':') s++;
1048         if(!*s) {
1049             error("Health configuration has invalid line %zu of file '%s/%s'. It does not contain a ':'. Ignoring it.", line, path, filename);
1050             continue;
1051         }
1052         *s = '\0';
1053         s++;
1054
1055         char *value = s;
1056         key = trim(key);
1057         value = trim(value);
1058
1059         if(!key) {
1060             error("Health configuration has invalid line %zu of file '%s/%s'. Keyword is empty. Ignoring it.", line, path, filename);
1061             continue;
1062         }
1063
1064         if(!value) {
1065             error("Health configuration has invalid line %zu of file '%s/%s'. value is empty. Ignoring it.", line, path, filename);
1066             continue;
1067         }
1068
1069         // info("Health file '%s/%s', key '%s', value '%s'", path, filename, key, value);
1070         uint32_t hash = simple_uhash(key);
1071
1072         if(hash == hash_alarm && !strcasecmp(key, HEALTH_ALARM_KEY)) {
1073             if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1074                 rrdcalc_free(&localhost, rc);
1075
1076             if(rt) {
1077                 if (!rrdcalctemplate_add_template_from_config(&localhost, rt))
1078                     rrdcalctemplate_free(&localhost, rt);
1079                 rt = NULL;
1080             }
1081
1082             rc = callocz(1, sizeof(RRDCALC));
1083             rc->name = strdupz(value);
1084             rc->hash = simple_hash(rc->name);
1085             rc->source = health_source_file(line, path, filename);
1086             rc->green = NAN;
1087             rc->red = NAN;
1088             rc->value = NAN;
1089             rc->old_value = NAN;
1090
1091             if(rrdvar_fix_name(rc->name))
1092                 error("Health configuration renamed alarm '%s' to '%s'", value, rc->name);
1093         }
1094         else if(hash == hash_template && !strcasecmp(key, HEALTH_TEMPLATE_KEY)) {
1095             if(rc) {
1096                 if(!rrdcalc_add_alarm_from_config(&localhost, rc))
1097                     rrdcalc_free(&localhost, rc);
1098                 rc = NULL;
1099             }
1100
1101             if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1102                 rrdcalctemplate_free(&localhost, rt);
1103
1104             rt = callocz(1, sizeof(RRDCALCTEMPLATE));
1105             rt->name = strdupz(value);
1106             rt->hash_name = simple_hash(rt->name);
1107             rt->source = health_source_file(line, path, filename);
1108             rt->green = NAN;
1109             rt->red = NAN;
1110
1111             if(rrdvar_fix_name(rt->name))
1112                 error("Health configuration renamed template '%s' to '%s'", value, rt->name);
1113         }
1114         else if(rc) {
1115             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1116                 if(rc->chart) {
1117                     if(strcmp(rc->chart, value))
1118                         info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1119                              line, path, filename, rc->name, key, rc->chart, value, value);
1120
1121                     freez(rc->chart);
1122                 }
1123                 rc->chart = strdupz(value);
1124                 rc->hash_chart = simple_hash(rc->chart);
1125             }
1126             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1127                 health_parse_db_lookup(line, path, filename, value, &rc->group, &rc->after, &rc->before,
1128                                        &rc->update_every,
1129                                        &rc->options, &rc->dimensions);
1130             }
1131             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1132                 if(!health_parse_duration(value, &rc->update_every))
1133                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' cannot parse duration: '%s'.",
1134                          line, path, filename, rc->name, key, value);
1135             }
1136             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1137                 char *e;
1138                 rc->green = strtold(value, &e);
1139                 if(e && *e) {
1140                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1141                          line, path, filename, rc->name, key, e);
1142                 }
1143             }
1144             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1145                 char *e;
1146                 rc->red = strtold(value, &e);
1147                 if(e && *e) {
1148                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1149                          line, path, filename, rc->name, key, e);
1150                 }
1151             }
1152             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1153                 const char *failed_at = NULL;
1154                 int error = 0;
1155                 rc->calculation = expression_parse(value, &failed_at, &error);
1156                 if(!rc->calculation) {
1157                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1158                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1159                 }
1160             }
1161             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1162                 const char *failed_at = NULL;
1163                 int error = 0;
1164                 rc->warning = expression_parse(value, &failed_at, &error);
1165                 if(!rc->warning) {
1166                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1167                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1168                 }
1169             }
1170             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1171                 const char *failed_at = NULL;
1172                 int error = 0;
1173                 rc->critical = expression_parse(value, &failed_at, &error);
1174                 if(!rc->critical) {
1175                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1176                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1177                 }
1178             }
1179             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1180                 if(rc->exec) {
1181                     if(strcmp(rc->exec, value))
1182                         info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1183                              line, path, filename, rc->name, key, rc->exec, value, value);
1184
1185                     freez(rc->exec);
1186                 }
1187                 rc->exec = strdupz(value);
1188             }
1189             else {
1190                 error("Health configuration at line %zu of file '%s/%s' for alarm '%s' has unknown key '%s'.",
1191                      line, path, filename, rc->name, key);
1192             }
1193         }
1194         else if(rt) {
1195             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1196                 if(rt->context) {
1197                     if(strcmp(rt->context, value))
1198                         info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1199                              line, path, filename, rt->name, key, rt->context, value, value);
1200
1201                     freez(rt->context);
1202                 }
1203                 rt->context = strdupz(value);
1204                 rt->hash_context = simple_hash(rt->context);
1205             }
1206             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1207                 health_parse_db_lookup(line, path, filename, value, &rt->group, &rt->after, &rt->before,
1208                                        &rt->update_every,
1209                                        &rt->options, &rt->dimensions);
1210             }
1211             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1212                 if(!health_parse_duration(value, &rt->update_every))
1213                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' cannot parse duration: '%s'.",
1214                          line, path, filename, rt->name, key, value);
1215             }
1216             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1217                 char *e;
1218                 rt->green = strtold(value, &e);
1219                 if(e && *e) {
1220                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1221                          line, path, filename, rt->name, key, e);
1222                 }
1223             }
1224             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1225                 char *e;
1226                 rt->red = strtold(value, &e);
1227                 if(e && *e) {
1228                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1229                          line, path, filename, rt->name, key, e);
1230                 }
1231             }
1232             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1233                 const char *failed_at = NULL;
1234                 int error = 0;
1235                 rt->calculation = expression_parse(value, &failed_at, &error);
1236                 if(!rt->calculation) {
1237                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1238                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1239                 }
1240             }
1241             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1242                 const char *failed_at = NULL;
1243                 int error = 0;
1244                 rt->warning = expression_parse(value, &failed_at, &error);
1245                 if(!rt->warning) {
1246                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1247                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1248                 }
1249             }
1250             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1251                 const char *failed_at = NULL;
1252                 int error = 0;
1253                 rt->critical = expression_parse(value, &failed_at, &error);
1254                 if(!rt->critical) {
1255                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1256                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1257                 }
1258             }
1259             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1260                 if(rt->exec) {
1261                     if(strcmp(rt->exec, value))
1262                         info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
1263                              line, path, filename, rt->name, key, rt->exec, value, value);
1264
1265                     freez(rt->exec);
1266                 }
1267                 rt->exec = strdupz(value);
1268             }
1269             else {
1270                 error("Health configuration at line %zu of file '%s/%s' for template '%s' has unknown key '%s'.",
1271                       line, path, filename, rt->name, key);
1272             }
1273         }
1274         else {
1275             error("Health configuration at line %zu of file '%s/%s' has unknown key '%s'. Expected either '" HEALTH_ALARM_KEY "' or '" HEALTH_TEMPLATE_KEY "'.",
1276                   line, path, filename, key);
1277         }
1278     }
1279
1280     if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1281         rrdcalc_free(&localhost, rc);
1282
1283     if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1284         rrdcalctemplate_free(&localhost, rt);
1285
1286     fclose(fp);
1287     return 1;
1288 }
1289
1290 void health_readdir(const char *path) {
1291     size_t pathlen = strlen(path);
1292
1293     debug(D_HEALTH, "Health configuration reading directory '%s'", path);
1294
1295     DIR *dir = opendir(path);
1296     if (!dir) {
1297         error("Health configuration cannot open directory '%s'.", path);
1298         return;
1299     }
1300
1301     struct dirent *de = NULL;
1302     while ((de = readdir(dir))) {
1303         size_t len = strlen(de->d_name);
1304
1305         if(de->d_type == DT_DIR
1306            && (
1307                    (de->d_name[0] == '.' && de->d_name[1] == '\0')
1308                    || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0')
1309            ))
1310             continue;
1311
1312         else if(de->d_type == DT_DIR) {
1313             char *s = mallocz(pathlen + strlen(de->d_name) + 2);
1314             strcpy(s, path);
1315             strcat(s, "/");
1316             strcat(s, de->d_name);
1317             health_readdir(s);
1318             freez(s);
1319             continue;
1320         }
1321
1322         else if((de->d_type == DT_LNK || de->d_type == DT_REG) &&
1323                 len > 5 && !strcmp(&de->d_name[len - 5], ".conf")) {
1324             health_readfile(path, de->d_name);
1325         }
1326     }
1327
1328     closedir(dir);
1329 }
1330
1331 static inline char *health_config_dir(void) {
1332     char buffer[FILENAME_MAX + 1];
1333     snprintfz(buffer, FILENAME_MAX, "%s/health.d", config_get("global", "config directory", CONFIG_DIR));
1334     return config_get("health", "health configuration directory", buffer);
1335 }
1336
1337 void health_init(void) {
1338     debug(D_HEALTH, "Health configuration initializing");
1339
1340     if(!(health_enabled = config_get_boolean("health", "enabled", 1))) {
1341         debug(D_HEALTH, "Health is disabled.");
1342         return;
1343     }
1344
1345     char *path = health_config_dir();
1346
1347     {
1348         char buffer[FILENAME_MAX + 1];
1349         snprintfz(buffer, FILENAME_MAX, "%s/alarm-email.sh", config_get("global", "plugins directory", PLUGINS_DIR));
1350         health_default_exec = config_get("health", "script to execute on alarm", buffer);
1351     }
1352
1353     long n = config_get_number("health", "in memory max health log entries", (long)health_log.max);
1354     if(n < 2) {
1355         error("Health configuration has invalid max log entries %ld. Using default %u", n, health_log.max);
1356         config_set_number("health", "in memory max health log entries", (long)health_log.max);
1357     }
1358     else health_log.max = (unsigned int)n;
1359
1360     rrdhost_rwlock(&localhost);
1361     health_readdir(path);
1362     rrdhost_unlock(&localhost);
1363 }
1364
1365 // ----------------------------------------------------------------------------
1366 // re-load health configuration
1367
1368 static inline void health_free_all_nolock(RRDHOST *host) {
1369     while(host->templates)
1370         rrdcalctemplate_free(host, host->templates);
1371
1372     while(host->alarms)
1373         rrdcalc_free(host, host->alarms);
1374 }
1375
1376 void health_reload(void) {
1377     if(!health_enabled) {
1378         error("Health reload is requested, but health is not enabled.");
1379         return;
1380     }
1381
1382     char *path = health_config_dir();
1383
1384     rrdhost_rwlock(&localhost);
1385     health_free_all_nolock(&localhost);
1386     rrdhost_unlock(&localhost);
1387
1388     rrdhost_rwlock(&localhost);
1389     health_readdir(path);
1390     rrdhost_unlock(&localhost);
1391
1392     RRDSET *st;
1393     for(st = localhost.rrdset_root; st ; st = st->next) {
1394         rrdhost_rwlock(&localhost);
1395
1396         st->green = NAN;
1397         st->red = NAN;
1398
1399         rrdsetcalc_link_matching(st);
1400         rrdcalctemplate_link_matching(st);
1401
1402         rrdhost_unlock(&localhost);
1403     }
1404 }
1405
1406
1407 // ----------------------------------------------------------------------------
1408 // health main thread and friends
1409
1410 static inline int rrdcalc_isrunnable(RRDCALC *rc, time_t now, time_t *next_run) {
1411     if (unlikely(!rc->rrdset)) {
1412         debug(D_HEALTH, "Health not running alarm '%s.%s'. It is not linked to a chart.", rc->chart?rc->chart:"NOCHART", rc->name);
1413         return 0;
1414     }
1415
1416     if (unlikely(!rc->update_every)) {
1417         debug(D_HEALTH, "Health not running alarm '%s.%s'. It does not have an update frequency", rc->chart?rc->chart:"NOCHART", rc->name);
1418         return 0;
1419     }
1420
1421     if (unlikely(rc->next_update > now)) {
1422         if (*next_run > rc->next_update)
1423             *next_run = rc->next_update;
1424
1425         debug(D_HEALTH, "Health not examining alarm '%s.%s' yet (will do in %d secs).", rc->chart?rc->chart:"NOCHART", rc->name, (int) (rc->next_update - now));
1426         return 0;
1427     }
1428
1429     return 1;
1430 }
1431
1432 static inline int rrdcalc_value2status(calculated_number n) {
1433     if(isnan(n)) return RRDCALC_STATUS_UNDEFINED;
1434     if(n) return RRDCALC_STATUS_RAISED;
1435     return RRDCALC_STATUS_CLEAR;
1436 }
1437
1438 static inline const char *rrdcalc_status2string(int status) {
1439     switch(status) {
1440         case RRDCALC_STATUS_UNINITIALIZED:
1441             return "UNINITIALIZED";
1442
1443         case RRDCALC_STATUS_UNDEFINED:
1444             return "UNDEFINED";
1445
1446         case RRDCALC_STATUS_CLEAR:
1447             return "CLEAR";
1448
1449         case RRDCALC_STATUS_RAISED:
1450             return "RAISED";
1451
1452         case RRDCALC_STATUS_WARNING:
1453             return "WARNING";
1454
1455         case RRDCALC_STATUS_CRITICAL:
1456             return "CRITICAL";
1457
1458         default:
1459             return "UNKNOWN";
1460     }
1461 }
1462
1463 static inline void health_alarm_execute(ALARM_ENTRY *ae) {
1464     if(ae->old_status == RRDCALC_STATUS_UNINITIALIZED && ae->new_status == RRDCALC_STATUS_CLEAR)
1465         return;
1466
1467     char buffer[FILENAME_MAX + 1];
1468     pid_t command_pid;
1469
1470     const char *exec = ae->exec;
1471     if(!exec) exec = health_default_exec;
1472
1473     snprintfz(buffer, FILENAME_MAX, "exec %s '%s' '%s' '%s' '%s' '%0.0Lf' '%0.0Lf' '%s' '%u' '%u'",
1474               exec,
1475               ae->name,
1476               ae->chart?ae->chart:"NOCAHRT",
1477               rrdcalc_status2string(ae->new_status),
1478               rrdcalc_status2string(ae->old_status),
1479               ae->new_value,
1480               ae->old_value,
1481               ae->source?ae->source:"UNKNOWN",
1482               (uint32_t)ae->duration,
1483               (uint32_t)ae->non_clear_duration
1484     );
1485
1486     debug(D_HEALTH, "executing command '%s'", buffer);
1487     FILE *fp = mypopen(buffer, &command_pid);
1488     if(!fp) {
1489         error("HEALTH: Cannot popen(\"%s\", \"r\").", buffer);
1490         return;
1491     }
1492     debug(D_HEALTH, "HEALTH reading from command");
1493     char *s = fgets(buffer, FILENAME_MAX, fp);
1494     (void)s;
1495     debug(D_HEALTH, "HEALTH closing command");
1496     mypclose(fp, command_pid);
1497     debug(D_HEALTH, "closed command");
1498 }
1499
1500 static inline void health_process_notifications(ALARM_ENTRY *ae) {
1501     info("Health alarm '%s.%s' = %0.2Lf - changed status from %s to %s",
1502          ae->chart?ae->chart:"NOCHART", ae->name,
1503          ae->new_value,
1504          rrdcalc_status2string(ae->old_status),
1505          rrdcalc_status2string(ae->new_status)
1506     );
1507
1508     health_alarm_execute(ae);
1509 }
1510
1511 static inline void health_alarm_log(time_t when,
1512                 const char *name, const char *chart, const char *exec,
1513                 time_t duration,
1514                 calculated_number old_value, calculated_number new_value,
1515                 int old_status, int new_status,
1516                 const char *source
1517 ) {
1518     ALARM_ENTRY *ae = callocz(1, sizeof(ALARM_ENTRY));
1519     ae->name = strdupz(name);
1520     ae->hash_name = simple_hash(ae->name);
1521
1522     if(chart) {
1523         ae->chart = strdupz(chart);
1524         ae->hash_chart = simple_hash(ae->chart);
1525     }
1526
1527     if(exec) ae->exec = strdupz(exec);
1528     if(source) ae->source = strdupz(source);
1529
1530     ae->id = health_log.nextid++;
1531     ae->when = when;
1532     ae->old_value = old_value;
1533     ae->new_value = new_value;
1534     ae->old_status = old_status;
1535     ae->new_status = new_status;
1536     ae->duration = duration;
1537
1538     if(ae->old_status == RRDCALC_STATUS_WARNING || ae->old_status == RRDCALC_STATUS_CRITICAL)
1539         ae->non_clear_duration += ae->duration;
1540
1541     // link it
1542     ae->next = health_log.alarms;
1543     health_log.alarms = ae;
1544     health_log.count++;
1545
1546     // match previous alarms
1547     ALARM_ENTRY *t;
1548     for(t = health_log.alarms ; t ; t = t->next) {
1549         if(t != ae &&
1550                 t->hash_name == ae->hash_name &&
1551                 t->hash_chart == ae->hash_chart &&
1552                 !strcmp(t->name, ae->name) &&
1553                 t->chart && ae->chart && !strcmp(t->chart, ae->chart)) {
1554
1555             if(!(t->notifications & HEALTH_ENTRY_NOTIFICATIONS_UPDATED) && !t->updated_by) {
1556                 t->notifications |= HEALTH_ENTRY_NOTIFICATIONS_UPDATED;
1557                 t->updated_by = ae;
1558
1559                 if((t->new_status == RRDCALC_STATUS_WARNING || t->new_status == RRDCALC_STATUS_CRITICAL) &&
1560                    (t->old_status == RRDCALC_STATUS_WARNING || t->old_status == RRDCALC_STATUS_CRITICAL))
1561                     ae->non_clear_duration += t->non_clear_duration;
1562             }
1563             else {
1564                 // no need to continue
1565                 break;
1566             }
1567         }
1568     }
1569 }
1570
1571 static inline void health_alarm_log_process(void) {
1572     static uint32_t last_processed = 0;
1573     ALARM_ENTRY *ae;
1574
1575     for(ae = health_log.alarms; ae ;ae = ae->next) {
1576         if(last_processed >= ae->id) break;
1577
1578         if(!(ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_PROCESSED) &&
1579                 !(ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_UPDATED)) {
1580             ae->notifications |= HEALTH_ENTRY_NOTIFICATIONS_PROCESSED;
1581             health_process_notifications(ae);
1582         }
1583     }
1584
1585     if(health_log.alarms)
1586         last_processed = health_log.alarms->id;
1587
1588     if(health_log.count <= health_log.max)
1589         return;
1590
1591     // cleanup excess entries in the log
1592     ALARM_ENTRY *last = NULL;
1593     unsigned int count = health_log.max;
1594     for(ae = health_log.alarms; ae && count ; count--, last = ae, ae = ae->next) ;
1595     if(!ae || !last || last->next != ae) return;
1596     last->next = NULL;
1597
1598     while(ae) {
1599         ALARM_ENTRY *t = ae->next;
1600
1601         freez(ae->chart);
1602         freez(ae->name);
1603         freez(ae->exec);
1604         freez(ae);
1605
1606         ae = t;
1607     }
1608 }
1609
1610 void *health_main(void *ptr) {
1611     (void)ptr;
1612
1613     info("HEALTH thread created with task id %d", gettid());
1614
1615     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1616         error("Cannot set pthread cancel type to DEFERRED.");
1617
1618     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1619         error("Cannot set pthread cancel state to ENABLE.");
1620
1621     int min_run_every = (int)config_get_number("health", "run at least every seconds", 10);
1622     if(min_run_every < 1) min_run_every = 1;
1623
1624     BUFFER *wb = buffer_create(100);
1625
1626     unsigned int loop = 0;
1627     while(health_enabled) {
1628         loop++;
1629         debug(D_HEALTH, "Health monitoring iteration no %u started", loop);
1630
1631         int oldstate, runnable = 0;
1632         time_t now = time(NULL);
1633         time_t next_run = now + min_run_every;
1634         RRDCALC *rc;
1635
1636         if (unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) != 0))
1637             error("Cannot set pthread cancel state to DISABLE.");
1638
1639         rrdhost_rdlock(&localhost);
1640
1641         // the first loop is to lookup values from the db
1642         for (rc = localhost.alarms; rc; rc = rc->next) {
1643             if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
1644                 continue;
1645
1646             runnable++;
1647             rc->old_value = rc->value;
1648
1649             // 1. if there is database lookup, do it
1650             // 2. if there is calculation expression, run it
1651
1652             if (unlikely(RRDCALC_HAS_DB_LOOKUP(rc))) {
1653                 time_t old_db_timestamp = rc->db_timestamp;
1654                 int value_is_null = 0;
1655
1656                 int ret = rrd2value(rc->rrdset, wb, &rc->value,
1657                                     rc->dimensions, 1, rc->after, rc->before, rc->group,
1658                                     rc->options, &rc->db_timestamp, &value_is_null);
1659
1660                 if (unlikely(ret != 200)) {
1661                     // database lookup failed
1662                     rc->value = NAN;
1663
1664                     debug(D_HEALTH, "Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
1665
1666                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_ERROR))) {
1667                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_ERROR;
1668                         error("Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
1669                     }
1670                 }
1671                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_ERROR))
1672                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_ERROR;
1673
1674                 if (unlikely(old_db_timestamp == rc->db_timestamp)) {
1675                     // database is stale
1676
1677                     debug(D_HEALTH, "Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
1678
1679                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_STALE))) {
1680                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_STALE;
1681                         error("Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
1682                     }
1683                 }
1684                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_STALE))
1685                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_STALE;
1686
1687                 if (unlikely(value_is_null)) {
1688                     // collected value is null
1689
1690                     rc->value = NAN;
1691
1692                     debug(D_HEALTH, "Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
1693                           rc->chart?rc->chart:"NOCHART", rc->name);
1694
1695                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_NAN))) {
1696                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_NAN;
1697                         error("Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
1698                               rc->chart?rc->chart:"NOCHART", rc->name);
1699                     }
1700                 }
1701                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_NAN))
1702                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_NAN;
1703
1704                 debug(D_HEALTH, "Health alarm '%s.%s': database lookup gave value "
1705                         CALCULATED_NUMBER_FORMAT, rc->chart?rc->chart:"NOCHART", rc->name, rc->value);
1706             }
1707
1708             if(unlikely(rc->calculation)) {
1709                 if (unlikely(!expression_evaluate(rc->calculation))) {
1710                     // calculation failed
1711
1712                     rc->value = NAN;
1713
1714                     debug(D_HEALTH, "Health alarm '%s.%s': failed to evaluate calculation with error: %s",
1715                           rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
1716
1717                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_CALC_ERROR))) {
1718                         rc->rrdcalc_options |= RRDCALC_OPTION_CALC_ERROR;
1719                         error("Health alarm '%s.%s': failed to evaluate calculation with error: %s",
1720                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
1721                     }
1722                 }
1723                 else {
1724                     if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_CALC_ERROR))
1725                         rc->rrdcalc_options &= ~RRDCALC_OPTION_CALC_ERROR;
1726
1727                     debug(D_HEALTH, "Health alarm '%s.%s': calculation expression gave value "
1728                             CALCULATED_NUMBER_FORMAT
1729                             ": %s (source: %s)",
1730                           rc->chart?rc->chart:"NOCHART", rc->name,
1731                           rc->calculation->result,
1732                           buffer_tostring(rc->calculation->error_msg),
1733                           rc->source
1734                     );
1735
1736                     rc->value = rc->calculation->result;
1737                 }
1738             }
1739         }
1740         rrdhost_unlock(&localhost);
1741
1742         if (runnable) {
1743             rrdhost_rdlock(&localhost);
1744
1745             for (rc = localhost.alarms; rc; rc = rc->next) {
1746                 if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
1747                     continue;
1748
1749                 int warning_status  = RRDCALC_STATUS_UNDEFINED;
1750                 int critical_status = RRDCALC_STATUS_UNDEFINED;
1751
1752                 if(unlikely(rc->warning)) {
1753                     if(unlikely(!expression_evaluate(rc->warning))) {
1754                         // calculation failed
1755
1756                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression failed with error: %s",
1757                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
1758
1759                         if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_WARN_ERROR))) {
1760                             rc->rrdcalc_options |= RRDCALC_OPTION_WARN_ERROR;
1761                             error("Health alarm '%s.%s': warning expression failed with error: %s",
1762                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
1763                         }
1764                     }
1765                     else {
1766                         if(unlikely(rc->rrdcalc_options & RRDCALC_OPTION_WARN_ERROR))
1767                             rc->rrdcalc_options &= ~RRDCALC_OPTION_WARN_ERROR;
1768
1769                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression gave value "
1770                                 CALCULATED_NUMBER_FORMAT
1771                                 ": %s (source: %s)",
1772                               rc->chart?rc->chart:"NOCHART", rc->name,
1773                               rc->warning->result,
1774                               buffer_tostring(rc->warning->error_msg),
1775                               rc->source
1776                         );
1777
1778                         warning_status = rrdcalc_value2status(rc->warning->result);
1779                     }
1780                 }
1781
1782                 if(unlikely(rc->critical)) {
1783                     if(unlikely(!expression_evaluate(rc->critical))) {
1784                         // calculation failed
1785
1786                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression failed with error: %s",
1787                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
1788
1789                         if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_CRIT_ERROR))) {
1790                             rc->rrdcalc_options |= RRDCALC_OPTION_CRIT_ERROR;
1791                             error("Health alarm '%s.%s': critical expression failed with error: %s",
1792                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
1793                         }
1794                     }
1795                     else {
1796                         if(unlikely(rc->rrdcalc_options & RRDCALC_OPTION_CRIT_ERROR))
1797                             rc->rrdcalc_options &= ~RRDCALC_OPTION_CRIT_ERROR;
1798
1799                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression gave value "
1800                                 CALCULATED_NUMBER_FORMAT
1801                                 ": %s (source: %s)",
1802                               rc->chart?rc->chart:"NOCHART", rc->name,
1803                               rc->critical->result,
1804                               buffer_tostring(rc->critical->error_msg),
1805                               rc->source
1806                         );
1807
1808                         critical_status = rrdcalc_value2status(rc->critical->result);
1809                     }
1810                 }
1811
1812                 int status = RRDCALC_STATUS_UNDEFINED;
1813
1814                 switch(warning_status) {
1815                     case RRDCALC_STATUS_CLEAR:
1816                         status = RRDCALC_STATUS_CLEAR;
1817                         break;
1818
1819                     case RRDCALC_STATUS_RAISED:
1820                         status = RRDCALC_STATUS_WARNING;
1821                         break;
1822
1823                     default:
1824                         break;
1825                 }
1826
1827                 switch(critical_status) {
1828                     case RRDCALC_STATUS_CLEAR:
1829                         if(status == RRDCALC_STATUS_UNDEFINED)
1830                             status = RRDCALC_STATUS_CLEAR;
1831                         break;
1832
1833                     case RRDCALC_STATUS_RAISED:
1834                         status = RRDCALC_STATUS_CRITICAL;
1835                         break;
1836
1837                     default:
1838                         break;
1839                 }
1840
1841                 if(status != rc->status) {
1842                     health_alarm_log(time(NULL), rc->name, rc->rrdset->id, rc->exec, now - rc->last_status_change, rc->old_value, rc->value, rc->status, status, rc->source);
1843                     rc->last_status_change = now;
1844                     rc->status = status;
1845                 }
1846
1847                 rc->last_updated = now;
1848                 rc->next_update = now + rc->update_every;
1849
1850                 if (next_run > rc->next_update)
1851                     next_run = rc->next_update;
1852             }
1853
1854             rrdhost_unlock(&localhost);
1855         }
1856
1857         if (unlikely(pthread_setcancelstate(oldstate, NULL) != 0))
1858             error("Cannot set pthread cancel state to RESTORE (%d).", oldstate);
1859
1860         // execute notifications
1861         // and cleanup
1862         health_alarm_log_process();
1863
1864         now = time(NULL);
1865         if(now < next_run) {
1866             debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration in %d secs",
1867                   loop, (int) (next_run - now));
1868             sleep_usec(1000000 * (unsigned long long) (next_run - now));
1869         }
1870         else {
1871             debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration now", loop);
1872         }
1873     }
1874
1875     buffer_free(wb);
1876
1877     info("HEALTH thread exiting");
1878     pthread_exit(NULL);
1879     return NULL;
1880 }