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