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