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