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