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