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