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