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