]> arthur.barton.de Git - netdata.git/blob - src/health.c
updated disk alarms
[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->alarms; 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->alarms == rc)
474         st->alarms = 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->alarms; 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->alarms;
531     host->alarms = 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->alarms)
631         host->alarms = rc->next;
632
633     else if(host->alarms) {
634         RRDCALC *t, *last = host->alarms;
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     expression_free(rc->calculation);
646     expression_free(rc->warning);
647     expression_free(rc->critical);
648
649     freez(rc->source);
650     freez(rc->name);
651     freez(rc->chart);
652     freez(rc->dimensions);
653     freez(rc->exec);
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     expression_free(rt->calculation);
706     expression_free(rt->warning);
707     expression_free(rt->critical);
708
709     freez(rt->dimensions);
710     freez(rt->context);
711     freez(rt->name);
712     freez(rt->exec);
713     freez(rt->source);
714     freez(rt);
715 }
716
717 // ----------------------------------------------------------------------------
718 // load health configuration
719
720 #define HEALTH_CONF_MAX_LINE 4096
721
722 #define HEALTH_ALARM_KEY "alarm"
723 #define HEALTH_TEMPLATE_KEY "template"
724 #define HEALTH_ON_KEY "on"
725 #define HEALTH_LOOKUP_KEY "lookup"
726 #define HEALTH_CALC_KEY "calc"
727 #define HEALTH_EVERY_KEY "every"
728 #define HEALTH_GREEN_KEY "green"
729 #define HEALTH_RED_KEY "red"
730 #define HEALTH_WARN_KEY "warn"
731 #define HEALTH_CRIT_KEY "crit"
732 #define HEALTH_EXEC_KEY "exec"
733
734 static inline int rrdcalc_add_alarm_from_config(RRDHOST *host, RRDCALC *rc) {
735     {
736         char fullname[RRDVAR_MAX_LENGTH + 1];
737         uint32_t hash = rrdcalc_fullname(fullname, RRDVAR_MAX_LENGTH + 1, rc->chart, rc->name);
738
739         if (rrdcalc_exists(host, fullname, hash))
740             return 0;
741     }
742
743     if(!rc->chart) {
744         error("Health configuration for alarm '%s' does not have a chart", rc->name);
745         return 0;
746     }
747
748     if(!RRDCALC_HAS_DB_LOOKUP(rc) && !rc->warning && !rc->critical) {
749         error("Health configuration for alarm '%s.%s' is useless (no calculation, no warning and no critical evaluation)", rc->chart?rc->chart:"NOCHART", rc->name);
750         return 0;
751     }
752
753     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",
754           rc->chart?rc->chart:"NOCHART",
755           rc->name,
756           (rc->exec)?rc->exec:"DEFAULT",
757           rc->green,
758           rc->red,
759           rc->group,
760           rc->after,
761           rc->before,
762           rc->options,
763           (rc->dimensions)?rc->dimensions:"NONE",
764           rc->update_every,
765           (rc->calculation)?rc->calculation->parsed_as:"NONE",
766           (rc->warning)?rc->warning->parsed_as:"NONE",
767           (rc->critical)?rc->critical->parsed_as:"NONE",
768           rc->source
769     );
770
771     rrdcalc_create_part2(host, rc);
772     return 1;
773 }
774
775 static inline int rrdcalctemplate_add_template_from_config(RRDHOST *host, RRDCALCTEMPLATE *rt) {
776     if(!rt->context) {
777         error("Health configuration for template '%s' does not have a context", rt->name);
778         return 0;
779     }
780
781     if(!RRDCALCTEMPLATE_HAS_CALCULATION(rt) && !rt->warning && !rt->critical) {
782         error("Health configuration for template '%s' is useless (no calculation, no warning and no critical evaluation)", rt->name);
783         return 0;
784     }
785
786     RRDCALCTEMPLATE *t;
787     for (t = host->templates; t ; t = t->next) {
788         if(t->hash_name == rt->hash_name && !strcmp(t->name, rt->name)) {
789             error("Health configuration template '%s' already exists for host '%s'.", rt->name, host->hostname);
790             return 0;
791         }
792     }
793
794     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'",
795           rt->name,
796           (rt->context)?rt->context:"NONE",
797           (rt->exec)?rt->exec:"DEFAULT",
798           rt->green,
799           rt->red,
800           rt->group,
801           rt->after,
802           rt->before,
803           rt->options,
804           (rt->dimensions)?rt->dimensions:"NONE",
805           rt->update_every,
806           (rt->calculation)?rt->calculation->parsed_as:"NONE",
807           (rt->warning)?rt->warning->parsed_as:"NONE",
808           (rt->critical)?rt->critical->parsed_as:"NONE",
809           rt->source
810     );
811
812     rt->next = host->templates;
813     host->templates = rt;
814     return 1;
815 }
816
817 static inline int health_parse_duration(char *string, int *result) {
818     // make sure it is a number
819     if(!*string || !(isdigit(*string) || *string == '+' || *string == '-')) {
820         *result = 0;
821         return 0;
822     }
823
824     char *e = NULL;
825     calculated_number n = strtold(string, &e);
826     if(e && *e) {
827         switch (*e) {
828             case 'Y':
829                 *result = (int) (n * 86400 * 365);
830                 break;
831             case 'M':
832                 *result = (int) (n * 86400 * 30);
833                 break;
834             case 'w':
835                 *result = (int) (n * 86400 * 7);
836                 break;
837             case 'd':
838                 *result = (int) (n * 86400);
839                 break;
840             case 'h':
841                 *result = (int) (n * 3600);
842                 break;
843             case 'm':
844                 *result = (int) (n * 60);
845                 break;
846
847             default:
848             case 's':
849                 *result = (int) (n);
850                 break;
851         }
852     }
853     else
854        *result = (int)(n);
855
856     return 1;
857 }
858
859 static inline int health_parse_db_lookup(
860         size_t line, const char *path, const char *file, char *string,
861         int *group_method, int *after, int *before, int *every,
862         uint32_t *options, char **dimensions
863 ) {
864     debug(D_HEALTH, "Health configuration parsing database lookup %zu@%s/%s: %s", line, path, file, string);
865
866     if(*dimensions) freez(*dimensions);
867     *dimensions = NULL;
868     *after = 0;
869     *before = 0;
870     *every = 0;
871     *options = 0;
872
873     char *s = string, *key;
874
875     // first is the group method
876     key = s;
877     while(*s && !isspace(*s)) s++;
878     while(*s && isspace(*s)) *s++ = '\0';
879     if(!*s) {
880         error("Health configuration invalid chart calculation at line %zu of file '%s/%s': expected group method followed by the 'after' time, but got '%s'",
881               line, path, file, key);
882         return 0;
883     }
884
885     if((*group_method = web_client_api_request_v1_data_group(key, -1)) == -1) {
886         error("Health configuration at line %zu of file '%s/%s': invalid group method '%s'",
887               line, path, file, key);
888         return 0;
889     }
890
891     // then is the 'after' time
892     key = s;
893     while(*s && !isspace(*s)) s++;
894     while(*s && isspace(*s)) *s++ = '\0';
895
896     if(!health_parse_duration(key, after)) {
897         error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' after group method",
898               line, path, file, key);
899         return 0;
900     }
901
902     // sane defaults
903     *every = abs(*after);
904
905     // now we may have optional parameters
906     while(*s) {
907         key = s;
908         while(*s && !isspace(*s)) s++;
909         while(*s && isspace(*s)) *s++ = '\0';
910         if(!*key) break;
911
912         if(!strcasecmp(key, "at")) {
913             char *value = s;
914             while(*s && !isspace(*s)) s++;
915             while(*s && isspace(*s)) *s++ = '\0';
916
917             if (!health_parse_duration(value, before)) {
918                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
919                       line, path, file, value, key);
920             }
921         }
922         else if(!strcasecmp(key, HEALTH_EVERY_KEY)) {
923             char *value = s;
924             while(*s && !isspace(*s)) s++;
925             while(*s && isspace(*s)) *s++ = '\0';
926
927             if (!health_parse_duration(value, every)) {
928                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
929                       line, path, file, value, key);
930             }
931         }
932         else if(!strcasecmp(key, "absolute") || !strcasecmp(key, "abs") || !strcasecmp(key, "absolute_sum")) {
933             *options |= RRDR_OPTION_ABSOLUTE;
934         }
935         else if(!strcasecmp(key, "min2max")) {
936             *options |= RRDR_OPTION_MIN2MAX;
937         }
938         else if(!strcasecmp(key, "null2zero")) {
939             *options |= RRDR_OPTION_NULL2ZERO;
940         }
941         else if(!strcasecmp(key, "percentage")) {
942             *options |= RRDR_OPTION_PERCENTAGE;
943         }
944         else if(!strcasecmp(key, "unaligned")) {
945             *options |= RRDR_OPTION_NOT_ALIGNED;
946         }
947         else if(!strcasecmp(key, "of")) {
948             if(*s && strcasecmp(s, "all"))
949                *dimensions = strdupz(s);
950             break;
951         }
952         else {
953             error("Health configuration at line %zu of file '%s/%s': unknown keyword '%s'",
954                   line, path, file, key);
955         }
956     }
957
958     return 1;
959 }
960
961 static inline char *health_source_file(int line, const char *path, const char *filename) {
962     char buffer[FILENAME_MAX + 1];
963     snprintfz(buffer, FILENAME_MAX, "%d@%s/%s", line, path, filename);
964     return strdupz(buffer);
965 }
966
967 int health_readfile(const char *path, const char *filename) {
968     debug(D_HEALTH, "Health configuration reading file '%s/%s'", path, filename);
969
970     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;
971     char buffer[HEALTH_CONF_MAX_LINE + 1];
972
973     if(unlikely(!hash_alarm)) {
974         hash_alarm = simple_uhash(HEALTH_ALARM_KEY);
975         hash_template = simple_uhash(HEALTH_TEMPLATE_KEY);
976         hash_on = simple_uhash(HEALTH_ON_KEY);
977         hash_calc = simple_uhash(HEALTH_CALC_KEY);
978         hash_lookup = simple_uhash(HEALTH_LOOKUP_KEY);
979         hash_green = simple_uhash(HEALTH_GREEN_KEY);
980         hash_red = simple_uhash(HEALTH_RED_KEY);
981         hash_warn = simple_uhash(HEALTH_WARN_KEY);
982         hash_crit = simple_uhash(HEALTH_CRIT_KEY);
983         hash_exec = simple_uhash(HEALTH_EXEC_KEY);
984         hash_every = simple_uhash(HEALTH_EVERY_KEY);
985     }
986
987     snprintfz(buffer, HEALTH_CONF_MAX_LINE, "%s/%s", path, filename);
988     FILE *fp = fopen(buffer, "r");
989     if(!fp) {
990         error("Health configuration cannot read file '%s'.", buffer);
991         return 0;
992     }
993
994     RRDCALC *rc = NULL;
995     RRDCALCTEMPLATE *rt = NULL;
996
997     size_t line = 0, append = 0;
998     char *s;
999     while((s = fgets(&buffer[append], (int)(HEALTH_CONF_MAX_LINE - append), fp)) || append) {
1000         int stop_appending = !s;
1001         line++;
1002         // info("Line %zu of file '%s/%s': '%s'", line, path, filename, s);
1003         s = trim(buffer);
1004         if(!s) continue;
1005         // info("Trimmed line %zu of file '%s/%s': '%s'", line, path, filename, s);
1006
1007         append = strlen(s);
1008         if(!stop_appending && s[append - 1] == '\\') {
1009             s[append - 1] = ' ';
1010             append = &s[append] - buffer;
1011             if(append < HEALTH_CONF_MAX_LINE)
1012                 continue;
1013             continue;
1014         }
1015         append = 0;
1016
1017         char *key = s;
1018         while(*s && *s != ':') s++;
1019         if(!*s) {
1020             error("Health configuration has invalid line %zu of file '%s/%s'. It does not contain a ':'. Ignoring it.", line, path, filename);
1021             continue;
1022         }
1023         *s = '\0';
1024         s++;
1025
1026         char *value = s;
1027         key = trim(key);
1028         value = trim(value);
1029
1030         if(!key) {
1031             error("Health configuration has invalid line %zu of file '%s/%s'. Keyword is empty. Ignoring it.", line, path, filename);
1032             continue;
1033         }
1034
1035         if(!value) {
1036             error("Health configuration has invalid line %zu of file '%s/%s'. value is empty. Ignoring it.", line, path, filename);
1037             continue;
1038         }
1039
1040         // info("Health file '%s/%s', key '%s', value '%s'", path, filename, key, value);
1041         uint32_t hash = simple_uhash(key);
1042
1043         if(hash == hash_alarm && !strcasecmp(key, HEALTH_ALARM_KEY)) {
1044             if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1045                 rrdcalc_free(&localhost, rc);
1046
1047             if(rt) {
1048                 if (!rrdcalctemplate_add_template_from_config(&localhost, rt))
1049                     rrdcalctemplate_free(&localhost, rt);
1050                 rt = NULL;
1051             }
1052
1053             rc = callocz(1, sizeof(RRDCALC));
1054             rc->name = strdupz(value);
1055             rc->hash = simple_hash(rc->name);
1056             rc->source = health_source_file(line, path, filename);
1057
1058             if(rrdvar_fix_name(rc->name))
1059                 error("Health configuration renamed alarm '%s' to '%s'", value, rc->name);
1060         }
1061         else if(hash == hash_template && !strcasecmp(key, HEALTH_TEMPLATE_KEY)) {
1062             if(rc) {
1063                 if(!rrdcalc_add_alarm_from_config(&localhost, rc))
1064                     rrdcalc_free(&localhost, rc);
1065                 rc = NULL;
1066             }
1067
1068             if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1069                 rrdcalctemplate_free(&localhost, rt);
1070
1071             rt = callocz(1, sizeof(RRDCALCTEMPLATE));
1072             rt->name = strdupz(value);
1073             rt->hash_name = simple_hash(rt->name);
1074             rt->source = health_source_file(line, path, filename);
1075
1076             if(rrdvar_fix_name(rt->name))
1077                 error("Health configuration renamed template '%s' to '%s'", value, rt->name);
1078         }
1079         else if(rc) {
1080             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1081                 if(rc->chart) {
1082                     if(strcmp(rc->chart, value))
1083                         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').",
1084                              line, path, filename, rc->name, key, rc->chart, value, value);
1085
1086                     freez(rc->chart);
1087                 }
1088                 rc->chart = strdupz(value);
1089                 rc->hash_chart = simple_hash(rc->chart);
1090             }
1091             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1092                 health_parse_db_lookup(line, path, filename, value, &rc->group, &rc->after, &rc->before,
1093                                        &rc->update_every,
1094                                        &rc->options, &rc->dimensions);
1095             }
1096             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1097                 if(!health_parse_duration(value, &rc->update_every))
1098                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' cannot parse duration: '%s'.",
1099                          line, path, filename, rc->name, key, value);
1100             }
1101             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1102                 char *e;
1103                 rc->green = strtold(value, &e);
1104                 if(e && *e) {
1105                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1106                          line, path, filename, rc->name, key, e);
1107                 }
1108             }
1109             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1110                 char *e;
1111                 rc->red = strtold(value, &e);
1112                 if(e && *e) {
1113                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1114                          line, path, filename, rc->name, key, e);
1115                 }
1116             }
1117             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1118                 const char *failed_at = NULL;
1119                 int error = 0;
1120                 rc->calculation = expression_parse(value, &failed_at, &error);
1121                 if(!rc->calculation) {
1122                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1123                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1124                 }
1125             }
1126             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1127                 const char *failed_at = NULL;
1128                 int error = 0;
1129                 rc->warning = expression_parse(value, &failed_at, &error);
1130                 if(!rc->warning) {
1131                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1132                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1133                 }
1134             }
1135             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1136                 const char *failed_at = NULL;
1137                 int error = 0;
1138                 rc->critical = expression_parse(value, &failed_at, &error);
1139                 if(!rc->critical) {
1140                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1141                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1142                 }
1143             }
1144             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1145                 if(rc->exec) {
1146                     if(strcmp(rc->exec, value))
1147                         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').",
1148                              line, path, filename, rc->name, key, rc->exec, value, value);
1149
1150                     freez(rc->exec);
1151                 }
1152                 rc->exec = strdupz(value);
1153             }
1154             else {
1155                 error("Health configuration at line %zu of file '%s/%s' for alarm '%s' has unknown key '%s'.",
1156                      line, path, filename, rc->name, key);
1157             }
1158         }
1159         else if(rt) {
1160             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1161                 if(rt->context) {
1162                     if(strcmp(rt->context, value))
1163                         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').",
1164                              line, path, filename, rt->name, key, rt->context, value, value);
1165
1166                     freez(rt->context);
1167                 }
1168                 rt->context = strdupz(value);
1169                 rt->hash_context = simple_hash(rt->context);
1170             }
1171             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1172                 health_parse_db_lookup(line, path, filename, value, &rt->group, &rt->after, &rt->before,
1173                                        &rt->update_every,
1174                                        &rt->options, &rt->dimensions);
1175             }
1176             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1177                 if(!health_parse_duration(value, &rt->update_every))
1178                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' cannot parse duration: '%s'.",
1179                          line, path, filename, rt->name, key, value);
1180             }
1181             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1182                 char *e;
1183                 rt->green = strtold(value, &e);
1184                 if(e && *e) {
1185                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1186                          line, path, filename, rt->name, key, e);
1187                 }
1188             }
1189             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1190                 char *e;
1191                 rt->red = strtold(value, &e);
1192                 if(e && *e) {
1193                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1194                          line, path, filename, rt->name, key, e);
1195                 }
1196             }
1197             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1198                 const char *failed_at = NULL;
1199                 int error = 0;
1200                 rt->calculation = expression_parse(value, &failed_at, &error);
1201                 if(!rt->calculation) {
1202                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1203                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1204                 }
1205             }
1206             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1207                 const char *failed_at = NULL;
1208                 int error = 0;
1209                 rt->warning = expression_parse(value, &failed_at, &error);
1210                 if(!rt->warning) {
1211                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1212                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1213                 }
1214             }
1215             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1216                 const char *failed_at = NULL;
1217                 int error = 0;
1218                 rt->critical = expression_parse(value, &failed_at, &error);
1219                 if(!rt->critical) {
1220                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1221                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1222                 }
1223             }
1224             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1225                 if(rt->exec) {
1226                     if(strcmp(rt->exec, value))
1227                         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').",
1228                              line, path, filename, rt->name, key, rt->exec, value, value);
1229
1230                     freez(rt->exec);
1231                 }
1232                 rt->exec = strdupz(value);
1233             }
1234             else {
1235                 error("Health configuration at line %zu of file '%s/%s' for template '%s' has unknown key '%s'.",
1236                       line, path, filename, rt->name, key);
1237             }
1238         }
1239         else {
1240             error("Health configuration at line %zu of file '%s/%s' has unknown key '%s'. Expected either '" HEALTH_ALARM_KEY "' or '" HEALTH_TEMPLATE_KEY "'.",
1241                   line, path, filename, key);
1242         }
1243     }
1244
1245     if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1246         rrdcalc_free(&localhost, rc);
1247
1248     if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1249         rrdcalctemplate_free(&localhost, rt);
1250
1251     fclose(fp);
1252     return 1;
1253 }
1254
1255 void health_readdir(const char *path) {
1256     size_t pathlen = strlen(path);
1257
1258     debug(D_HEALTH, "Health configuration reading directory '%s'", path);
1259
1260     DIR *dir = opendir(path);
1261     if (!dir) {
1262         error("Health configuration cannot open directory '%s'.", path);
1263         return;
1264     }
1265
1266     struct dirent *de = NULL;
1267     while ((de = readdir(dir))) {
1268         size_t len = strlen(de->d_name);
1269
1270         if(de->d_type == DT_DIR
1271            && (
1272                    (de->d_name[0] == '.' && de->d_name[1] == '\0')
1273                    || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0')
1274            ))
1275             continue;
1276
1277         else if(de->d_type == DT_DIR) {
1278             char *s = mallocz(pathlen + strlen(de->d_name) + 2);
1279             strcpy(s, path);
1280             strcat(s, "/");
1281             strcat(s, de->d_name);
1282             health_readdir(s);
1283             freez(s);
1284             continue;
1285         }
1286
1287         else if((de->d_type == DT_LNK || de->d_type == DT_REG) &&
1288                 len > 5 && !strcmp(&de->d_name[len - 5], ".conf")) {
1289             health_readfile(path, de->d_name);
1290         }
1291     }
1292
1293     closedir(dir);
1294 }
1295
1296 static inline char *health_config_dir(void) {
1297     char buffer[FILENAME_MAX + 1];
1298     snprintfz(buffer, FILENAME_MAX, "%s/health.d", config_get("global", "config directory", CONFIG_DIR));
1299     return config_get("health", "health configuration directory", buffer);
1300 }
1301
1302 void health_init(void) {
1303     debug(D_HEALTH, "Health configuration initializing");
1304
1305     if(!(health_enabled = config_get_boolean("health", "enabled", 1))) {
1306         debug(D_HEALTH, "Health is disabled.");
1307         return;
1308     }
1309
1310     char *path = health_config_dir();
1311
1312     {
1313         char buffer[FILENAME_MAX + 1];
1314         snprintfz(buffer, FILENAME_MAX, "%s/alarm.sh", config_get("global", "plugins directory", PLUGINS_DIR));
1315         health_default_exec = config_get("health", "script to execute on alarm", buffer);
1316     }
1317
1318     rrdhost_rwlock(&localhost);
1319     health_readdir(path);
1320     rrdhost_unlock(&localhost);
1321 }
1322
1323 // ----------------------------------------------------------------------------
1324 // re-load health configuration
1325
1326 static inline void health_free_all_nolock(RRDHOST *host) {
1327     while(host->templates)
1328         rrdcalctemplate_free(host, host->templates);
1329
1330     while(host->alarms)
1331         rrdcalc_free(host, host->alarms);
1332 }
1333
1334 void health_reload(void) {
1335     if(!health_enabled) {
1336         error("Health reload is requested, but health is not enabled.");
1337         return;
1338     }
1339
1340     char *path = health_config_dir();
1341
1342     rrdhost_rwlock(&localhost);
1343     health_free_all_nolock(&localhost);
1344     rrdhost_unlock(&localhost);
1345
1346     rrdhost_rwlock(&localhost);
1347     health_readdir(path);
1348     rrdhost_unlock(&localhost);
1349
1350     RRDSET *st;
1351     for(st = localhost.rrdset_root; st ; st = st->next) {
1352         rrdhost_rwlock(&localhost);
1353
1354         rrdsetcalc_link_matching(st);
1355         rrdcalctemplate_link_matching(st);
1356
1357         rrdhost_unlock(&localhost);
1358     }
1359 }
1360
1361
1362 // ----------------------------------------------------------------------------
1363 // health main thread and friends
1364
1365 static inline int rrdcalc_isrunnable(RRDCALC *rc, time_t now, time_t *next_run) {
1366     if (unlikely(!rc->rrdset)) {
1367         debug(D_HEALTH, "Health not running alarm '%s.%s'. It is not linked to a chart.", rc->chart?rc->chart:"NOCHART", rc->name);
1368         return 0;
1369     }
1370
1371     if (unlikely(!rc->update_every)) {
1372         debug(D_HEALTH, "Health not running alarm '%s.%s'. It does not have an update frequency", rc->chart?rc->chart:"NOCHART", rc->name);
1373         return 0;
1374     }
1375
1376     if (unlikely(rc->next_update > now)) {
1377         if (*next_run > rc->next_update)
1378             *next_run = rc->next_update;
1379
1380         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));
1381         return 0;
1382     }
1383
1384     return 1;
1385 }
1386
1387 static inline int rrdcalc_value2status(calculated_number n) {
1388     if(isnan(n)) return RRDCALC_STATUS_UNDEFINED;
1389     if(n) return RRDCALC_STATUS_RAISED;
1390     return RRDCALC_STATUS_OFF;
1391 }
1392
1393 static inline const char *rrdcalc_status2string(int status) {
1394     switch(status) {
1395         case RRDCALC_STATUS_UNINITIALIZED:
1396             return "UNINITIALIZED";
1397
1398         case RRDCALC_STATUS_UNDEFINED:
1399             return "UNDEFINED";
1400
1401         case RRDCALC_STATUS_RAISED:
1402             return "RAISED";
1403
1404         case RRDCALC_STATUS_OFF:
1405             return "OFF";
1406
1407         default:
1408             return "UNKNOWN";
1409     }
1410 }
1411
1412 void rrdcalc_check_critical_event(RRDCALC *rc) {
1413     calculated_number n = rc->critical->result;
1414
1415     int old_status = rc->critical_status;
1416     int new_status = rrdcalc_value2status(n);
1417
1418     if(new_status != old_status) {
1419         info("Health alarm '%s.%s' = %0.2Lf - CRITICAL condition changed status from %s to %s",
1420              rc->chart?rc->chart:"NOCHART", rc->name,
1421              rc->value,
1422              rrdcalc_status2string(old_status),
1423              rrdcalc_status2string(new_status)
1424         );
1425
1426         rc->critical_status = new_status;
1427     }
1428 }
1429
1430 void rrdcalc_check_warning_event(RRDCALC *rc) {
1431     calculated_number n = rc->warning->result;
1432
1433     int old_status = rc->warning_status;
1434     int new_status = rrdcalc_value2status(n);
1435
1436     if(new_status != old_status) {
1437         info("Health alarm '%s.%s' = %0.2Lf - WARNING condition changed status from %s to %s",
1438              rc->chart?rc->chart:"NOCHART", rc->name,
1439              rc->value,
1440              rrdcalc_status2string(old_status),
1441              rrdcalc_status2string(new_status)
1442         );
1443
1444         rc->warning_status = new_status;
1445     }
1446 }
1447
1448 void *health_main(void *ptr) {
1449     (void)ptr;
1450
1451     info("HEALTH thread created with task id %d", gettid());
1452
1453     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1454         error("Cannot set pthread cancel type to DEFERRED.");
1455
1456     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1457         error("Cannot set pthread cancel state to ENABLE.");
1458
1459     int min_run_every = (int)config_get_number("health", "run at least every seconds", 10);
1460     if(min_run_every < 1) min_run_every = 1;
1461
1462     BUFFER *wb = buffer_create(100);
1463
1464     unsigned int loop = 0;
1465     while(health_enabled) {
1466         loop++;
1467         debug(D_HEALTH, "Health monitoring iteration no %u started", loop);
1468
1469         int oldstate, runnable = 0;
1470         time_t now = time(NULL);
1471         time_t next_run = now + min_run_every;
1472         RRDCALC *rc;
1473
1474         if (unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) != 0))
1475             error("Cannot set pthread cancel state to DISABLE.");
1476
1477         rrdhost_rdlock(&localhost);
1478
1479         // the first loop is to lookup values from the db
1480         for (rc = localhost.alarms; rc; rc = rc->next) {
1481             if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
1482                 continue;
1483
1484             runnable++;
1485
1486             // 1. if there is database lookup, do it
1487             // 2. if there is calculation expression, run it
1488
1489             if (unlikely(RRDCALC_HAS_DB_LOOKUP(rc))) {
1490                 time_t old_db_timestamp = rc->db_timestamp;
1491                 int value_is_null = 0;
1492
1493                 int ret = rrd2value(rc->rrdset, wb, &rc->value,
1494                                     rc->dimensions, 1, rc->after, rc->before, rc->group,
1495                                     rc->options, &rc->db_timestamp, &value_is_null);
1496
1497                 if (unlikely(ret != 200)) {
1498                     // database lookup failed
1499                     rc->value = NAN;
1500
1501                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_ERROR))) {
1502                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_ERROR;
1503                         error("Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
1504                     }
1505                 }
1506                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_ERROR))
1507                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_ERROR;
1508
1509                 if (unlikely(old_db_timestamp == rc->db_timestamp)) {
1510                     // database is stale
1511
1512                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_STALE))) {
1513                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_STALE;
1514                         error("Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
1515                     }
1516                 }
1517                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_STALE))
1518                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_STALE;
1519
1520                 if (unlikely(value_is_null)) {
1521                     // collected value is null
1522
1523                     rc->value = NAN;
1524
1525                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_DB_NAN))) {
1526                         rc->rrdcalc_options |= RRDCALC_OPTION_DB_NAN;
1527                         error("Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
1528                               rc->chart?rc->chart:"NOCHART", rc->name);
1529                     }
1530                 }
1531                 else if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_DB_NAN))
1532                     rc->rrdcalc_options &= ~RRDCALC_OPTION_DB_NAN;
1533
1534                 debug(D_HEALTH, "Health alarm '%s.%s': database lookup gave value "
1535                         CALCULATED_NUMBER_FORMAT, rc->chart?rc->chart:"NOCHART", rc->name, rc->value);
1536             }
1537
1538             if(unlikely(rc->calculation)) {
1539                 if (unlikely(!expression_evaluate(rc->calculation))) {
1540                     // calculation failed
1541
1542                     rc->value = NAN;
1543
1544                     if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_CALC_ERROR))) {
1545                         rc->rrdcalc_options |= RRDCALC_OPTION_CALC_ERROR;
1546                         error("Health alarm '%s.%s': failed to evaluate calculation with error: %s",
1547                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
1548                     }
1549                 }
1550                 else {
1551                     if (unlikely(rc->rrdcalc_options & RRDCALC_OPTION_CALC_ERROR))
1552                         rc->rrdcalc_options &= ~RRDCALC_OPTION_CALC_ERROR;
1553
1554                     debug(D_HEALTH, "Health alarm '%s.%s': calculation expression gave value "
1555                             CALCULATED_NUMBER_FORMAT
1556                             ": %s (source: %s)",
1557                           rc->chart?rc->chart:"NOCHART", rc->name,
1558                           rc->calculation->result,
1559                           buffer_tostring(rc->calculation->error_msg),
1560                           rc->source
1561                     );
1562
1563                     rc->value = rc->calculation->result;
1564                 }
1565             }
1566         }
1567         rrdhost_unlock(&localhost);
1568
1569         if (runnable) {
1570             rrdhost_rdlock(&localhost);
1571
1572             for (rc = localhost.alarms; rc; rc = rc->next) {
1573                 if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
1574                     continue;
1575
1576                 if(unlikely(rc->warning)) {
1577                     if(unlikely(!expression_evaluate(rc->warning))) {
1578                         // calculation failed
1579                         if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_WARN_ERROR))) {
1580                             rc->rrdcalc_options |= RRDCALC_OPTION_WARN_ERROR;
1581                             error("Health alarm '%s.%s': warning expression failed with error: %s",
1582                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
1583                         }
1584                     }
1585                     else {
1586                         if(unlikely(rc->rrdcalc_options & RRDCALC_OPTION_WARN_ERROR))
1587                             rc->rrdcalc_options &= ~RRDCALC_OPTION_WARN_ERROR;
1588
1589                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression gave value "
1590                                 CALCULATED_NUMBER_FORMAT
1591                                 ": %s (source: %s)",
1592                               rc->chart?rc->chart:"NOCHART", rc->name,
1593                               rc->warning->result,
1594                               buffer_tostring(rc->warning->error_msg),
1595                               rc->source
1596                         );
1597                     }
1598
1599                     rrdcalc_check_warning_event(rc);
1600                 }
1601
1602                 if(unlikely(rc->critical)) {
1603                     if(unlikely(!expression_evaluate(rc->critical))) {
1604                         // calculation failed
1605                         if (unlikely(!(rc->rrdcalc_options & RRDCALC_OPTION_CRIT_ERROR))) {
1606                             rc->rrdcalc_options |= RRDCALC_OPTION_CRIT_ERROR;
1607                             error("Health alarm '%s.%s': critical expression failed with error: %s",
1608                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
1609                         }
1610                     }
1611                     else {
1612                         if(unlikely(rc->rrdcalc_options & RRDCALC_OPTION_CRIT_ERROR))
1613                             rc->rrdcalc_options &= ~RRDCALC_OPTION_CRIT_ERROR;
1614
1615                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression gave value "
1616                                 CALCULATED_NUMBER_FORMAT
1617                                 ": %s (source: %s)",
1618                               rc->chart?rc->chart:"NOCHART", rc->name,
1619                               rc->critical->result,
1620                               buffer_tostring(rc->critical->error_msg),
1621                               rc->source
1622                         );
1623                     }
1624
1625                     rrdcalc_check_critical_event(rc);
1626                 }
1627
1628                 rc->last_updated = now;
1629                 rc->next_update = now + rc->update_every;
1630
1631                 if (next_run > rc->next_update)
1632                     next_run = rc->next_update;
1633             }
1634
1635             rrdhost_unlock(&localhost);
1636         }
1637
1638
1639         if (unlikely(pthread_setcancelstate(oldstate, NULL) != 0))
1640             error("Cannot set pthread cancel state to RESTORE (%d).", oldstate);
1641
1642         debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration in %d secs",
1643               loop, (int) (next_run - now));
1644
1645         sleep_usec(1000000 * (unsigned long long) (next_run - now));
1646     }
1647
1648     buffer_free(wb);
1649
1650     info("HEALTH thread exiting");
1651     pthread_exit(NULL);
1652     return NULL;
1653 }