]> arthur.barton.de Git - netdata.git/blob - src/health.c
properly handle interactions between CLEAR, WARNING, CRITICAL
[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->rrdcontext->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->rrdcontext->id);
175     avl_traverse_lock(&st->rrdcontext->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->rrdcontext->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->rrdcontext->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->rrdcontext->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->rrdcontext->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->rrdcontext->variables_root_index, rs->context);
251     rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host);
252     rrdvar_free(st->rrdhost, &st->rrdcontext->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->rrdcontext->variables_root_index, rs->id, rs->type, rs->value);
317     rs->context_name = rrdvar_create_and_index("context", &st->rrdcontext->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->rrdcontext->variables_root_index, rs->context_id);
384     rrdvar_free(st->rrdhost, &st->rrdcontext->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->rrdcontext->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->rrdcontext->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(!RRDCALC_HAS_DB_LOOKUP(rc) && !rc->warning && !rc->critical) {
759         error("Health configuration for alarm '%s.%s' is useless (no calculation, no warning and no critical evaluation)", rc->chart?rc->chart:"NOCHART", rc->name);
760         return 0;
761     }
762
763     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",
764           rc->chart?rc->chart:"NOCHART",
765           rc->name,
766           (rc->exec)?rc->exec:"DEFAULT",
767           rc->green,
768           rc->red,
769           rc->group,
770           rc->after,
771           rc->before,
772           rc->options,
773           (rc->dimensions)?rc->dimensions:"NONE",
774           rc->update_every,
775           (rc->calculation)?rc->calculation->parsed_as:"NONE",
776           (rc->warning)?rc->warning->parsed_as:"NONE",
777           (rc->critical)?rc->critical->parsed_as:"NONE",
778           rc->source
779     );
780
781     rrdcalc_create_part2(host, rc);
782     return 1;
783 }
784
785 static inline int rrdcalctemplate_add_template_from_config(RRDHOST *host, RRDCALCTEMPLATE *rt) {
786     if(!rt->context) {
787         error("Health configuration for template '%s' does not have a context", rt->name);
788         return 0;
789     }
790
791     if(!RRDCALCTEMPLATE_HAS_CALCULATION(rt) && !rt->warning && !rt->critical) {
792         error("Health configuration for template '%s' is useless (no calculation, no warning and no critical evaluation)", rt->name);
793         return 0;
794     }
795
796     RRDCALCTEMPLATE *t;
797     for (t = host->templates; t ; t = t->next) {
798         if(t->hash_name == rt->hash_name && !strcmp(t->name, rt->name)) {
799             error("Health configuration template '%s' already exists for host '%s'.", rt->name, host->hostname);
800             return 0;
801         }
802     }
803
804     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'",
805           rt->name,
806           (rt->context)?rt->context:"NONE",
807           (rt->exec)?rt->exec:"DEFAULT",
808           rt->green,
809           rt->red,
810           rt->group,
811           rt->after,
812           rt->before,
813           rt->options,
814           (rt->dimensions)?rt->dimensions:"NONE",
815           rt->update_every,
816           (rt->calculation)?rt->calculation->parsed_as:"NONE",
817           (rt->warning)?rt->warning->parsed_as:"NONE",
818           (rt->critical)?rt->critical->parsed_as:"NONE",
819           rt->source
820     );
821
822     rt->next = host->templates;
823     host->templates = rt;
824     return 1;
825 }
826
827 static inline int health_parse_duration(char *string, int *result) {
828     // make sure it is a number
829     if(!*string || !(isdigit(*string) || *string == '+' || *string == '-')) {
830         *result = 0;
831         return 0;
832     }
833
834     char *e = NULL;
835     calculated_number n = strtold(string, &e);
836     if(e && *e) {
837         switch (*e) {
838             case 'Y':
839                 *result = (int) (n * 86400 * 365);
840                 break;
841             case 'M':
842                 *result = (int) (n * 86400 * 30);
843                 break;
844             case 'w':
845                 *result = (int) (n * 86400 * 7);
846                 break;
847             case 'd':
848                 *result = (int) (n * 86400);
849                 break;
850             case 'h':
851                 *result = (int) (n * 3600);
852                 break;
853             case 'm':
854                 *result = (int) (n * 60);
855                 break;
856
857             default:
858             case 's':
859                 *result = (int) (n);
860                 break;
861         }
862     }
863     else
864        *result = (int)(n);
865
866     return 1;
867 }
868
869 static inline int health_parse_db_lookup(
870         size_t line, const char *path, const char *file, char *string,
871         int *group_method, int *after, int *before, int *every,
872         uint32_t *options, char **dimensions
873 ) {
874     debug(D_HEALTH, "Health configuration parsing database lookup %zu@%s/%s: %s", line, path, file, string);
875
876     if(*dimensions) freez(*dimensions);
877     *dimensions = NULL;
878     *after = 0;
879     *before = 0;
880     *every = 0;
881     *options = 0;
882
883     char *s = string, *key;
884
885     // first is the group method
886     key = s;
887     while(*s && !isspace(*s)) s++;
888     while(*s && isspace(*s)) *s++ = '\0';
889     if(!*s) {
890         error("Health configuration invalid chart calculation at line %zu of file '%s/%s': expected group method followed by the 'after' time, but got '%s'",
891               line, path, file, key);
892         return 0;
893     }
894
895     if((*group_method = web_client_api_request_v1_data_group(key, -1)) == -1) {
896         error("Health configuration at line %zu of file '%s/%s': invalid group method '%s'",
897               line, path, file, key);
898         return 0;
899     }
900
901     // then is the 'after' time
902     key = s;
903     while(*s && !isspace(*s)) s++;
904     while(*s && isspace(*s)) *s++ = '\0';
905
906     if(!health_parse_duration(key, after)) {
907         error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' after group method",
908               line, path, file, key);
909         return 0;
910     }
911
912     // sane defaults
913     *every = abs(*after);
914
915     // now we may have optional parameters
916     while(*s) {
917         key = s;
918         while(*s && !isspace(*s)) s++;
919         while(*s && isspace(*s)) *s++ = '\0';
920         if(!*key) break;
921
922         if(!strcasecmp(key, "at")) {
923             char *value = s;
924             while(*s && !isspace(*s)) s++;
925             while(*s && isspace(*s)) *s++ = '\0';
926
927             if (!health_parse_duration(value, before)) {
928                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
929                       line, path, file, value, key);
930             }
931         }
932         else if(!strcasecmp(key, HEALTH_EVERY_KEY)) {
933             char *value = s;
934             while(*s && !isspace(*s)) s++;
935             while(*s && isspace(*s)) *s++ = '\0';
936
937             if (!health_parse_duration(value, every)) {
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, "absolute") || !strcasecmp(key, "abs") || !strcasecmp(key, "absolute_sum")) {
943             *options |= RRDR_OPTION_ABSOLUTE;
944         }
945         else if(!strcasecmp(key, "min2max")) {
946             *options |= RRDR_OPTION_MIN2MAX;
947         }
948         else if(!strcasecmp(key, "null2zero")) {
949             *options |= RRDR_OPTION_NULL2ZERO;
950         }
951         else if(!strcasecmp(key, "percentage")) {
952             *options |= RRDR_OPTION_PERCENTAGE;
953         }
954         else if(!strcasecmp(key, "unaligned")) {
955             *options |= RRDR_OPTION_NOT_ALIGNED;
956         }
957         else if(!strcasecmp(key, "of")) {
958             if(*s && strcasecmp(s, "all"))
959                *dimensions = strdupz(s);
960             break;
961         }
962         else {
963             error("Health configuration at line %zu of file '%s/%s': unknown keyword '%s'",
964                   line, path, file, key);
965         }
966     }
967
968     return 1;
969 }
970
971 static inline char *health_source_file(size_t line, const char *path, const char *filename) {
972     char buffer[FILENAME_MAX + 1];
973     snprintfz(buffer, FILENAME_MAX, "%zu@%s/%s", line, path, filename);
974     return strdupz(buffer);
975 }
976
977 int health_readfile(const char *path, const char *filename) {
978     debug(D_HEALTH, "Health configuration reading file '%s/%s'", path, filename);
979
980     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;
981     char buffer[HEALTH_CONF_MAX_LINE + 1];
982
983     if(unlikely(!hash_alarm)) {
984         hash_alarm = simple_uhash(HEALTH_ALARM_KEY);
985         hash_template = simple_uhash(HEALTH_TEMPLATE_KEY);
986         hash_on = simple_uhash(HEALTH_ON_KEY);
987         hash_calc = simple_uhash(HEALTH_CALC_KEY);
988         hash_lookup = simple_uhash(HEALTH_LOOKUP_KEY);
989         hash_green = simple_uhash(HEALTH_GREEN_KEY);
990         hash_red = simple_uhash(HEALTH_RED_KEY);
991         hash_warn = simple_uhash(HEALTH_WARN_KEY);
992         hash_crit = simple_uhash(HEALTH_CRIT_KEY);
993         hash_exec = simple_uhash(HEALTH_EXEC_KEY);
994         hash_every = simple_uhash(HEALTH_EVERY_KEY);
995     }
996
997     snprintfz(buffer, HEALTH_CONF_MAX_LINE, "%s/%s", path, filename);
998     FILE *fp = fopen(buffer, "r");
999     if(!fp) {
1000         error("Health configuration cannot read file '%s'.", buffer);
1001         return 0;
1002     }
1003
1004     RRDCALC *rc = NULL;
1005     RRDCALCTEMPLATE *rt = NULL;
1006
1007     size_t line = 0, append = 0;
1008     char *s;
1009     while((s = fgets(&buffer[append], (int)(HEALTH_CONF_MAX_LINE - append), fp)) || append) {
1010         int stop_appending = !s;
1011         line++;
1012         // info("Line %zu of file '%s/%s': '%s'", line, path, filename, s);
1013         s = trim(buffer);
1014         if(!s) continue;
1015         // info("Trimmed line %zu of file '%s/%s': '%s'", line, path, filename, s);
1016
1017         append = strlen(s);
1018         if(!stop_appending && s[append - 1] == '\\') {
1019             s[append - 1] = ' ';
1020             append = &s[append] - buffer;
1021             if(append < HEALTH_CONF_MAX_LINE)
1022                 continue;
1023             continue;
1024         }
1025         append = 0;
1026
1027         char *key = s;
1028         while(*s && *s != ':') s++;
1029         if(!*s) {
1030             error("Health configuration has invalid line %zu of file '%s/%s'. It does not contain a ':'. Ignoring it.", line, path, filename);
1031             continue;
1032         }
1033         *s = '\0';
1034         s++;
1035
1036         char *value = s;
1037         key = trim(key);
1038         value = trim(value);
1039
1040         if(!key) {
1041             error("Health configuration has invalid line %zu of file '%s/%s'. Keyword is empty. Ignoring it.", line, path, filename);
1042             continue;
1043         }
1044
1045         if(!value) {
1046             error("Health configuration has invalid line %zu of file '%s/%s'. value is empty. Ignoring it.", line, path, filename);
1047             continue;
1048         }
1049
1050         // info("Health file '%s/%s', key '%s', value '%s'", path, filename, key, value);
1051         uint32_t hash = simple_uhash(key);
1052
1053         if(hash == hash_alarm && !strcasecmp(key, HEALTH_ALARM_KEY)) {
1054             if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1055                 rrdcalc_free(&localhost, rc);
1056
1057             if(rt) {
1058                 if (!rrdcalctemplate_add_template_from_config(&localhost, rt))
1059                     rrdcalctemplate_free(&localhost, rt);
1060                 rt = NULL;
1061             }
1062
1063             rc = callocz(1, sizeof(RRDCALC));
1064             rc->name = strdupz(value);
1065             rc->hash = simple_hash(rc->name);
1066             rc->source = health_source_file(line, path, filename);
1067             rc->value = NAN;
1068             rc->old_value = NAN;
1069
1070             if(rrdvar_fix_name(rc->name))
1071                 error("Health configuration renamed alarm '%s' to '%s'", value, rc->name);
1072         }
1073         else if(hash == hash_template && !strcasecmp(key, HEALTH_TEMPLATE_KEY)) {
1074             if(rc) {
1075                 if(!rrdcalc_add_alarm_from_config(&localhost, rc))
1076                     rrdcalc_free(&localhost, rc);
1077                 rc = NULL;
1078             }
1079
1080             if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1081                 rrdcalctemplate_free(&localhost, rt);
1082
1083             rt = callocz(1, sizeof(RRDCALCTEMPLATE));
1084             rt->name = strdupz(value);
1085             rt->hash_name = simple_hash(rt->name);
1086             rt->source = health_source_file(line, path, filename);
1087
1088             if(rrdvar_fix_name(rt->name))
1089                 error("Health configuration renamed template '%s' to '%s'", value, rt->name);
1090         }
1091         else if(rc) {
1092             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1093                 if(rc->chart) {
1094                     if(strcmp(rc->chart, value))
1095                         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').",
1096                              line, path, filename, rc->name, key, rc->chart, value, value);
1097
1098                     freez(rc->chart);
1099                 }
1100                 rc->chart = strdupz(value);
1101                 rc->hash_chart = simple_hash(rc->chart);
1102             }
1103             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1104                 health_parse_db_lookup(line, path, filename, value, &rc->group, &rc->after, &rc->before,
1105                                        &rc->update_every,
1106                                        &rc->options, &rc->dimensions);
1107             }
1108             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1109                 if(!health_parse_duration(value, &rc->update_every))
1110                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' cannot parse duration: '%s'.",
1111                          line, path, filename, rc->name, key, value);
1112             }
1113             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1114                 char *e;
1115                 rc->green = strtold(value, &e);
1116                 if(e && *e) {
1117                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1118                          line, path, filename, rc->name, key, e);
1119                 }
1120             }
1121             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1122                 char *e;
1123                 rc->red = strtold(value, &e);
1124                 if(e && *e) {
1125                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1126                          line, path, filename, rc->name, key, e);
1127                 }
1128             }
1129             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1130                 const char *failed_at = NULL;
1131                 int error = 0;
1132                 rc->calculation = expression_parse(value, &failed_at, &error);
1133                 if(!rc->calculation) {
1134                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1135                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1136                 }
1137             }
1138             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1139                 const char *failed_at = NULL;
1140                 int error = 0;
1141                 rc->warning = expression_parse(value, &failed_at, &error);
1142                 if(!rc->warning) {
1143                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1144                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1145                 }
1146             }
1147             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1148                 const char *failed_at = NULL;
1149                 int error = 0;
1150                 rc->critical = expression_parse(value, &failed_at, &error);
1151                 if(!rc->critical) {
1152                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1153                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1154                 }
1155             }
1156             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1157                 if(rc->exec) {
1158                     if(strcmp(rc->exec, value))
1159                         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').",
1160                              line, path, filename, rc->name, key, rc->exec, value, value);
1161
1162                     freez(rc->exec);
1163                 }
1164                 rc->exec = strdupz(value);
1165             }
1166             else {
1167                 error("Health configuration at line %zu of file '%s/%s' for alarm '%s' has unknown key '%s'.",
1168                      line, path, filename, rc->name, key);
1169             }
1170         }
1171         else if(rt) {
1172             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1173                 if(rt->context) {
1174                     if(strcmp(rt->context, value))
1175                         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').",
1176                              line, path, filename, rt->name, key, rt->context, value, value);
1177
1178                     freez(rt->context);
1179                 }
1180                 rt->context = strdupz(value);
1181                 rt->hash_context = simple_hash(rt->context);
1182             }
1183             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1184                 health_parse_db_lookup(line, path, filename, value, &rt->group, &rt->after, &rt->before,
1185                                        &rt->update_every,
1186                                        &rt->options, &rt->dimensions);
1187             }
1188             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1189                 if(!health_parse_duration(value, &rt->update_every))
1190                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' cannot parse duration: '%s'.",
1191                          line, path, filename, rt->name, key, value);
1192             }
1193             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1194                 char *e;
1195                 rt->green = strtold(value, &e);
1196                 if(e && *e) {
1197                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1198                          line, path, filename, rt->name, key, e);
1199                 }
1200             }
1201             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1202                 char *e;
1203                 rt->red = strtold(value, &e);
1204                 if(e && *e) {
1205                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1206                          line, path, filename, rt->name, key, e);
1207                 }
1208             }
1209             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1210                 const char *failed_at = NULL;
1211                 int error = 0;
1212                 rt->calculation = expression_parse(value, &failed_at, &error);
1213                 if(!rt->calculation) {
1214                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1215                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1216                 }
1217             }
1218             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1219                 const char *failed_at = NULL;
1220                 int error = 0;
1221                 rt->warning = expression_parse(value, &failed_at, &error);
1222                 if(!rt->warning) {
1223                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1224                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1225                 }
1226             }
1227             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1228                 const char *failed_at = NULL;
1229                 int error = 0;
1230                 rt->critical = expression_parse(value, &failed_at, &error);
1231                 if(!rt->critical) {
1232                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1233                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1234                 }
1235             }
1236             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1237                 if(rt->exec) {
1238                     if(strcmp(rt->exec, value))
1239                         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').",
1240                              line, path, filename, rt->name, key, rt->exec, value, value);
1241
1242                     freez(rt->exec);
1243                 }
1244                 rt->exec = strdupz(value);
1245             }
1246             else {
1247                 error("Health configuration at line %zu of file '%s/%s' for template '%s' has unknown key '%s'.",
1248                       line, path, filename, rt->name, key);
1249             }
1250         }
1251         else {
1252             error("Health configuration at line %zu of file '%s/%s' has unknown key '%s'. Expected either '" HEALTH_ALARM_KEY "' or '" HEALTH_TEMPLATE_KEY "'.",
1253                   line, path, filename, key);
1254         }
1255     }
1256
1257     if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1258         rrdcalc_free(&localhost, rc);
1259
1260     if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1261         rrdcalctemplate_free(&localhost, rt);
1262
1263     fclose(fp);
1264     return 1;
1265 }
1266
1267 void health_readdir(const char *path) {
1268     size_t pathlen = strlen(path);
1269
1270     debug(D_HEALTH, "Health configuration reading directory '%s'", path);
1271
1272     DIR *dir = opendir(path);
1273     if (!dir) {
1274         error("Health configuration cannot open directory '%s'.", path);
1275         return;
1276     }
1277
1278     struct dirent *de = NULL;
1279     while ((de = readdir(dir))) {
1280         size_t len = strlen(de->d_name);
1281
1282         if(de->d_type == DT_DIR
1283            && (
1284                    (de->d_name[0] == '.' && de->d_name[1] == '\0')
1285                    || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0')
1286            ))
1287             continue;
1288
1289         else if(de->d_type == DT_DIR) {
1290             char *s = mallocz(pathlen + strlen(de->d_name) + 2);
1291             strcpy(s, path);
1292             strcat(s, "/");
1293             strcat(s, de->d_name);
1294             health_readdir(s);
1295             freez(s);
1296             continue;
1297         }
1298
1299         else if((de->d_type == DT_LNK || de->d_type == DT_REG) &&
1300                 len > 5 && !strcmp(&de->d_name[len - 5], ".conf")) {
1301             health_readfile(path, de->d_name);
1302         }
1303     }
1304
1305     closedir(dir);
1306 }
1307
1308 static inline char *health_config_dir(void) {
1309     char buffer[FILENAME_MAX + 1];
1310     snprintfz(buffer, FILENAME_MAX, "%s/health.d", config_get("global", "config directory", CONFIG_DIR));
1311     return config_get("health", "health configuration directory", buffer);
1312 }
1313
1314 void health_init(void) {
1315     debug(D_HEALTH, "Health configuration initializing");
1316
1317     if(!(health_enabled = config_get_boolean("health", "enabled", 1))) {
1318         debug(D_HEALTH, "Health is disabled.");
1319         return;
1320     }
1321
1322     char *path = health_config_dir();
1323
1324     {
1325         char buffer[FILENAME_MAX + 1];
1326         snprintfz(buffer, FILENAME_MAX, "%s/alarm.sh", config_get("global", "plugins directory", PLUGINS_DIR));
1327         health_default_exec = config_get("health", "script to execute on alarm", buffer);
1328     }
1329
1330     long n = config_get_number("health", "in memory max health log entries", (long)health_log.max);
1331     if(n < 2) {
1332         error("Health configuration has invalid max log entries %ld. Using default %u", n, health_log.max);
1333         config_set_number("health", "in memory max health log entries", (long)health_log.max);
1334     }
1335     else health_log.max = (unsigned int)n;
1336
1337     rrdhost_rwlock(&localhost);
1338     health_readdir(path);
1339     rrdhost_unlock(&localhost);
1340 }
1341
1342 // ----------------------------------------------------------------------------
1343 // re-load health configuration
1344
1345 static inline void health_free_all_nolock(RRDHOST *host) {
1346     while(host->templates)
1347         rrdcalctemplate_free(host, host->templates);
1348
1349     while(host->alarms)
1350         rrdcalc_free(host, host->alarms);
1351 }
1352
1353 void health_reload(void) {
1354     if(!health_enabled) {
1355         error("Health reload is requested, but health is not enabled.");
1356         return;
1357     }
1358
1359     char *path = health_config_dir();
1360
1361     rrdhost_rwlock(&localhost);
1362     health_free_all_nolock(&localhost);
1363     rrdhost_unlock(&localhost);
1364
1365     rrdhost_rwlock(&localhost);
1366     health_readdir(path);
1367     rrdhost_unlock(&localhost);
1368
1369     RRDSET *st;
1370     for(st = localhost.rrdset_root; st ; st = st->next) {
1371         rrdhost_rwlock(&localhost);
1372
1373         rrdsetcalc_link_matching(st);
1374         rrdcalctemplate_link_matching(st);
1375
1376         rrdhost_unlock(&localhost);
1377     }
1378 }
1379
1380
1381 // ----------------------------------------------------------------------------
1382 // health main thread and friends
1383
1384 static inline int rrdcalc_isrunnable(RRDCALC *rc, time_t now, time_t *next_run) {
1385     if (unlikely(!rc->rrdset)) {
1386         debug(D_HEALTH, "Health not running alarm '%s.%s'. It is not linked to a chart.", rc->chart?rc->chart:"NOCHART", rc->name);
1387         return 0;
1388     }
1389
1390     if (unlikely(!rc->update_every)) {
1391         debug(D_HEALTH, "Health not running alarm '%s.%s'. It does not have an update frequency", rc->chart?rc->chart:"NOCHART", rc->name);
1392         return 0;
1393     }
1394
1395     if (unlikely(rc->next_update > now)) {
1396         if (*next_run > rc->next_update)
1397             *next_run = rc->next_update;
1398
1399         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));
1400         return 0;
1401     }
1402
1403     return 1;
1404 }
1405
1406 static inline int rrdcalc_value2status(calculated_number n) {
1407     if(isnan(n)) return RRDCALC_STATUS_UNDEFINED;
1408     if(n) return RRDCALC_STATUS_RAISED;
1409     return RRDCALC_STATUS_CLEAR;
1410 }
1411
1412 static inline const char *rrdcalc_status2string(int status) {
1413     switch(status) {
1414         case RRDCALC_STATUS_UNINITIALIZED:
1415             return "UNINITIALIZED";
1416
1417         case RRDCALC_STATUS_UNDEFINED:
1418             return "UNDEFINED";
1419
1420         case RRDCALC_STATUS_CLEAR:
1421             return "CLEAR";
1422
1423         case RRDCALC_STATUS_RAISED:
1424             return "RAISED";
1425
1426         case RRDCALC_STATUS_WARNING:
1427             return "WARNING";
1428
1429         case RRDCALC_STATUS_CRITICAL:
1430             return "CRITICAL";
1431
1432         default:
1433             return "UNKNOWN";
1434     }
1435 }
1436
1437 static inline void health_alarm_execute(ALARM_ENTRY *ae) {
1438     if(ae->old_status == RRDCALC_STATUS_UNINITIALIZED && ae->new_status == RRDCALC_STATUS_CLEAR)
1439         return;
1440
1441     char buffer[FILENAME_MAX + 1];
1442     pid_t command_pid;
1443
1444     const char *exec = ae->exec;
1445     if(!exec) exec = health_default_exec;
1446
1447     snprintfz(buffer, FILENAME_MAX, "exec %s '%s' '%s' '%s' '%s' '%0.0Lf' '%0.0Lf' '%s' '%u'",
1448               exec,
1449               ae->name,
1450               ae->chart?ae->chart:"NOCAHRT",
1451               rrdcalc_status2string(ae->new_status),
1452               rrdcalc_status2string(ae->old_status),
1453               ae->new_value,
1454               ae->old_value,
1455               ae->source?ae->source:"UNKNOWN",
1456               (uint32_t)ae->duration
1457     );
1458
1459     debug(D_HEALTH, "executing command '%s'", buffer);
1460     FILE *fp = mypopen(buffer, &command_pid);
1461     if(!fp) {
1462         error("HEALTH: Cannot popen(\"%s\", \"r\").", buffer);
1463         return;
1464     }
1465     debug(D_HEALTH, "HEALTH reading from command");
1466     char *s = fgets(buffer, FILENAME_MAX, fp);
1467     (void)s;
1468     debug(D_HEALTH, "HEALTH closing command");
1469     mypclose(fp, command_pid);
1470     debug(D_HEALTH, "closed command");
1471 }
1472
1473 static inline void health_process_notifications(ALARM_ENTRY *ae) {
1474     info("Health alarm '%s.%s' = %0.2Lf - changed status from %s to %s",
1475          ae->chart?ae->chart:"NOCHART", ae->name,
1476          ae->new_value,
1477          rrdcalc_status2string(ae->old_status),
1478          rrdcalc_status2string(ae->new_status)
1479     );
1480
1481     health_alarm_execute(ae);
1482 }
1483
1484 static inline void health_alarm_log(time_t when,
1485                 const char *name, const char *chart, const char *exec,
1486                 time_t duration,
1487                 calculated_number old_value, calculated_number new_value,
1488                 int old_status, int new_status,
1489                 const char *source
1490 ) {
1491     ALARM_ENTRY *ae = callocz(1, sizeof(ALARM_ENTRY));
1492     ae->name = strdupz(name);
1493     ae->hash_name = simple_hash(ae->name);
1494
1495     if(chart) {
1496         ae->chart = strdupz(chart);
1497         ae->hash_chart = simple_hash(ae->chart);
1498     }
1499
1500     if(exec) ae->exec = strdupz(exec);
1501     if(source) ae->source = strdupz(source);
1502
1503     ae->id = health_log.nextid++;
1504     ae->when = when;
1505     ae->old_value = old_value;
1506     ae->new_value = new_value;
1507     ae->old_status = old_status;
1508     ae->new_status = new_status;
1509     ae->duration = duration;
1510
1511     // link it
1512     ae->next = health_log.alarms;
1513     health_log.alarms = ae;
1514     health_log.count++;
1515
1516     // match previous alarms
1517     ALARM_ENTRY *t;
1518     for(t = health_log.alarms ; t ; t = t->next) {
1519         if(t != ae &&
1520                 t->hash_name == ae->hash_name &&
1521                 t->hash_chart == ae->hash_chart &&
1522                 !strcmp(t->name, ae->name) &&
1523                 t->chart && ae->chart && !strcmp(t->chart, ae->chart)) {
1524             t->notifications |= HEALTH_ENTRY_NOTIFICATIONS_UPDATED;
1525             t->updated_by = ae;
1526         }
1527     }
1528 }
1529
1530 static inline void health_alarm_log_process(void) {
1531     static uint32_t last_processed = 0;
1532     ALARM_ENTRY *ae;
1533
1534     for(ae = health_log.alarms; ae ;ae = ae->next) {
1535         if(last_processed >= ae->id) break;
1536
1537         if(!(ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_PROCESSED) &&
1538                 !(ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_UPDATED)) {
1539             ae->notifications |= HEALTH_ENTRY_NOTIFICATIONS_PROCESSED;
1540             health_process_notifications(ae);
1541         }
1542     }
1543
1544     if(health_log.alarms)
1545         last_processed = health_log.alarms->id;
1546
1547     if(health_log.count <= health_log.max)
1548         return;
1549
1550     // cleanup excess entries in the log
1551     ALARM_ENTRY *last = NULL;
1552     unsigned int count = health_log.max;
1553     for(ae = health_log.alarms; ae && count ; count--, last = ae, ae = ae->next) ;
1554     if(!ae || !last || last->next != ae) return;
1555     last->next = NULL;
1556
1557     while(ae) {
1558         ALARM_ENTRY *t = ae->next;
1559
1560         freez(ae->chart);
1561         freez(ae->name);
1562         freez(ae->exec);
1563         freez(ae);
1564
1565         ae = t;
1566     }
1567 }
1568
1569 void *health_main(void *ptr) {
1570     (void)ptr;
1571
1572     info("HEALTH thread created with task id %d", gettid());
1573
1574     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1575         error("Cannot set pthread cancel type to DEFERRED.");
1576
1577     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1578         error("Cannot set pthread cancel state to ENABLE.");
1579
1580     int min_run_every = (int)config_get_number("health", "run at least every seconds", 10);
1581     if(min_run_every < 1) min_run_every = 1;
1582
1583     BUFFER *wb = buffer_create(100);
1584
1585     unsigned int loop = 0;
1586     while(health_enabled) {
1587         loop++;
1588         debug(D_HEALTH, "Health monitoring iteration no %u started", loop);
1589
1590         int oldstate, runnable = 0;
1591         time_t now = time(NULL);
1592         time_t next_run = now + min_run_every;
1593         RRDCALC *rc;
1594
1595         if (unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) != 0))
1596             error("Cannot set pthread cancel state to DISABLE.");
1597
1598         rrdhost_rdlock(&localhost);
1599
1600         // the first loop is to lookup values from the db
1601         for (rc = localhost.alarms; rc; rc = rc->next) {
1602             if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
1603                 continue;
1604
1605             runnable++;
1606             rc->old_value = rc->value;
1607
1608             // 1. if there is database lookup, do it
1609             // 2. if there is calculation expression, run it
1610
1611             if (unlikely(RRDCALC_HAS_DB_LOOKUP(rc))) {
1612                 time_t old_db_timestamp = rc->db_timestamp;
1613                 int value_is_null = 0;
1614
1615                 int ret = rrd2value(rc->rrdset, wb, &rc->value,
1616                                     rc->dimensions, 1, rc->after, rc->before, rc->group,
1617                                     rc->options, &rc->db_timestamp, &value_is_null);
1618
1619                 if (unlikely(ret != 200)) {
1620                     // database lookup failed
1621                     rc->value = NAN;
1622
1623                     debug(D_HEALTH, "Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
1624
1625                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_ERROR))) {
1626                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_ERROR;
1627                         error("Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
1628                     }
1629                 }
1630                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_ERROR))
1631                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_ERROR;
1632
1633                 if (unlikely(old_db_timestamp == rc->db_timestamp)) {
1634                     // database is stale
1635
1636                     debug(D_HEALTH, "Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
1637
1638                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_STALE))) {
1639                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_STALE;
1640                         error("Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
1641                     }
1642                 }
1643                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_STALE))
1644                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_STALE;
1645
1646                 if (unlikely(value_is_null)) {
1647                     // collected value is null
1648
1649                     rc->value = NAN;
1650
1651                     debug(D_HEALTH, "Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
1652                           rc->chart?rc->chart:"NOCHART", rc->name);
1653
1654                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_NAN))) {
1655                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_NAN;
1656                         error("Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
1657                               rc->chart?rc->chart:"NOCHART", rc->name);
1658                     }
1659                 }
1660                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_NAN))
1661                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_NAN;
1662
1663                 debug(D_HEALTH, "Health alarm '%s.%s': database lookup gave value "
1664                         CALCULATED_NUMBER_FORMAT, rc->chart?rc->chart:"NOCHART", rc->name, rc->value);
1665             }
1666
1667             if(unlikely(rc->calculation)) {
1668                 if (unlikely(!expression_evaluate(rc->calculation))) {
1669                     // calculation failed
1670
1671                     rc->value = NAN;
1672
1673                     debug(D_HEALTH, "Health alarm '%s.%s': failed to evaluate calculation with error: %s",
1674                           rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
1675
1676                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_CALC_ERROR))) {
1677                         rc->rrdcalc_options |= RRDCALC_OPTION_CALC_ERROR;
1678                         error("Health alarm '%s.%s': failed to evaluate calculation with error: %s",
1679                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
1680                     }
1681                 }
1682                 else {
1683                     if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_CALC_ERROR))
1684                         rc->rrdcalc_options &= ~RRDCALC_OPTION_CALC_ERROR;
1685
1686                     debug(D_HEALTH, "Health alarm '%s.%s': calculation expression gave value "
1687                             CALCULATED_NUMBER_FORMAT
1688                             ": %s (source: %s)",
1689                           rc->chart?rc->chart:"NOCHART", rc->name,
1690                           rc->calculation->result,
1691                           buffer_tostring(rc->calculation->error_msg),
1692                           rc->source
1693                     );
1694
1695                     rc->value = rc->calculation->result;
1696                 }
1697             }
1698         }
1699         rrdhost_unlock(&localhost);
1700
1701         if (runnable) {
1702             rrdhost_rdlock(&localhost);
1703
1704             for (rc = localhost.alarms; rc; rc = rc->next) {
1705                 if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
1706                     continue;
1707
1708                 int warning_status  = RRDCALC_STATUS_UNDEFINED;
1709                 int critical_status = RRDCALC_STATUS_UNDEFINED;
1710
1711                 if(unlikely(rc->warning)) {
1712                     if(unlikely(!expression_evaluate(rc->warning))) {
1713                         // calculation failed
1714
1715                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression failed with error: %s",
1716                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
1717
1718                         if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_WARN_ERROR))) {
1719                             rc->rrdcalc_options |= RRDCALC_OPTION_WARN_ERROR;
1720                             error("Health alarm '%s.%s': warning expression failed with error: %s",
1721                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
1722                         }
1723                     }
1724                     else {
1725                         if(unlikely(rc->rrdcalc_options & RRDCALC_OPTION_WARN_ERROR))
1726                             rc->rrdcalc_options &= ~RRDCALC_OPTION_WARN_ERROR;
1727
1728                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression gave value "
1729                                 CALCULATED_NUMBER_FORMAT
1730                                 ": %s (source: %s)",
1731                               rc->chart?rc->chart:"NOCHART", rc->name,
1732                               rc->warning->result,
1733                               buffer_tostring(rc->warning->error_msg),
1734                               rc->source
1735                         );
1736
1737                         warning_status = rrdcalc_value2status(rc->warning->result);
1738                     }
1739                 }
1740
1741                 if(unlikely(rc->critical)) {
1742                     if(unlikely(!expression_evaluate(rc->critical))) {
1743                         // calculation failed
1744
1745                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression failed with error: %s",
1746                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
1747
1748                         if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_CRIT_ERROR))) {
1749                             rc->rrdcalc_options |= RRDCALC_OPTION_CRIT_ERROR;
1750                             error("Health alarm '%s.%s': critical expression failed with error: %s",
1751                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
1752                         }
1753                     }
1754                     else {
1755                         if(unlikely(rc->rrdcalc_options & RRDCALC_OPTION_CRIT_ERROR))
1756                             rc->rrdcalc_options &= ~RRDCALC_OPTION_CRIT_ERROR;
1757
1758                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression gave value "
1759                                 CALCULATED_NUMBER_FORMAT
1760                                 ": %s (source: %s)",
1761                               rc->chart?rc->chart:"NOCHART", rc->name,
1762                               rc->critical->result,
1763                               buffer_tostring(rc->critical->error_msg),
1764                               rc->source
1765                         );
1766
1767                         critical_status = rrdcalc_value2status(rc->critical->result);
1768                     }
1769                 }
1770
1771                 int status = RRDCALC_STATUS_UNDEFINED;
1772
1773                 switch(warning_status) {
1774                     case RRDCALC_STATUS_CLEAR:
1775                         status = RRDCALC_STATUS_CLEAR;
1776                         break;
1777
1778                     case RRDCALC_STATUS_RAISED:
1779                         status = RRDCALC_STATUS_WARNING;
1780                         break;
1781
1782                     default:
1783                         break;
1784                 }
1785
1786                 switch(critical_status) {
1787                     case RRDCALC_STATUS_CLEAR:
1788                         if(status == RRDCALC_STATUS_UNDEFINED)
1789                             status = RRDCALC_STATUS_CLEAR;
1790                         break;
1791
1792                     case RRDCALC_STATUS_RAISED:
1793                         status = RRDCALC_STATUS_CRITICAL;
1794                         break;
1795
1796                     default:
1797                         break;
1798                 }
1799
1800                 if(status != rc->status) {
1801                     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);
1802                     rc->last_status_change = now;
1803                     rc->status = status;
1804                 }
1805
1806                 rc->last_updated = now;
1807                 rc->next_update = now + rc->update_every;
1808
1809                 if (next_run > rc->next_update)
1810                     next_run = rc->next_update;
1811             }
1812
1813             rrdhost_unlock(&localhost);
1814         }
1815
1816         if (unlikely(pthread_setcancelstate(oldstate, NULL) != 0))
1817             error("Cannot set pthread cancel state to RESTORE (%d).", oldstate);
1818
1819         // execute notifications
1820         // and cleanup
1821         health_alarm_log_process();
1822
1823         now = time(NULL);
1824         if(now < next_run) {
1825             debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration in %d secs",
1826                   loop, (int) (next_run - now));
1827             sleep_usec(1000000 * (unsigned long long) (next_run - now));
1828         }
1829         else {
1830             debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration now", loop);
1831         }
1832     }
1833
1834     buffer_free(wb);
1835
1836     info("HEALTH thread exiting");
1837     pthread_exit(NULL);
1838     return NULL;
1839 }