]> arthur.barton.de Git - netdata.git/blob - src/health.c
Merge pull request #975 from paulfantom/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->status = &rc->status;
697         rc->calculation->this = &rc->value;
698         rc->calculation->after = &rc->db_after;
699         rc->calculation->before = &rc->db_before;
700         rc->calculation->rrdcalc = rc;
701     }
702
703     if(rc->warning) {
704         rc->warning->status = &rc->status;
705         rc->warning->this = &rc->value;
706         rc->warning->after = &rc->db_after;
707         rc->warning->before = &rc->db_before;
708         rc->warning->rrdcalc = rc;
709     }
710
711     if(rc->critical) {
712         rc->critical->status = &rc->status;
713         rc->critical->this = &rc->value;
714         rc->critical->after = &rc->db_after;
715         rc->critical->before = &rc->db_before;
716         rc->critical->rrdcalc = rc;
717     }
718
719     // link it to the host
720     if(likely(host->alarms)) {
721         // append it
722         RRDCALC *t;
723         for(t = host->alarms; t && t->next ; t = t->next) ;
724         t->next = rc;
725     }
726     else {
727         host->alarms = rc;
728     }
729
730     // link it to its chart
731     RRDSET *st;
732     for(st = host->rrdset_root; st ; st = st->next) {
733         if(rrdcalc_is_matching_this_rrdset(rc, st)) {
734             rrdsetcalc_link(st, rc);
735             break;
736         }
737     }
738 }
739
740 static inline RRDCALC *rrdcalc_create(RRDHOST *host, RRDCALCTEMPLATE *rt, const char *chart) {
741
742     debug(D_HEALTH, "Health creating dynamic alarm (from template) '%s.%s'", chart, rt->name);
743
744     if(rrdcalc_exists(host, chart, rt->name, 0, 0))
745         return NULL;
746
747     RRDCALC *rc = callocz(1, sizeof(RRDCALC));
748     rc->next_event_id = 1;
749     rc->id = rrdcalc_get_unique_id(host, chart, rt->name, &rc->next_event_id);
750     rc->name = strdupz(rt->name);
751     rc->hash = simple_hash(rc->name);
752     rc->chart = strdupz(chart);
753     rc->hash_chart = simple_hash(rc->chart);
754
755     if(rt->dimensions) rc->dimensions = strdupz(rt->dimensions);
756
757     rc->green = rt->green;
758     rc->red = rt->red;
759     rc->value = NAN;
760     rc->old_value = NAN;
761
762     rc->delay_up_duration = rt->delay_up_duration;
763     rc->delay_down_duration = rt->delay_down_duration;
764     rc->delay_max_duration = rt->delay_max_duration;
765     rc->delay_multiplier = rt->delay_multiplier;
766
767     rc->group = rt->group;
768     rc->after = rt->after;
769     rc->before = rt->before;
770     rc->update_every = rt->update_every;
771     rc->options = rt->options;
772
773     if(rt->exec) rc->exec = strdupz(rt->exec);
774     if(rt->recipient) rc->recipient = strdupz(rt->recipient);
775     if(rt->source) rc->source = strdupz(rt->source);
776     if(rt->units) rc->units = strdupz(rt->units);
777     if(rt->info) rc->info = strdupz(rt->info);
778
779     if(rt->calculation) {
780         rc->calculation = expression_parse(rt->calculation->source, NULL, NULL);
781         if(!rc->calculation)
782             error("Health alarm '%s.%s': failed to parse calculation expression '%s'", chart, rt->name, rt->calculation->source);
783     }
784     if(rt->warning) {
785         rc->warning = expression_parse(rt->warning->source, NULL, NULL);
786         if(!rc->warning)
787             error("Health alarm '%s.%s': failed to re-parse warning expression '%s'", chart, rt->name, rt->warning->source);
788     }
789     if(rt->critical) {
790         rc->critical = expression_parse(rt->critical->source, NULL, NULL);
791         if(!rc->critical)
792             error("Health alarm '%s.%s': failed to re-parse critical expression '%s'", chart, rt->name, rt->critical->source);
793     }
794
795     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",
796           (rc->chart)?rc->chart:"NOCHART",
797           rc->name,
798           (rc->exec)?rc->exec:"DEFAULT",
799           (rc->recipient)?rc->recipient:"DEFAULT",
800           rc->green,
801           rc->red,
802           rc->group,
803           rc->after,
804           rc->before,
805           rc->options,
806           (rc->dimensions)?rc->dimensions:"NONE",
807           rc->update_every,
808           (rc->calculation)?rc->calculation->parsed_as:"NONE",
809           (rc->warning)?rc->warning->parsed_as:"NONE",
810           (rc->critical)?rc->critical->parsed_as:"NONE",
811           rc->source,
812           rc->delay_up_duration,
813           rc->delay_down_duration,
814           rc->delay_max_duration,
815           rc->delay_multiplier
816     );
817
818     rrdcalc_create_part2(host, rc);
819     return rc;
820 }
821
822 void rrdcalc_free(RRDHOST *host, RRDCALC *rc) {
823     if(!rc) return;
824
825     debug(D_HEALTH, "Health removing alarm '%s.%s' of host '%s'", rc->chart?rc->chart:"NOCHART", rc->name, host->hostname);
826
827     // unlink it from RRDSET
828     if(rc->rrdset) rrdsetcalc_unlink(rc);
829
830     // unlink it from RRDHOST
831     if(unlikely(rc == host->alarms))
832         host->alarms = rc->next;
833
834     else if(likely(host->alarms)) {
835         RRDCALC *t, *last = host->alarms;
836         for(t = last->next; t && t != rc; last = t, t = t->next) ;
837         if(last->next == rc)
838             last->next = rc->next;
839         else
840             error("Cannot unlink alarm '%s.%s' from host '%s': not found", rc->chart?rc->chart:"NOCHART", rc->name, host->hostname);
841     }
842     else
843         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);
844
845     expression_free(rc->calculation);
846     expression_free(rc->warning);
847     expression_free(rc->critical);
848
849     freez(rc->name);
850     freez(rc->chart);
851     freez(rc->family);
852     freez(rc->dimensions);
853     freez(rc->exec);
854     freez(rc->recipient);
855     freez(rc->source);
856     freez(rc->units);
857     freez(rc->info);
858     freez(rc);
859 }
860
861 // ----------------------------------------------------------------------------
862 // RRDCALCTEMPLATE management
863
864 void rrdcalctemplate_link_matching(RRDSET *st) {
865     RRDCALCTEMPLATE *rt;
866
867     for(rt = st->rrdhost->templates; rt ; rt = rt->next) {
868         if(rt->hash_context == st->hash_context && !strcmp(rt->context, st->context)) {
869             RRDCALC *rc = rrdcalc_create(st->rrdhost, rt, st->id);
870             if(unlikely(!rc))
871                 error("Health tried to create alarm from template '%s', but it failed", rt->name);
872
873 #ifdef NETDATA_INTERNAL_CHECKS
874             else if(rc->rrdset != st)
875                 error("Health alarm '%s.%s' should be linked to chart '%s', but it is not", rc->chart?rc->chart:"NOCHART", rc->name, st->id);
876 #endif
877         }
878     }
879 }
880
881 static inline void rrdcalctemplate_free(RRDHOST *host, RRDCALCTEMPLATE *rt) {
882     debug(D_HEALTH, "Health removing template '%s' of host '%s'", rt->name, host->hostname);
883
884     if(host->templates) {
885         if(host->templates == rt) {
886             host->templates = rt->next;
887         }
888         else {
889             RRDCALCTEMPLATE *t, *last = host->templates;
890             for (t = last->next; t && t != rt; last = t, t = t->next ) ;
891             if(last && last->next == rt) {
892                 last->next = rt->next;
893                 rt->next = NULL;
894             }
895             else
896                 error("Cannot find RRDCALCTEMPLATE '%s' linked in host '%s'", rt->name, host->hostname);
897         }
898     }
899
900     expression_free(rt->calculation);
901     expression_free(rt->warning);
902     expression_free(rt->critical);
903
904     freez(rt->name);
905     freez(rt->exec);
906     freez(rt->recipient);
907     freez(rt->context);
908     freez(rt->source);
909     freez(rt->units);
910     freez(rt->info);
911     freez(rt->dimensions);
912     freez(rt);
913 }
914
915 // ----------------------------------------------------------------------------
916 // load health configuration
917
918 #define HEALTH_CONF_MAX_LINE 4096
919
920 #define HEALTH_ALARM_KEY "alarm"
921 #define HEALTH_TEMPLATE_KEY "template"
922 #define HEALTH_ON_KEY "on"
923 #define HEALTH_LOOKUP_KEY "lookup"
924 #define HEALTH_CALC_KEY "calc"
925 #define HEALTH_EVERY_KEY "every"
926 #define HEALTH_GREEN_KEY "green"
927 #define HEALTH_RED_KEY "red"
928 #define HEALTH_WARN_KEY "warn"
929 #define HEALTH_CRIT_KEY "crit"
930 #define HEALTH_EXEC_KEY "exec"
931 #define HEALTH_RECIPIENT_KEY "to"
932 #define HEALTH_UNITS_KEY "units"
933 #define HEALTH_INFO_KEY "info"
934 #define HEALTH_DELAY_KEY "delay"
935
936 static inline int rrdcalc_add_alarm_from_config(RRDHOST *host, RRDCALC *rc) {
937     if(!rc->chart) {
938         error("Health configuration for alarm '%s' does not have a chart", rc->name);
939         return 0;
940     }
941
942     if(!rc->update_every) {
943         error("Health configuration for alarm '%s.%s' has no frequency (parameter 'every'). Ignoring it.", rc->chart?rc->chart:"NOCHART", rc->name);
944         return 0;
945     }
946
947     if(!RRDCALC_HAS_DB_LOOKUP(rc) && !rc->warning && !rc->critical) {
948         error("Health configuration for alarm '%s.%s' is useless (no calculation, no warning and no critical evaluation)", rc->chart?rc->chart:"NOCHART", rc->name);
949         return 0;
950     }
951
952     if (rrdcalc_exists(host, rc->chart, rc->name, rc->hash_chart, rc->hash))
953         return 0;
954
955     rc->id = rrdcalc_get_unique_id(&localhost, rc->chart, rc->name, &rc->next_event_id);
956
957     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",
958           rc->chart?rc->chart:"NOCHART",
959           rc->name,
960           rc->id,
961           (rc->exec)?rc->exec:"DEFAULT",
962           (rc->recipient)?rc->recipient:"DEFAULT",
963           rc->green,
964           rc->red,
965           rc->group,
966           rc->after,
967           rc->before,
968           rc->options,
969           (rc->dimensions)?rc->dimensions:"NONE",
970           rc->update_every,
971           (rc->calculation)?rc->calculation->parsed_as:"NONE",
972           (rc->warning)?rc->warning->parsed_as:"NONE",
973           (rc->critical)?rc->critical->parsed_as:"NONE",
974           rc->source,
975           rc->delay_up_duration,
976           rc->delay_down_duration,
977           rc->delay_max_duration,
978           rc->delay_multiplier
979     );
980
981     rrdcalc_create_part2(host, rc);
982     return 1;
983 }
984
985 static inline int rrdcalctemplate_add_template_from_config(RRDHOST *host, RRDCALCTEMPLATE *rt) {
986     if(unlikely(!rt->context)) {
987         error("Health configuration for template '%s' does not have a context", rt->name);
988         return 0;
989     }
990
991     if(unlikely(!rt->update_every)) {
992         error("Health configuration for template '%s' has no frequency (parameter 'every'). Ignoring it.", rt->name);
993         return 0;
994     }
995
996     if(unlikely(!RRDCALCTEMPLATE_HAS_CALCULATION(rt) && !rt->warning && !rt->critical)) {
997         error("Health configuration for template '%s' is useless (no calculation, no warning and no critical evaluation)", rt->name);
998         return 0;
999     }
1000
1001     RRDCALCTEMPLATE *t, *last = NULL;
1002     for (t = host->templates; t ; last = t, t = t->next) {
1003         if(unlikely(t->hash_name == rt->hash_name && !strcmp(t->name, rt->name))) {
1004             error("Health configuration template '%s' already exists for host '%s'.", rt->name, host->hostname);
1005             return 0;
1006         }
1007     }
1008
1009     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",
1010           rt->name,
1011           (rt->context)?rt->context:"NONE",
1012           (rt->exec)?rt->exec:"DEFAULT",
1013           (rt->recipient)?rt->recipient:"DEFAULT",
1014           rt->green,
1015           rt->red,
1016           rt->group,
1017           rt->after,
1018           rt->before,
1019           rt->options,
1020           (rt->dimensions)?rt->dimensions:"NONE",
1021           rt->update_every,
1022           (rt->calculation)?rt->calculation->parsed_as:"NONE",
1023           (rt->warning)?rt->warning->parsed_as:"NONE",
1024           (rt->critical)?rt->critical->parsed_as:"NONE",
1025           rt->source,
1026           rt->delay_up_duration,
1027           rt->delay_down_duration,
1028           rt->delay_max_duration,
1029           rt->delay_multiplier
1030     );
1031
1032     if(likely(last)) {
1033         last->next = rt;
1034     }
1035     else {
1036         rt->next = host->templates;
1037         host->templates = rt;
1038     }
1039
1040     return 1;
1041 }
1042
1043 static inline int health_parse_duration(char *string, int *result) {
1044     // make sure it is a number
1045     if(!*string || !(isdigit(*string) || *string == '+' || *string == '-')) {
1046         *result = 0;
1047         return 0;
1048     }
1049
1050     char *e = NULL;
1051     calculated_number n = strtold(string, &e);
1052     if(e && *e) {
1053         switch (*e) {
1054             case 'Y':
1055                 *result = (int) (n * 86400 * 365);
1056                 break;
1057             case 'M':
1058                 *result = (int) (n * 86400 * 30);
1059                 break;
1060             case 'w':
1061                 *result = (int) (n * 86400 * 7);
1062                 break;
1063             case 'd':
1064                 *result = (int) (n * 86400);
1065                 break;
1066             case 'h':
1067                 *result = (int) (n * 3600);
1068                 break;
1069             case 'm':
1070                 *result = (int) (n * 60);
1071                 break;
1072
1073             default:
1074             case 's':
1075                 *result = (int) (n);
1076                 break;
1077         }
1078     }
1079     else
1080        *result = (int)(n);
1081
1082     return 1;
1083 }
1084
1085 static inline int health_parse_delay(
1086         size_t line, const char *path, const char *file, char *string,
1087         int *delay_up_duration,
1088         int *delay_down_duration,
1089         int *delay_max_duration,
1090         float *delay_multiplier) {
1091
1092     char given_up = 0;
1093     char given_down = 0;
1094     char given_max = 0;
1095     char given_multiplier = 0;
1096
1097     char *s = string;
1098     while(*s) {
1099         char *key = s;
1100
1101         while(*s && !isspace(*s)) s++;
1102         while(*s && isspace(*s)) *s++ = '\0';
1103
1104         if(!*key) break;
1105
1106         char *value = s;
1107         while(*s && !isspace(*s)) s++;
1108         while(*s && isspace(*s)) *s++ = '\0';
1109
1110         if(!strcasecmp(key, "up")) {
1111             if (!health_parse_duration(value, delay_up_duration)) {
1112                 error("Health configuration at line %zu of file '%s/%s': invalid value '%s' for '%s' keyword",
1113                       line, path, file, value, key);
1114             }
1115             else given_up = 1;
1116         }
1117         else if(!strcasecmp(key, "down")) {
1118             if (!health_parse_duration(value, delay_down_duration)) {
1119                 error("Health configuration at line %zu of file '%s/%s': invalid value '%s' for '%s' keyword",
1120                       line, path, file, value, key);
1121             }
1122             else given_down = 1;
1123         }
1124         else if(!strcasecmp(key, "multiplier")) {
1125             *delay_multiplier = strtof(value, NULL);
1126             if(isnan(*delay_multiplier) || isinf(*delay_multiplier) || islessequal(*delay_multiplier, 0)) {
1127                 error("Health configuration at line %zu of file '%s/%s': invalid value '%s' for '%s' keyword",
1128                       line, path, file, value, key);
1129             }
1130             else given_multiplier = 1;
1131         }
1132         else if(!strcasecmp(key, "max")) {
1133             if (!health_parse_duration(value, delay_max_duration)) {
1134                 error("Health configuration at line %zu of file '%s/%s': invalid value '%s' for '%s' keyword",
1135                       line, path, file, value, key);
1136             }
1137             else given_max = 1;
1138         }
1139         else {
1140             error("Health configuration at line %zu of file '%s/%s': unknown keyword '%s'",
1141                   line, path, file, key);
1142         }
1143     }
1144
1145     if(!given_up)
1146         *delay_up_duration = 0;
1147
1148     if(!given_down)
1149         *delay_down_duration = 0;
1150
1151     if(!given_multiplier)
1152         *delay_multiplier = 1.0;
1153
1154     if(!given_max) {
1155         if((*delay_max_duration) < (*delay_up_duration) * (*delay_multiplier))
1156             *delay_max_duration = (*delay_up_duration) * (*delay_multiplier);
1157
1158         if((*delay_max_duration) < (*delay_down_duration) * (*delay_multiplier))
1159             *delay_max_duration = (*delay_down_duration) * (*delay_multiplier);
1160     }
1161
1162     return 1;
1163 }
1164
1165 static inline int health_parse_db_lookup(
1166         size_t line, const char *path, const char *file, char *string,
1167         int *group_method, int *after, int *before, int *every,
1168         uint32_t *options, char **dimensions
1169 ) {
1170     debug(D_HEALTH, "Health configuration parsing database lookup %zu@%s/%s: %s", line, path, file, string);
1171
1172     if(*dimensions) freez(*dimensions);
1173     *dimensions = NULL;
1174     *after = 0;
1175     *before = 0;
1176     *every = 0;
1177     *options = 0;
1178
1179     char *s = string, *key;
1180
1181     // first is the group method
1182     key = s;
1183     while(*s && !isspace(*s)) s++;
1184     while(*s && isspace(*s)) *s++ = '\0';
1185     if(!*s) {
1186         error("Health configuration invalid chart calculation at line %zu of file '%s/%s': expected group method followed by the 'after' time, but got '%s'",
1187               line, path, file, key);
1188         return 0;
1189     }
1190
1191     if((*group_method = web_client_api_request_v1_data_group(key, -1)) == -1) {
1192         error("Health configuration at line %zu of file '%s/%s': invalid group method '%s'",
1193               line, path, file, key);
1194         return 0;
1195     }
1196
1197     // then is the 'after' time
1198     key = s;
1199     while(*s && !isspace(*s)) s++;
1200     while(*s && isspace(*s)) *s++ = '\0';
1201
1202     if(!health_parse_duration(key, after)) {
1203         error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' after group method",
1204               line, path, file, key);
1205         return 0;
1206     }
1207
1208     // sane defaults
1209     *every = abs(*after);
1210
1211     // now we may have optional parameters
1212     while(*s) {
1213         key = s;
1214         while(*s && !isspace(*s)) s++;
1215         while(*s && isspace(*s)) *s++ = '\0';
1216         if(!*key) break;
1217
1218         if(!strcasecmp(key, "at")) {
1219             char *value = s;
1220             while(*s && !isspace(*s)) s++;
1221             while(*s && isspace(*s)) *s++ = '\0';
1222
1223             if (!health_parse_duration(value, before)) {
1224                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
1225                       line, path, file, value, key);
1226             }
1227         }
1228         else if(!strcasecmp(key, HEALTH_EVERY_KEY)) {
1229             char *value = s;
1230             while(*s && !isspace(*s)) s++;
1231             while(*s && isspace(*s)) *s++ = '\0';
1232
1233             if (!health_parse_duration(value, every)) {
1234                 error("Health configuration at line %zu of file '%s/%s': invalid duration '%s' for '%s' keyword",
1235                       line, path, file, value, key);
1236             }
1237         }
1238         else if(!strcasecmp(key, "absolute") || !strcasecmp(key, "abs") || !strcasecmp(key, "absolute_sum")) {
1239             *options |= RRDR_OPTION_ABSOLUTE;
1240         }
1241         else if(!strcasecmp(key, "min2max")) {
1242             *options |= RRDR_OPTION_MIN2MAX;
1243         }
1244         else if(!strcasecmp(key, "null2zero")) {
1245             *options |= RRDR_OPTION_NULL2ZERO;
1246         }
1247         else if(!strcasecmp(key, "percentage")) {
1248             *options |= RRDR_OPTION_PERCENTAGE;
1249         }
1250         else if(!strcasecmp(key, "unaligned")) {
1251             *options |= RRDR_OPTION_NOT_ALIGNED;
1252         }
1253         else if(!strcasecmp(key, "of")) {
1254             if(*s && strcasecmp(s, "all"))
1255                *dimensions = strdupz(s);
1256             break;
1257         }
1258         else {
1259             error("Health configuration at line %zu of file '%s/%s': unknown keyword '%s'",
1260                   line, path, file, key);
1261         }
1262     }
1263
1264     return 1;
1265 }
1266
1267 static inline char *health_source_file(size_t line, const char *path, const char *filename) {
1268     char buffer[FILENAME_MAX + 1];
1269     snprintfz(buffer, FILENAME_MAX, "%zu@%s/%s", line, path, filename);
1270     return strdupz(buffer);
1271 }
1272
1273 static inline void strip_quotes(char *s) {
1274     while(*s) {
1275         if(*s == '\'' || *s == '"') *s = ' ';
1276         s++;
1277     }
1278 }
1279
1280 int health_readfile(const char *path, const char *filename) {
1281     debug(D_HEALTH, "Health configuration reading file '%s/%s'", path, filename);
1282
1283     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;
1284     char buffer[HEALTH_CONF_MAX_LINE + 1];
1285
1286     if(unlikely(!hash_alarm)) {
1287         hash_alarm = simple_uhash(HEALTH_ALARM_KEY);
1288         hash_template = simple_uhash(HEALTH_TEMPLATE_KEY);
1289         hash_on = simple_uhash(HEALTH_ON_KEY);
1290         hash_calc = simple_uhash(HEALTH_CALC_KEY);
1291         hash_lookup = simple_uhash(HEALTH_LOOKUP_KEY);
1292         hash_green = simple_uhash(HEALTH_GREEN_KEY);
1293         hash_red = simple_uhash(HEALTH_RED_KEY);
1294         hash_warn = simple_uhash(HEALTH_WARN_KEY);
1295         hash_crit = simple_uhash(HEALTH_CRIT_KEY);
1296         hash_exec = simple_uhash(HEALTH_EXEC_KEY);
1297         hash_every = simple_uhash(HEALTH_EVERY_KEY);
1298         hash_units = simple_hash(HEALTH_UNITS_KEY);
1299         hash_info = simple_hash(HEALTH_INFO_KEY);
1300         hash_recipient = simple_hash(HEALTH_RECIPIENT_KEY);
1301         hash_delay = simple_uhash(HEALTH_DELAY_KEY);
1302     }
1303
1304     snprintfz(buffer, HEALTH_CONF_MAX_LINE, "%s/%s", path, filename);
1305     FILE *fp = fopen(buffer, "r");
1306     if(!fp) {
1307         error("Health configuration cannot read file '%s'.", buffer);
1308         return 0;
1309     }
1310
1311     RRDCALC *rc = NULL;
1312     RRDCALCTEMPLATE *rt = NULL;
1313
1314     size_t line = 0, append = 0;
1315     char *s;
1316     while((s = fgets(&buffer[append], (int)(HEALTH_CONF_MAX_LINE - append), fp)) || append) {
1317         int stop_appending = !s;
1318         line++;
1319         // info("Line %zu of file '%s/%s': '%s'", line, path, filename, s);
1320         s = trim(buffer);
1321         if(!s) continue;
1322         // info("Trimmed line %zu of file '%s/%s': '%s'", line, path, filename, s);
1323
1324         append = strlen(s);
1325         if(!stop_appending && s[append - 1] == '\\') {
1326             s[append - 1] = ' ';
1327             append = &s[append] - buffer;
1328             if(append < HEALTH_CONF_MAX_LINE)
1329                 continue;
1330             else {
1331                 error("Health configuration has too long muli-line at line %zu of file '%s/%s'.", line, path, filename);
1332             }
1333         }
1334         append = 0;
1335
1336         char *key = s;
1337         while(*s && *s != ':') s++;
1338         if(!*s) {
1339             error("Health configuration has invalid line %zu of file '%s/%s'. It does not contain a ':'. Ignoring it.", line, path, filename);
1340             continue;
1341         }
1342         *s = '\0';
1343         s++;
1344
1345         char *value = s;
1346         key = trim(key);
1347         value = trim(value);
1348
1349         if(!key) {
1350             error("Health configuration has invalid line %zu of file '%s/%s'. Keyword is empty. Ignoring it.", line, path, filename);
1351             continue;
1352         }
1353
1354         if(!value) {
1355             error("Health configuration has invalid line %zu of file '%s/%s'. value is empty. Ignoring it.", line, path, filename);
1356             continue;
1357         }
1358
1359         // info("Health file '%s/%s', key '%s', value '%s'", path, filename, key, value);
1360         uint32_t hash = simple_uhash(key);
1361
1362         if(hash == hash_alarm && !strcasecmp(key, HEALTH_ALARM_KEY)) {
1363             if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1364                 rrdcalc_free(&localhost, rc);
1365
1366             if(rt) {
1367                 if (!rrdcalctemplate_add_template_from_config(&localhost, rt))
1368                     rrdcalctemplate_free(&localhost, rt);
1369                 rt = NULL;
1370             }
1371
1372             rc = callocz(1, sizeof(RRDCALC));
1373             rc->next_event_id = 1;
1374             rc->name = strdupz(value);
1375             rc->hash = simple_hash(rc->name);
1376             rc->source = health_source_file(line, path, filename);
1377             rc->green = NAN;
1378             rc->red = NAN;
1379             rc->value = NAN;
1380             rc->old_value = NAN;
1381             rc->delay_multiplier = 1.0;
1382
1383             if(rrdvar_fix_name(rc->name))
1384                 error("Health configuration renamed alarm '%s' to '%s'", value, rc->name);
1385         }
1386         else if(hash == hash_template && !strcasecmp(key, HEALTH_TEMPLATE_KEY)) {
1387             if(rc) {
1388                 if(!rrdcalc_add_alarm_from_config(&localhost, rc))
1389                     rrdcalc_free(&localhost, rc);
1390                 rc = NULL;
1391             }
1392
1393             if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1394                 rrdcalctemplate_free(&localhost, rt);
1395
1396             rt = callocz(1, sizeof(RRDCALCTEMPLATE));
1397             rt->name = strdupz(value);
1398             rt->hash_name = simple_hash(rt->name);
1399             rt->source = health_source_file(line, path, filename);
1400             rt->green = NAN;
1401             rt->red = NAN;
1402             rt->delay_multiplier = 1.0;
1403
1404             if(rrdvar_fix_name(rt->name))
1405                 error("Health configuration renamed template '%s' to '%s'", value, rt->name);
1406         }
1407         else if(rc) {
1408             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1409                 if(rc->chart) {
1410                     if(strcmp(rc->chart, value))
1411                         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').",
1412                              line, path, filename, rc->name, key, rc->chart, value, value);
1413
1414                     freez(rc->chart);
1415                 }
1416                 rc->chart = strdupz(value);
1417                 rc->hash_chart = simple_hash(rc->chart);
1418             }
1419             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1420                 health_parse_db_lookup(line, path, filename, value, &rc->group, &rc->after, &rc->before,
1421                                        &rc->update_every,
1422                                        &rc->options, &rc->dimensions);
1423             }
1424             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1425                 if(!health_parse_duration(value, &rc->update_every))
1426                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' cannot parse duration: '%s'.",
1427                          line, path, filename, rc->name, key, value);
1428             }
1429             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1430                 char *e;
1431                 rc->green = strtold(value, &e);
1432                 if(e && *e) {
1433                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1434                          line, path, filename, rc->name, key, e);
1435                 }
1436             }
1437             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1438                 char *e;
1439                 rc->red = strtold(value, &e);
1440                 if(e && *e) {
1441                     info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
1442                          line, path, filename, rc->name, key, e);
1443                 }
1444             }
1445             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1446                 const char *failed_at = NULL;
1447                 int error = 0;
1448                 rc->calculation = expression_parse(value, &failed_at, &error);
1449                 if(!rc->calculation) {
1450                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1451                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1452                 }
1453             }
1454             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1455                 const char *failed_at = NULL;
1456                 int error = 0;
1457                 rc->warning = expression_parse(value, &failed_at, &error);
1458                 if(!rc->warning) {
1459                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1460                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1461                 }
1462             }
1463             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1464                 const char *failed_at = NULL;
1465                 int error = 0;
1466                 rc->critical = expression_parse(value, &failed_at, &error);
1467                 if(!rc->critical) {
1468                     error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1469                           line, path, filename, rc->name, key, value, expression_strerror(error), failed_at);
1470                 }
1471             }
1472             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1473                 if(rc->exec) {
1474                     if(strcmp(rc->exec, value))
1475                         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').",
1476                              line, path, filename, rc->name, key, rc->exec, value, value);
1477
1478                     freez(rc->exec);
1479                 }
1480                 rc->exec = strdupz(value);
1481             }
1482             else if(hash == hash_recipient && !strcasecmp(key, HEALTH_RECIPIENT_KEY)) {
1483                 if(rc->recipient) {
1484                     if(strcmp(rc->recipient, value))
1485                         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').",
1486                              line, path, filename, rc->name, key, rc->recipient, value, value);
1487
1488                     freez(rc->recipient);
1489                 }
1490                 rc->recipient = strdupz(value);
1491             }
1492             else if(hash == hash_units && !strcasecmp(key, HEALTH_UNITS_KEY)) {
1493                 if(rc->units) {
1494                     if(strcmp(rc->units, value))
1495                         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').",
1496                              line, path, filename, rc->name, key, rc->units, value, value);
1497
1498                     freez(rc->units);
1499                 }
1500                 rc->units = strdupz(value);
1501                 strip_quotes(rc->units);
1502             }
1503             else if(hash == hash_info && !strcasecmp(key, HEALTH_INFO_KEY)) {
1504                 if(rc->info) {
1505                     if(strcmp(rc->info, value))
1506                         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').",
1507                              line, path, filename, rc->name, key, rc->info, value, value);
1508
1509                     freez(rc->info);
1510                 }
1511                 rc->info = strdupz(value);
1512                 strip_quotes(rc->info);
1513             }
1514             else if(hash == hash_delay && !strcasecmp(key, HEALTH_DELAY_KEY)) {
1515                 health_parse_delay(line, path, filename, value, &rc->delay_up_duration, &rc->delay_down_duration, &rc->delay_max_duration, &rc->delay_multiplier);
1516             }
1517             else {
1518                 error("Health configuration at line %zu of file '%s/%s' for alarm '%s' has unknown key '%s'.",
1519                      line, path, filename, rc->name, key);
1520             }
1521         }
1522         else if(rt) {
1523             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
1524                 if(rt->context) {
1525                     if(strcmp(rt->context, value))
1526                         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').",
1527                              line, path, filename, rt->name, key, rt->context, value, value);
1528
1529                     freez(rt->context);
1530                 }
1531                 rt->context = strdupz(value);
1532                 rt->hash_context = simple_hash(rt->context);
1533             }
1534             else if(hash == hash_lookup && !strcasecmp(key, HEALTH_LOOKUP_KEY)) {
1535                 health_parse_db_lookup(line, path, filename, value, &rt->group, &rt->after, &rt->before,
1536                                        &rt->update_every,
1537                                        &rt->options, &rt->dimensions);
1538             }
1539             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
1540                 if(!health_parse_duration(value, &rt->update_every))
1541                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' cannot parse duration: '%s'.",
1542                          line, path, filename, rt->name, key, value);
1543             }
1544             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
1545                 char *e;
1546                 rt->green = strtold(value, &e);
1547                 if(e && *e) {
1548                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1549                          line, path, filename, rt->name, key, e);
1550                 }
1551             }
1552             else if(hash == hash_red && !strcasecmp(key, HEALTH_RED_KEY)) {
1553                 char *e;
1554                 rt->red = strtold(value, &e);
1555                 if(e && *e) {
1556                     info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
1557                          line, path, filename, rt->name, key, e);
1558                 }
1559             }
1560             else if(hash == hash_calc && !strcasecmp(key, HEALTH_CALC_KEY)) {
1561                 const char *failed_at = NULL;
1562                 int error = 0;
1563                 rt->calculation = expression_parse(value, &failed_at, &error);
1564                 if(!rt->calculation) {
1565                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1566                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1567                 }
1568             }
1569             else if(hash == hash_warn && !strcasecmp(key, HEALTH_WARN_KEY)) {
1570                 const char *failed_at = NULL;
1571                 int error = 0;
1572                 rt->warning = expression_parse(value, &failed_at, &error);
1573                 if(!rt->warning) {
1574                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1575                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1576                 }
1577             }
1578             else if(hash == hash_crit && !strcasecmp(key, HEALTH_CRIT_KEY)) {
1579                 const char *failed_at = NULL;
1580                 int error = 0;
1581                 rt->critical = expression_parse(value, &failed_at, &error);
1582                 if(!rt->critical) {
1583                     error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' has unparse-able expression '%s': %s at '%s'",
1584                           line, path, filename, rt->name, key, value, expression_strerror(error), failed_at);
1585                 }
1586             }
1587             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
1588                 if(rt->exec) {
1589                     if(strcmp(rt->exec, value))
1590                         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').",
1591                              line, path, filename, rt->name, key, rt->exec, value, value);
1592
1593                     freez(rt->exec);
1594                 }
1595                 rt->exec = strdupz(value);
1596             }
1597             else if(hash == hash_recipient && !strcasecmp(key, HEALTH_RECIPIENT_KEY)) {
1598                 if(rt->recipient) {
1599                     if(strcmp(rt->recipient, value))
1600                         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').",
1601                              line, path, filename, rt->name, key, rt->recipient, value, value);
1602
1603                     freez(rt->recipient);
1604                 }
1605                 rt->recipient = strdupz(value);
1606             }
1607             else if(hash == hash_units && !strcasecmp(key, HEALTH_UNITS_KEY)) {
1608                 if(rt->units) {
1609                     if(strcmp(rt->units, value))
1610                         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').",
1611                              line, path, filename, rt->name, key, rt->units, value, value);
1612
1613                     freez(rt->units);
1614                 }
1615                 rt->units = strdupz(value);
1616                 strip_quotes(rt->units);
1617             }
1618             else if(hash == hash_info && !strcasecmp(key, HEALTH_INFO_KEY)) {
1619                 if(rt->info) {
1620                     if(strcmp(rt->info, value))
1621                         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').",
1622                              line, path, filename, rt->name, key, rt->info, value, value);
1623
1624                     freez(rt->info);
1625                 }
1626                 rt->info = strdupz(value);
1627                 strip_quotes(rt->info);
1628             }
1629             else if(hash == hash_delay && !strcasecmp(key, HEALTH_DELAY_KEY)) {
1630                 health_parse_delay(line, path, filename, value, &rt->delay_up_duration, &rt->delay_down_duration, &rt->delay_max_duration, &rt->delay_multiplier);
1631             }
1632             else {
1633                 error("Health configuration at line %zu of file '%s/%s' for template '%s' has unknown key '%s'.",
1634                       line, path, filename, rt->name, key);
1635             }
1636         }
1637         else {
1638             error("Health configuration at line %zu of file '%s/%s' has unknown key '%s'. Expected either '" HEALTH_ALARM_KEY "' or '" HEALTH_TEMPLATE_KEY "'.",
1639                   line, path, filename, key);
1640         }
1641     }
1642
1643     if(rc && !rrdcalc_add_alarm_from_config(&localhost, rc))
1644         rrdcalc_free(&localhost, rc);
1645
1646     if(rt && !rrdcalctemplate_add_template_from_config(&localhost, rt))
1647         rrdcalctemplate_free(&localhost, rt);
1648
1649     fclose(fp);
1650     return 1;
1651 }
1652
1653 void health_readdir(const char *path) {
1654     size_t pathlen = strlen(path);
1655
1656     debug(D_HEALTH, "Health configuration reading directory '%s'", path);
1657
1658     DIR *dir = opendir(path);
1659     if (!dir) {
1660         error("Health configuration cannot open directory '%s'.", path);
1661         return;
1662     }
1663
1664     struct dirent *de = NULL;
1665     while ((de = readdir(dir))) {
1666         size_t len = strlen(de->d_name);
1667
1668         if(de->d_type == DT_DIR
1669            && (
1670                    (de->d_name[0] == '.' && de->d_name[1] == '\0')
1671                    || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0')
1672            )) {
1673             debug(D_HEALTH, "Ignoring directory '%s'", de->d_name);
1674             continue;
1675         }
1676
1677         else if(de->d_type == DT_DIR) {
1678             char *s = mallocz(pathlen + strlen(de->d_name) + 2);
1679             strcpy(s, path);
1680             strcat(s, "/");
1681             strcat(s, de->d_name);
1682             health_readdir(s);
1683             freez(s);
1684             continue;
1685         }
1686
1687         else if((de->d_type == DT_LNK || de->d_type == DT_REG || de->d_type == DT_UNKNOWN) &&
1688                 len > 5 && !strcmp(&de->d_name[len - 5], ".conf")) {
1689             health_readfile(path, de->d_name);
1690         }
1691
1692         else debug(D_HEALTH, "Ignoring file '%s'", de->d_name);
1693     }
1694
1695     closedir(dir);
1696 }
1697
1698 static inline char *health_config_dir(void) {
1699     char buffer[FILENAME_MAX + 1];
1700     snprintfz(buffer, FILENAME_MAX, "%s/health.d", config_get("global", "config directory", CONFIG_DIR));
1701     return config_get("health", "health configuration directory", buffer);
1702 }
1703
1704 void health_init(void) {
1705     debug(D_HEALTH, "Health configuration initializing");
1706
1707     if(!(health_enabled = config_get_boolean("health", "enabled", 1))) {
1708         debug(D_HEALTH, "Health is disabled.");
1709         return;
1710     }
1711
1712     char *path = health_config_dir();
1713
1714     {
1715         char buffer[FILENAME_MAX + 1];
1716         snprintfz(buffer, FILENAME_MAX, "%s/alarm-notify.sh", config_get("global", "plugins directory", PLUGINS_DIR));
1717         health_default_exec = config_get("health", "script to execute on alarm", buffer);
1718     }
1719
1720     long n = config_get_number("health", "in memory max health log entries", (long)localhost.health_log.max);
1721     if(n < 10) {
1722         error("Health configuration has invalid max log entries %ld. Using default %u", n, localhost.health_log.max);
1723         config_set_number("health", "in memory max health log entries", (long)localhost.health_log.max);
1724     }
1725     else localhost.health_log.max = (unsigned int)n;
1726
1727     rrdhost_rwlock(&localhost);
1728     health_readdir(path);
1729     rrdhost_unlock(&localhost);
1730 }
1731
1732 // ----------------------------------------------------------------------------
1733 // JSON generation
1734
1735 static inline void health_string2json(BUFFER *wb, const char *prefix, const char *label, const char *value, const char *suffix) {
1736     if(value && *value)
1737         buffer_sprintf(wb, "%s\"%s\":\"%s\"%s", prefix, label, value, suffix);
1738     else
1739         buffer_sprintf(wb, "%s\"%s\":null%s", prefix, label, suffix);
1740 }
1741
1742 static inline void health_alarm_entry2json_nolock(BUFFER *wb, ALARM_ENTRY *ae, RRDHOST *host) {
1743     buffer_sprintf(wb, "\n\t{\n"
1744                            "\t\t\"hostname\": \"%s\",\n"
1745                            "\t\t\"unique_id\": %u,\n"
1746                            "\t\t\"alarm_id\": %u,\n"
1747                            "\t\t\"alarm_event_id\": %u,\n"
1748                            "\t\t\"name\": \"%s\",\n"
1749                            "\t\t\"chart\": \"%s\",\n"
1750                            "\t\t\"family\": \"%s\",\n"
1751                            "\t\t\"processed\": %s,\n"
1752                            "\t\t\"updated\": %s,\n"
1753                            "\t\t\"exec_run\": %lu,\n"
1754                            "\t\t\"exec_failed\": %s,\n"
1755                            "\t\t\"exec\": \"%s\",\n"
1756                            "\t\t\"recipient\": \"%s\",\n"
1757                            "\t\t\"exec_code\": %d,\n"
1758                            "\t\t\"source\": \"%s\",\n"
1759                            "\t\t\"units\": \"%s\",\n"
1760                            "\t\t\"info\": \"%s\",\n"
1761                            "\t\t\"when\": %lu,\n"
1762                            "\t\t\"duration\": %lu,\n"
1763                            "\t\t\"non_clear_duration\": %lu,\n"
1764                            "\t\t\"status\": \"%s\",\n"
1765                            "\t\t\"old_status\": \"%s\",\n"
1766                            "\t\t\"delay\": %d,\n"
1767                            "\t\t\"delay_up_to_timestamp\": %lu,\n",
1768                    host->hostname,
1769                    ae->unique_id,
1770                    ae->alarm_id,
1771                    ae->alarm_event_id,
1772                    ae->name,
1773                    ae->chart,
1774                    ae->family,
1775                    (ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_PROCESSED)?"true":"false",
1776                    (ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_UPDATED)?"true":"false",
1777                    (unsigned long)ae->exec_run_timestamp,
1778                    (ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_EXEC_FAILED)?"true":"false",
1779                    ae->exec?ae->exec:health_default_exec,
1780                    ae->recipient?ae->recipient:health_default_recipient,
1781                    ae->exec_code,
1782                    ae->source,
1783                    ae->units?ae->units:"",
1784                    ae->info?ae->info:"",
1785                    (unsigned long)ae->when,
1786                    (unsigned long)ae->duration,
1787                    (unsigned long)ae->non_clear_duration,
1788                    rrdcalc_status2string(ae->new_status),
1789                    rrdcalc_status2string(ae->old_status),
1790                    ae->delay,
1791                    (unsigned long)ae->delay_up_to_timestamp
1792     );
1793
1794     buffer_strcat(wb, "\t\t\"value\":");
1795     buffer_rrd_value(wb, ae->new_value);
1796     buffer_strcat(wb, ",\n");
1797
1798     buffer_strcat(wb, "\t\t\"old_value\":");
1799     buffer_rrd_value(wb, ae->old_value);
1800     buffer_strcat(wb, "\n");
1801
1802     buffer_strcat(wb, "\t}");
1803 }
1804
1805 void health_alarm_log2json(RRDHOST *host, BUFFER *wb, uint32_t after) {
1806     pthread_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
1807
1808     buffer_strcat(wb, "[");
1809
1810     unsigned int max = host->health_log.max;
1811     unsigned int count = 0;
1812     ALARM_ENTRY *ae;
1813     for(ae = host->health_log.alarms; ae && count < max ; count++, ae = ae->next) {
1814         if(ae->unique_id > after) {
1815             if(likely(count)) buffer_strcat(wb, ",");
1816             health_alarm_entry2json_nolock(wb, ae, host);
1817         }
1818     }
1819
1820     buffer_strcat(wb, "\n]\n");
1821
1822     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
1823 }
1824
1825 static inline void health_rrdcalc2json_nolock(BUFFER *wb, RRDCALC *rc) {
1826     buffer_sprintf(wb,
1827            "\t\t\"%s.%s\": {\n"
1828                    "\t\t\t\"id\": %lu,\n"
1829                    "\t\t\t\"name\": \"%s\",\n"
1830                    "\t\t\t\"chart\": \"%s\",\n"
1831                    "\t\t\t\"family\": \"%s\",\n"
1832                    "\t\t\t\"active\": %s,\n"
1833                    "\t\t\t\"exec\": \"%s\",\n"
1834                    "\t\t\t\"recipient\": \"%s\",\n"
1835                    "\t\t\t\"source\": \"%s\",\n"
1836                    "\t\t\t\"units\": \"%s\",\n"
1837                    "\t\t\t\"info\": \"%s\",\n"
1838                                    "\t\t\t\"status\": \"%s\",\n"
1839                    "\t\t\t\"last_status_change\": %lu,\n"
1840                    "\t\t\t\"last_updated\": %lu,\n"
1841                    "\t\t\t\"next_update\": %lu,\n"
1842                    "\t\t\t\"update_every\": %d,\n"
1843                    "\t\t\t\"delay_up_duration\": %d,\n"
1844                    "\t\t\t\"delay_down_duration\": %d,\n"
1845                    "\t\t\t\"delay_max_duration\": %d,\n"
1846                    "\t\t\t\"delay_multiplier\": %f,\n"
1847                    "\t\t\t\"delay\": %d,\n"
1848                    "\t\t\t\"delay_up_to_timestamp\": %lu,\n"
1849             , rc->chart, rc->name
1850             , (unsigned long)rc->id
1851             , rc->name
1852             , rc->chart
1853             , (rc->rrdset && rc->rrdset->family)?rc->rrdset->family:""
1854             , (rc->rrdset)?"true":"false"
1855             , rc->exec?rc->exec:health_default_exec
1856             , rc->recipient?rc->recipient:health_default_recipient
1857             , rc->source
1858             , rc->units?rc->units:""
1859             , rc->info?rc->info:""
1860             , rrdcalc_status2string(rc->status)
1861             , (unsigned long)rc->last_status_change
1862             , (unsigned long)rc->last_updated
1863             , (unsigned long)rc->next_update
1864             , rc->update_every
1865             , rc->delay_up_duration
1866             , rc->delay_down_duration
1867             , rc->delay_max_duration
1868             , rc->delay_multiplier
1869             , rc->delay_last
1870             , (unsigned long)rc->delay_up_to_timestamp
1871     );
1872
1873     if(RRDCALC_HAS_DB_LOOKUP(rc)) {
1874         if(rc->dimensions && *rc->dimensions)
1875             health_string2json(wb, "\t\t\t", "lookup_dimensions", rc->dimensions, ",\n");
1876
1877         buffer_sprintf(wb,
1878                        "\t\t\t\"db_after\": %lu,\n"
1879                        "\t\t\t\"db_before\": %lu,\n"
1880                        "\t\t\t\"lookup_method\": \"%s\",\n"
1881                        "\t\t\t\"lookup_after\": %d,\n"
1882                        "\t\t\t\"lookup_before\": %d,\n"
1883                        "\t\t\t\"lookup_options\": \"",
1884                        (unsigned long) rc->db_after,
1885                        (unsigned long) rc->db_before,
1886                        group_method2string(rc->group),
1887                        rc->after,
1888                        rc->before
1889         );
1890         buffer_data_options2string(wb, rc->options);
1891         buffer_strcat(wb, "\",\n");
1892     }
1893
1894     if(rc->calculation) {
1895         health_string2json(wb, "\t\t\t", "calc", rc->calculation->source, ",\n");
1896         health_string2json(wb, "\t\t\t", "calc_parsed", rc->calculation->parsed_as, ",\n");
1897     }
1898
1899     if(rc->warning) {
1900         health_string2json(wb, "\t\t\t", "warn", rc->warning->source, ",\n");
1901         health_string2json(wb, "\t\t\t", "warn_parsed", rc->warning->parsed_as, ",\n");
1902     }
1903
1904     if(rc->critical) {
1905         health_string2json(wb, "\t\t\t", "crit", rc->critical->source, ",\n");
1906         health_string2json(wb, "\t\t\t", "crit_parsed", rc->critical->parsed_as, ",\n");
1907     }
1908
1909     buffer_strcat(wb, "\t\t\t\"green\":");
1910     buffer_rrd_value(wb, rc->green);
1911     buffer_strcat(wb, ",\n");
1912
1913     buffer_strcat(wb, "\t\t\t\"red\":");
1914     buffer_rrd_value(wb, rc->red);
1915     buffer_strcat(wb, ",\n");
1916
1917     buffer_strcat(wb, "\t\t\t\"value\":");
1918     buffer_rrd_value(wb, rc->value);
1919     buffer_strcat(wb, "\n");
1920
1921     buffer_strcat(wb, "\t\t}");
1922 }
1923
1924 //void health_rrdcalctemplate2json_nolock(BUFFER *wb, RRDCALCTEMPLATE *rt) {
1925 //
1926 //}
1927
1928 void health_alarms2json(RRDHOST *host, BUFFER *wb, int all) {
1929     int i;
1930
1931     rrdhost_rdlock(&localhost);
1932     buffer_sprintf(wb, "{\n\t\"hostname\": \"%s\","
1933                         "\n\t\"latest_alarm_log_unique_id\": %u,"
1934                         "\n\t\"status\": %s,"
1935                         "\n\t\"now\": %lu,"
1936                         "\n\t\"alarms\": {\n",
1937                         host->hostname,
1938                         (host->health_log.next_log_id > 0)?(host->health_log.next_log_id - 1):0,
1939                         health_enabled?"true":"false",
1940                         (unsigned long)time(NULL));
1941
1942     RRDCALC *rc;
1943     for(i = 0, rc = host->alarms; rc ; rc = rc->next) {
1944         if(unlikely(!rc->rrdset || !rc->rrdset->last_collected_time.tv_sec))
1945             continue;
1946
1947         if(likely(!all && !(rc->status == RRDCALC_STATUS_WARNING || rc->status == RRDCALC_STATUS_CRITICAL)))
1948             continue;
1949
1950         if(likely(i)) buffer_strcat(wb, ",\n");
1951         health_rrdcalc2json_nolock(wb, rc);
1952         i++;
1953     }
1954
1955 //    buffer_strcat(wb, "\n\t},\n\t\"templates\": {");
1956 //    RRDCALCTEMPLATE *rt;
1957 //    for(rt = host->templates; rt ; rt = rt->next)
1958 //        health_rrdcalctemplate2json_nolock(wb, rt);
1959
1960     buffer_strcat(wb, "\n\t}\n}\n");
1961     rrdhost_unlock(&localhost);
1962 }
1963
1964
1965 // ----------------------------------------------------------------------------
1966 // re-load health configuration
1967
1968 static inline void health_free_all_nolock(RRDHOST *host) {
1969     while(host->templates)
1970         rrdcalctemplate_free(host, host->templates);
1971
1972     while(host->alarms)
1973         rrdcalc_free(host, host->alarms);
1974 }
1975
1976 void health_reload(void) {
1977     if(!health_enabled) {
1978         error("Health reload is requested, but health is not enabled.");
1979         return;
1980     }
1981
1982     char *path = health_config_dir();
1983
1984     // free all running alarms
1985     rrdhost_rwlock(&localhost);
1986     health_free_all_nolock(&localhost);
1987     rrdhost_unlock(&localhost);
1988
1989     // invalidate all previous entries in the alarm log
1990     ALARM_ENTRY *t;
1991     for(t = localhost.health_log.alarms ; t ; t = t->next) {
1992         if(t->new_status != RRDCALC_STATUS_REMOVED)
1993             t->notifications |= HEALTH_ENTRY_NOTIFICATIONS_UPDATED;
1994     }
1995
1996     // reset all thresholds to all charts
1997     RRDSET *st;
1998     for(st = localhost.rrdset_root; st ; st = st->next) {
1999         st->green = NAN;
2000         st->red = NAN;
2001     }
2002
2003     // load the new alarms
2004     rrdhost_rwlock(&localhost);
2005     health_readdir(path);
2006     rrdhost_unlock(&localhost);
2007
2008     // link the loaded alarms to their charts
2009     for(st = localhost.rrdset_root; st ; st = st->next) {
2010         rrdhost_rwlock(&localhost);
2011
2012         rrdsetcalc_link_matching(st);
2013         rrdcalctemplate_link_matching(st);
2014
2015         rrdhost_unlock(&localhost);
2016     }
2017 }
2018
2019
2020 // ----------------------------------------------------------------------------
2021 // health main thread and friends
2022
2023 static inline int rrdcalc_value2status(calculated_number n) {
2024     if(isnan(n)) return RRDCALC_STATUS_UNDEFINED;
2025     if(n) return RRDCALC_STATUS_RAISED;
2026     return RRDCALC_STATUS_CLEAR;
2027 }
2028
2029 static inline void health_alarm_execute(RRDHOST *host, ALARM_ENTRY *ae) {
2030     ae->notifications |= HEALTH_ENTRY_NOTIFICATIONS_PROCESSED;
2031
2032     // find the previous notification for the same alarm
2033     ALARM_ENTRY *t;
2034     for(t = ae->next; t ;t = t->next) {
2035         if(t->alarm_id == ae->alarm_id && t->notifications & HEALTH_ENTRY_NOTIFICATIONS_EXEC_RUN)
2036             break;
2037     }
2038
2039     if(t && t->new_status == ae->new_status) {
2040         // don't send the same notification again
2041         info("Health not sending again notification for alarm '%s.%s' status %s", ae->chart, ae->name, rrdcalc_status2string(ae->new_status));
2042         return;
2043     }
2044
2045     if((ae->old_status == RRDCALC_STATUS_UNDEFINED && ae->new_status == RRDCALC_STATUS_UNINITIALIZED)
2046         || (ae->old_status == RRDCALC_STATUS_UNINITIALIZED && ae->new_status == RRDCALC_STATUS_CLEAR)) {
2047         info("Health not sending notification for first initialization of alarm '%s.%s' status %s", ae->chart, ae->name, rrdcalc_status2string(ae->new_status));
2048         return;
2049     }
2050
2051     char buffer[FILENAME_MAX + 1];
2052     pid_t command_pid;
2053
2054     const char *exec = ae->exec;
2055     if(!exec) exec = health_default_exec;
2056
2057     const char *recipient = ae->recipient;
2058     if(!recipient) recipient = health_default_recipient;
2059
2060     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'",
2061               exec,
2062               recipient,
2063               host->hostname,
2064               ae->unique_id,
2065               ae->alarm_id,
2066               ae->alarm_event_id,
2067               (unsigned long)ae->when,
2068               ae->name,
2069               ae->chart?ae->chart:"NOCAHRT",
2070               ae->family?ae->family:"NOFAMILY",
2071               rrdcalc_status2string(ae->new_status),
2072               rrdcalc_status2string(ae->old_status),
2073               ae->new_value,
2074               ae->old_value,
2075               ae->source?ae->source:"UNKNOWN",
2076               (uint32_t)ae->duration,
2077               (uint32_t)ae->non_clear_duration,
2078               ae->units?ae->units:"",
2079               ae->info?ae->info:""
2080     );
2081
2082     ae->notifications |= HEALTH_ENTRY_NOTIFICATIONS_EXEC_RUN;
2083     ae->exec_run_timestamp = time(NULL);
2084
2085     debug(D_HEALTH, "executing command '%s'", buffer);
2086     FILE *fp = mypopen(buffer, &command_pid);
2087     if(!fp) {
2088         error("HEALTH: Cannot popen(\"%s\", \"r\").", buffer);
2089         return;
2090     }
2091     debug(D_HEALTH, "HEALTH reading from command");
2092     char *s = fgets(buffer, FILENAME_MAX, fp);
2093     (void)s;
2094     ae->exec_code = mypclose(fp, command_pid);
2095     debug(D_HEALTH, "done executing command - returned with code %d", ae->exec_code);
2096
2097     if(ae->exec_code != 0)
2098         ae->notifications |= HEALTH_ENTRY_NOTIFICATIONS_EXEC_FAILED;
2099 }
2100
2101 static inline void health_process_notifications(RRDHOST *host, ALARM_ENTRY *ae) {
2102     info("Health alarm '%s.%s' = %0.2Lf - changed status from %s to %s",
2103          ae->chart?ae->chart:"NOCHART", ae->name,
2104          ae->new_value,
2105          rrdcalc_status2string(ae->old_status),
2106          rrdcalc_status2string(ae->new_status)
2107     );
2108
2109     health_alarm_execute(host, ae);
2110 }
2111
2112 static inline void health_alarm_log_process(RRDHOST *host) {
2113     static uint32_t stop_at_id = 0;
2114     uint32_t first_waiting = (host->health_log.alarms)?host->health_log.alarms->unique_id:0;
2115     time_t now = time(NULL);
2116
2117     pthread_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
2118
2119     ALARM_ENTRY *ae;
2120     for(ae = host->health_log.alarms; ae && ae->unique_id >= stop_at_id ; ae = ae->next) {
2121         if(unlikely(
2122             !(ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_PROCESSED) &&
2123             !(ae->notifications & HEALTH_ENTRY_NOTIFICATIONS_UPDATED)
2124             )) {
2125
2126             if(unlikely(ae->unique_id < first_waiting))
2127                 first_waiting = ae->unique_id;
2128
2129             if(likely(now >= ae->delay_up_to_timestamp))
2130                 health_process_notifications(host, ae);
2131         }
2132     }
2133
2134     // remember this for the next iteration
2135     stop_at_id = first_waiting;
2136
2137     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
2138
2139     if(host->health_log.count <= host->health_log.max)
2140         return;
2141
2142     // cleanup excess entries in the log
2143     pthread_rwlock_wrlock(&host->health_log.alarm_log_rwlock);
2144
2145     ALARM_ENTRY *last = NULL;
2146     unsigned int count = host->health_log.max * 2 / 3;
2147     for(ae = host->health_log.alarms; ae && count ; count--, last = ae, ae = ae->next) ;
2148
2149     if(ae && last && last->next == ae)
2150         last->next = NULL;
2151     else
2152         ae = NULL;
2153
2154     while(ae) {
2155         debug(D_HEALTH, "Health removing alarm log entry with id: %u", ae->unique_id);
2156
2157         ALARM_ENTRY *t = ae->next;
2158
2159         freez(ae->name);
2160         freez(ae->chart);
2161         freez(ae->family);
2162         freez(ae->exec);
2163         freez(ae->recipient);
2164         freez(ae->source);
2165         freez(ae->units);
2166         freez(ae->info);
2167         freez(ae);
2168
2169         ae = t;
2170         host->health_log.count--;
2171     }
2172
2173     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
2174 }
2175
2176 static inline int rrdcalc_isrunnable(RRDCALC *rc, time_t now, time_t *next_run) {
2177     if (unlikely(!rc->rrdset)) {
2178         debug(D_HEALTH, "Health not running alarm '%s.%s'. It is not linked to a chart.", rc->chart?rc->chart:"NOCHART", rc->name);
2179         return 0;
2180     }
2181
2182     if (unlikely(!rc->rrdset->last_collected_time.tv_sec)) {
2183         debug(D_HEALTH, "Health not running alarm '%s.%s'. Chart is not yet collected.", rc->chart?rc->chart:"NOCHART", rc->name);
2184         return 0;
2185     }
2186
2187     if (unlikely(!rc->update_every)) {
2188         debug(D_HEALTH, "Health not running alarm '%s.%s'. It does not have an update frequency", rc->chart?rc->chart:"NOCHART", rc->name);
2189         return 0;
2190     }
2191
2192     if (unlikely(rc->next_update > now)) {
2193         if (unlikely(*next_run > rc->next_update))
2194             *next_run = rc->next_update;
2195
2196         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));
2197         return 0;
2198     }
2199
2200     // FIXME
2201     // we should check that the DB lookup is possible
2202     // i.e.
2203     // - the duration of the chart includes the required timeframe
2204     // we SHOULD NOT check the dimensions - there might be alarms that refer non-existing dimensions (e.g. cpu steal)
2205
2206     return 1;
2207 }
2208
2209 void *health_main(void *ptr) {
2210     (void)ptr;
2211
2212     info("HEALTH thread created with task id %d", gettid());
2213
2214     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
2215         error("Cannot set pthread cancel type to DEFERRED.");
2216
2217     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
2218         error("Cannot set pthread cancel state to ENABLE.");
2219
2220     int min_run_every = (int)config_get_number("health", "run at least every seconds", 10);
2221     if(min_run_every < 1) min_run_every = 1;
2222
2223     BUFFER *wb = buffer_create(100);
2224
2225     unsigned int loop = 0;
2226     while(health_enabled) {
2227         loop++;
2228         debug(D_HEALTH, "Health monitoring iteration no %u started", loop);
2229
2230         int oldstate, runnable = 0;
2231         time_t now = time(NULL);
2232         time_t next_run = now + min_run_every;
2233         RRDCALC *rc;
2234
2235         if (unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) != 0))
2236             error("Cannot set pthread cancel state to DISABLE.");
2237
2238         rrdhost_rdlock(&localhost);
2239
2240         // the first loop is to lookup values from the db
2241         for (rc = localhost.alarms; rc; rc = rc->next) {
2242             if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
2243                 continue;
2244
2245             runnable++;
2246             rc->old_value = rc->value;
2247
2248             // 1. if there is database lookup, do it
2249             // 2. if there is calculation expression, run it
2250
2251             if (unlikely(RRDCALC_HAS_DB_LOOKUP(rc))) {
2252                 time_t old_db_timestamp = rc->db_before;
2253                 int value_is_null = 0;
2254
2255                 int ret = rrd2value(rc->rrdset, wb, &rc->value,
2256                                     rc->dimensions, 1, rc->after, rc->before, rc->group,
2257                                     rc->options, &rc->db_after, &rc->db_before, &value_is_null);
2258
2259                 if (unlikely(ret != 200)) {
2260                     // database lookup failed
2261                     rc->value = NAN;
2262
2263                     debug(D_HEALTH, "Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
2264
2265                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_DB_ERROR))) {
2266                         rc->rrdcalc_flags |= RRDCALC_FLAG_DB_ERROR;
2267                         error("Health alarm '%s.%s': database lookup returned error %d", rc->chart?rc->chart:"NOCHART", rc->name, ret);
2268                     }
2269                 }
2270                 else if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_DB_ERROR))
2271                     rc->rrdcalc_flags &= ~RRDCALC_FLAG_DB_ERROR;
2272
2273                 if (unlikely(old_db_timestamp == rc->db_before)) {
2274                     // database is stale
2275
2276                     debug(D_HEALTH, "Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
2277
2278                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_DB_STALE))) {
2279                         rc->rrdcalc_flags |= RRDCALC_FLAG_DB_STALE;
2280                         error("Health alarm '%s.%s': database is stale", rc->chart?rc->chart:"NOCHART", rc->name);
2281                     }
2282                 }
2283                 else if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_DB_STALE))
2284                     rc->rrdcalc_flags &= ~RRDCALC_FLAG_DB_STALE;
2285
2286                 if (unlikely(value_is_null)) {
2287                     // collected value is null
2288
2289                     rc->value = NAN;
2290
2291                     debug(D_HEALTH, "Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
2292                           rc->chart?rc->chart:"NOCHART", rc->name);
2293
2294                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_DB_NAN))) {
2295                         rc->rrdcalc_flags |= RRDCALC_FLAG_DB_NAN;
2296                         error("Health alarm '%s.%s': database lookup returned empty value (possibly value is not collected yet)",
2297                               rc->chart?rc->chart:"NOCHART", rc->name);
2298                     }
2299                 }
2300                 else if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_DB_NAN))
2301                     rc->rrdcalc_flags &= ~RRDCALC_FLAG_DB_NAN;
2302
2303                 debug(D_HEALTH, "Health alarm '%s.%s': database lookup gave value "
2304                         CALCULATED_NUMBER_FORMAT, rc->chart?rc->chart:"NOCHART", rc->name, rc->value);
2305             }
2306
2307             if(unlikely(rc->calculation)) {
2308                 if (unlikely(!expression_evaluate(rc->calculation))) {
2309                     // calculation failed
2310
2311                     rc->value = NAN;
2312
2313                     debug(D_HEALTH, "Health alarm '%s.%s': failed to evaluate calculation with error: %s",
2314                           rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
2315
2316                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_CALC_ERROR))) {
2317                         rc->rrdcalc_flags |= RRDCALC_FLAG_CALC_ERROR;
2318                         error("Health alarm '%s.%s': failed to evaluate calculation with error: %s",
2319                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
2320                     }
2321                 }
2322                 else {
2323                     if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_CALC_ERROR))
2324                         rc->rrdcalc_flags &= ~RRDCALC_FLAG_CALC_ERROR;
2325
2326                     debug(D_HEALTH, "Health alarm '%s.%s': calculation expression gave value "
2327                             CALCULATED_NUMBER_FORMAT
2328                             ": %s (source: %s)",
2329                           rc->chart?rc->chart:"NOCHART", rc->name,
2330                           rc->calculation->result,
2331                           buffer_tostring(rc->calculation->error_msg),
2332                           rc->source
2333                     );
2334
2335                     rc->value = rc->calculation->result;
2336                 }
2337             }
2338         }
2339         rrdhost_unlock(&localhost);
2340
2341         if (runnable) {
2342             rrdhost_rdlock(&localhost);
2343
2344             for (rc = localhost.alarms; rc; rc = rc->next) {
2345                 if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
2346                     continue;
2347
2348                 int warning_status  = RRDCALC_STATUS_UNDEFINED;
2349                 int critical_status = RRDCALC_STATUS_UNDEFINED;
2350
2351                 if(likely(rc->warning)) {
2352                     if(unlikely(!expression_evaluate(rc->warning))) {
2353                         // calculation failed
2354
2355                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression failed with error: %s",
2356                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
2357
2358                         if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_WARN_ERROR))) {
2359                             rc->rrdcalc_flags |= RRDCALC_FLAG_WARN_ERROR;
2360                             error("Health alarm '%s.%s': warning expression failed with error: %s",
2361                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->warning->error_msg));
2362                         }
2363                     }
2364                     else {
2365                         if(unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_WARN_ERROR))
2366                             rc->rrdcalc_flags &= ~RRDCALC_FLAG_WARN_ERROR;
2367
2368                         debug(D_HEALTH, "Health alarm '%s.%s': warning expression gave value "
2369                                 CALCULATED_NUMBER_FORMAT
2370                                 ": %s (source: %s)",
2371                               rc->chart?rc->chart:"NOCHART", rc->name,
2372                               rc->warning->result,
2373                               buffer_tostring(rc->warning->error_msg),
2374                               rc->source
2375                         );
2376
2377                         warning_status = rrdcalc_value2status(rc->warning->result);
2378                     }
2379                 }
2380
2381                 if(likely(rc->critical)) {
2382                     if(unlikely(!expression_evaluate(rc->critical))) {
2383                         // calculation failed
2384
2385                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression failed with error: %s",
2386                               rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
2387
2388                         if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_CRIT_ERROR))) {
2389                             rc->rrdcalc_flags |= RRDCALC_FLAG_CRIT_ERROR;
2390                             error("Health alarm '%s.%s': critical expression failed with error: %s",
2391                                   rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->critical->error_msg));
2392                         }
2393                     }
2394                     else {
2395                         if(unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_CRIT_ERROR))
2396                             rc->rrdcalc_flags &= ~RRDCALC_FLAG_CRIT_ERROR;
2397
2398                         debug(D_HEALTH, "Health alarm '%s.%s': critical expression gave value "
2399                                 CALCULATED_NUMBER_FORMAT
2400                                 ": %s (source: %s)",
2401                               rc->chart?rc->chart:"NOCHART", rc->name,
2402                               rc->critical->result,
2403                               buffer_tostring(rc->critical->error_msg),
2404                               rc->source
2405                         );
2406
2407                         critical_status = rrdcalc_value2status(rc->critical->result);
2408                     }
2409                 }
2410
2411                 int status = RRDCALC_STATUS_UNDEFINED;
2412
2413                 switch(warning_status) {
2414                     case RRDCALC_STATUS_CLEAR:
2415                         status = RRDCALC_STATUS_CLEAR;
2416                         break;
2417
2418                     case RRDCALC_STATUS_RAISED:
2419                         status = RRDCALC_STATUS_WARNING;
2420                         break;
2421
2422                     default:
2423                         break;
2424                 }
2425
2426                 switch(critical_status) {
2427                     case RRDCALC_STATUS_CLEAR:
2428                         if(status == RRDCALC_STATUS_UNDEFINED)
2429                             status = RRDCALC_STATUS_CLEAR;
2430                         break;
2431
2432                     case RRDCALC_STATUS_RAISED:
2433                         status = RRDCALC_STATUS_CRITICAL;
2434                         break;
2435
2436                     default:
2437                         break;
2438                 }
2439
2440                 if(status != rc->status) {
2441                     int delay = 0;
2442
2443                     if(now > rc->delay_up_to_timestamp) {
2444                         rc->delay_up_current = rc->delay_up_duration;
2445                         rc->delay_down_current = rc->delay_down_duration;
2446                         rc->delay_last = 0;
2447                         rc->delay_up_to_timestamp = 0;
2448                     }
2449                     else {
2450                         rc->delay_up_current = (int)(rc->delay_up_current * rc->delay_multiplier);
2451                         if(rc->delay_up_current > rc->delay_max_duration) rc->delay_up_current = rc->delay_max_duration;
2452
2453                         rc->delay_down_current = (int)(rc->delay_down_current * rc->delay_multiplier);
2454                         if(rc->delay_down_current > rc->delay_max_duration) rc->delay_down_current = rc->delay_max_duration;
2455                     }
2456
2457                     if(status > rc->status)
2458                         delay = rc->delay_up_current;
2459                     else
2460                         delay = rc->delay_down_current;
2461
2462                     // COMMENTED: because we do need to send raising alarms
2463                     // if(now + delay < rc->delay_up_to_timestamp)
2464                     //    delay = (int)(rc->delay_up_to_timestamp - now);
2465
2466                     rc->delay_last = delay;
2467                     rc->delay_up_to_timestamp = now + delay;
2468                     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);
2469                     rc->last_status_change = now;
2470                     rc->status = status;
2471                 }
2472
2473                 rc->last_updated = now;
2474                 rc->next_update = now + rc->update_every;
2475
2476                 if (next_run > rc->next_update)
2477                     next_run = rc->next_update;
2478             }
2479
2480             rrdhost_unlock(&localhost);
2481         }
2482
2483         if (unlikely(pthread_setcancelstate(oldstate, NULL) != 0))
2484             error("Cannot set pthread cancel state to RESTORE (%d).", oldstate);
2485
2486         // execute notifications
2487         // and cleanup
2488         health_alarm_log_process(&localhost);
2489
2490         now = time(NULL);
2491         if(now < next_run) {
2492             debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration in %d secs",
2493                   loop, (int) (next_run - now));
2494             sleep_usec(1000000 * (unsigned long long) (next_run - now));
2495         }
2496         else {
2497             debug(D_HEALTH, "Health monitoring iteration no %u done. Next iteration now", loop);
2498         }
2499     }
2500
2501     buffer_free(wb);
2502
2503     info("HEALTH thread exiting");
2504     pthread_exit(NULL);
2505     return NULL;
2506 }