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