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