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