]> arthur.barton.de Git - netdata.git/blobdiff - src/health.c
improvements identified via static code analysis with cppcheck
[netdata.git] / src / health.c
index 55a1d784116daa8671f060cf53e1b10ec1ffb4aa..280c913f41a92d8c4f686c42f87e832dec299007 100644 (file)
@@ -6,6 +6,7 @@ struct health_options {
     const char *health_default_exec;
     const char *health_default_recipient;
     const char *log_filename;
+    size_t log_entries_written;
     FILE *log_fp;
 };
 
@@ -13,6 +14,7 @@ static struct health_options health = {
     .health_default_exec = PLUGINS_DIR "/alarm-notify.sh",
     .health_default_recipient = "root",
     .log_filename = VARLIB_DIR "/health/alarm_log.db",
+    .log_entries_written = 0,
     .log_fp = NULL
 };
 
@@ -30,11 +32,11 @@ static inline int health_alarm_log_open(void) {
 
     if(health.log_fp) {
         if (setvbuf(health.log_fp, NULL, _IOLBF, 0) != 0)
-            error("Cannot set line buffering on health log file.");
+            error("Health: cannot set line buffering on health log file.");
         return 0;
     }
 
-    error("Cannot open health log file '%s'. Health data will be lost in case of netdata or server crash.", health.log_filename);
+    error("Health: cannot open health log file '%s'. Health data will be lost in case of netdata or server crash.", health.log_filename);
     return -1;
 }
 
@@ -45,24 +47,46 @@ static inline void health_alarm_log_close(void) {
     }
 }
 
-static inline void health_log_recreate(void) {
-    if(health.log_fp != NULL) {
+static inline void health_log_rotate(void) {
+    static size_t rotate_every = 0;
+
+    if(unlikely(rotate_every == 0)) {
+        rotate_every = (size_t)config_get_number("health", "rotate log every lines", 2000);
+        if(rotate_every < 100) rotate_every = 100;
+    }
+
+    if(unlikely(health.log_entries_written > rotate_every)) {
         health_alarm_log_close();
 
+        char old_filename[FILENAME_MAX + 1];
+        snprintfz(old_filename, FILENAME_MAX, "%s.old", health.log_filename);
+
+        if(unlink(old_filename) == -1 && errno != ENOENT)
+            error("Health: cannot remove old alarms log file '%s'", old_filename);
+
+        if(link(health.log_filename, old_filename) == -1 && errno != ENOENT)
+            error("Health: cannot move file '%s' to '%s'.", health.log_filename, old_filename);
+
+        if(unlink(health.log_filename) == -1 && errno != ENOENT)
+            error("Health: cannot remove old alarms log file '%s'", health.log_filename);
+
         // open it with truncate
         health.log_fp = fopen(health.log_filename, "w");
-        if(health.log_fp) fclose(health.log_fp);
-        else error("Cannot truncate health log '%s'", health.log_filename);
+
+        if(health.log_fp)
+            fclose(health.log_fp);
+        else
+            error("Health: cannot truncate health log '%s'", health.log_filename);
 
         health.log_fp = NULL;
 
+        health.log_entries_written = 0;
         health_alarm_log_open();
     }
 }
 
 static inline void health_alarm_log_save(RRDHOST *host, ALARM_ENTRY *ae) {
-    (void)host;
-    (void)ae;
+    health_log_rotate();
 
     if(likely(health.log_fp)) {
         if(unlikely(fprintf(health.log_fp
@@ -108,153 +132,224 @@ static inline void health_alarm_log_save(RRDHOST *host, ALARM_ENTRY *ae) {
                 , (long double)ae->old_value
         ) < 0))
             error("Health: failed to save alarm log entry. Health data may be lost in case of abnormal restart.");
-        else
+        else {
             ae->flags |= HEALTH_ENTRY_FLAG_SAVED;
+            health.log_entries_written++;
+        }
     }
 }
 
-static inline void health_alarm_log_load(RRDHOST *host) {
-    (void)host;
+static inline ssize_t health_alarm_log_read(RRDHOST *host, FILE *fp, const char *filename) {
+    static uint32_t max_unique_id = 0, max_alarm_id = 0;
 
-    health_alarm_log_close();
+    errno = 0;
 
-    FILE *fp = fopen(health.log_filename, "r");
-    if(!fp)
-        error("Registry: cannot open health file: %s", health.log_filename);
-    else {
-        errno = 0;
-
-        char *s, *buf = mallocz(65536 + 1);
-        size_t line = 0;
-        size_t len = 0;
-
-        while((s = fgets_trim_len(buf, 65536, fp, &len))) {
-            line++;
-            // fprintf(stderr, "line %zu: '%s'\n", line, s);
-
-            int max_entries = 30, entries = 0;
-            char *pointers[max_entries];
-
-            pointers[entries++] = s;
-            while(*s) {
-                if(unlikely(*s == '\t')) {
-                    *s = '\0';
-                    pointers[entries++] = s;
-                    if(entries > max_entries) {
-                        error("Line %zu of file '%s' has more than %d entries. Ignoring excessive entries.", line, health.log_filename, max_entries);
-                        break;
-                    }
+    char *s, *buf = mallocz(65536 + 1);
+    size_t line = 0, len = 0;
+    ssize_t loaded = 0, updated = 0, errored = 0, duplicate = 0;
+
+    pthread_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
+
+    while((s = fgets_trim_len(buf, 65536, fp, &len))) {
+        health.log_entries_written++;
+        line++;
+
+        int max_entries = 30, entries = 0;
+        char *pointers[max_entries];
+
+        pointers[entries++] = s++;
+        while(*s) {
+            if(unlikely(*s == '\t')) {
+                *s = '\0';
+                pointers[entries++] = ++s;
+                if(entries >= max_entries) {
+                    error("Health: line %zu of file '%s' has more than %d entries. Ignoring excessive entries.", line, filename, max_entries);
+                    break;
                 }
-                s++;
             }
+            else s++;
+        }
 
-            if(likely(*pointers[0] == 'U' || *pointers[0] == 'A')) {
-                ALARM_ENTRY *ae = NULL;
+        if(likely(*pointers[0] == 'U' || *pointers[0] == 'A')) {
+            ALARM_ENTRY *ae = NULL;
 
-                if(entries < 26) {
-                    error("Line %zu of file '%s' should have at least 26 entries, but it has %d. Ignoring line.", line, health.log_filename, entries);
-                    continue;
-                }
+            if(entries < 26) {
+                error("Health: line %zu of file '%s' should have at least 26 entries, but it has %d. Ignoring it.", line, filename, entries);
+                errored++;
+                continue;
+            }
 
-                // if this is an update, find it
-                if(unlikely(*pointers[0] == 'U')) {
-                    uint32_t unique_id = (uint32_t)strtoul(pointers[2], NULL, 16);
+            // check that we have valid ids
+            uint32_t unique_id = (uint32_t)strtoul(pointers[2], NULL, 16);
+            if(!unique_id) {
+                error("Health: line %zu of file '%s' states alarm entry with invalid unique id %u (%s). Ignoring it.", line, filename, unique_id, pointers[2]);
+                errored++;
+                continue;
+            }
 
-                    // fprintf(stderr, "searching for alarm entry with unique id %u\n", unique_id);
+            uint32_t alarm_id = (uint32_t)strtoul(pointers[3], NULL, 16);
+            if(!alarm_id) {
+                error("Health: line %zu of file '%s' states alarm entry for invalid alarm id %u (%s). Ignoring it.", line, filename, alarm_id, pointers[3]);
+                errored++;
+                continue;
+            }
 
-                    // find it
-                    for(ae = host->health_log.alarms; ae ;ae = ae->next) {
-                        if(unlikely(ae->unique_id == unique_id)) break;
-                    }
+            if(unlikely(*pointers[0] == 'A')) {
+                // make sure it is properly numbered
+                if(unlikely(host->health_log.alarms && unique_id < host->health_log.alarms->unique_id)) {
+                    error("Health: line %zu of file '%s' has alarm log entry with %u in wrong order. Ignoring it.", line, filename, unique_id);
+                    errored++;
+                    continue;
+                }
 
-                    if(!ae) {
-                        *pointers[0] = 'A';
-                        error("Line %zu of file '%s' updates alarm log entry with unique id %u, but it is not found.", line, health.log_filename, unique_id);
+                ae = callocz(1, sizeof(ALARM_ENTRY));
+            }
+            else if(unlikely(*pointers[0] == 'U')) {
+                // find the original
+                for(ae = host->health_log.alarms; ae; ae = ae->next) {
+                    if(unlikely(unique_id == ae->unique_id)) {
+                        if(unlikely(*pointers[0] == 'A')) {
+                            error("Health: line %zu of file '%s' adds duplicate alarm log entry with unique id %u. Using the later."
+                                  , line, filename, unique_id);
+                            *pointers[0] = 'U';
+                            duplicate++;
+                        }
+                        break;
+                    }
+                    else if(unlikely(unique_id > ae->unique_id)) {
+                        // no need to continue
+                        // the linked list is sorted
+                        ae = NULL;
+                        break;
                     }
                 }
 
-                // create a new one
-                if(likely(!ae)) {
-                    ae = callocz(1, sizeof(ALARM_ENTRY));
+                // if not found, skip this line
+                if(!ae) {
+                    // error("Health: line %zu of file '%s' updates alarm log entry with unique id %u, but it is not found.", line, filename, unique_id);
+                    continue;
                 }
+            }
 
-                if(strcmp(pointers[1], host->hostname))
-                    error("Line %zu of file '%s' provides an alarm for host '%s' but this is named '%s'.", line, health.log_filename, pointers[1], host->hostname);
+            // check for a possible host missmatch
+            //if(strcmp(pointers[1], host->hostname))
+            //    error("Health: line %zu of file '%s' provides an alarm for host '%s' but this is named '%s'.", line, filename, pointers[1], host->hostname);
 
-                ae->unique_id               = (uint32_t)strtoul(pointers[2], NULL, 16);
-                ae->alarm_id                = (uint32_t)strtoul(pointers[3], NULL, 16);
-                ae->alarm_event_id          = (uint32_t)strtoul(pointers[4], NULL, 16);
-                ae->updated_by_id           = (uint32_t)strtoul(pointers[5], NULL, 16);
-                ae->updates_id              = (uint32_t)strtoul(pointers[6], NULL, 16);
+            ae->unique_id               = unique_id;
+            ae->alarm_id                = alarm_id;
+            ae->alarm_event_id          = (uint32_t)strtoul(pointers[4], NULL, 16);
+            ae->updated_by_id           = (uint32_t)strtoul(pointers[5], NULL, 16);
+            ae->updates_id              = (uint32_t)strtoul(pointers[6], NULL, 16);
 
-                ae->when                    = (uint32_t)strtoul(pointers[7], NULL, 16);
-                ae->duration                = (uint32_t)strtoul(pointers[8], NULL, 16);
-                ae->non_clear_duration      = (uint32_t)strtoul(pointers[9], NULL, 16);
-                ae->flags                   = (uint32_t)strtoul(pointers[10], NULL, 16);
-                ae->exec_run_timestamp      = (uint32_t)strtoul(pointers[11], NULL, 16);
-                ae->delay_up_to_timestamp   = (uint32_t)strtoul(pointers[12], NULL, 16);
+            ae->when                    = (uint32_t)strtoul(pointers[7], NULL, 16);
+            ae->duration                = (uint32_t)strtoul(pointers[8], NULL, 16);
+            ae->non_clear_duration      = (uint32_t)strtoul(pointers[9], NULL, 16);
 
-                if(unlikely(ae->name)) freez(ae->name);
-                ae->name = strdupz(pointers[13]);
+            ae->flags                   = (uint32_t)strtoul(pointers[10], NULL, 16);
+            ae->flags |= HEALTH_ENTRY_FLAG_SAVED;
 
-                if(unlikely(ae->chart)) freez(ae->chart);
-                ae->chart = strdupz(pointers[14]);
+            ae->exec_run_timestamp      = (uint32_t)strtoul(pointers[11], NULL, 16);
+            ae->delay_up_to_timestamp   = (uint32_t)strtoul(pointers[12], NULL, 16);
 
-                if(unlikely(ae->family)) freez(ae->family);
-                ae->family = strdupz(pointers[15]);
+            if(unlikely(ae->name)) freez(ae->name);
+            ae->name = strdupz(pointers[13]);
+            ae->hash_name = simple_hash(ae->name);
 
-                if(unlikely(ae->exec)) freez(ae->exec);
-                ae->exec = strdupz(pointers[16]);
-                if(!*ae->exec) { freez(ae->exec); ae->exec = NULL; }
+            if(unlikely(ae->chart)) freez(ae->chart);
+            ae->chart = strdupz(pointers[14]);
+            ae->hash_chart = simple_hash(ae->chart);
 
-                if(unlikely(ae->recipient)) freez(ae->recipient);
-                ae->recipient = strdupz(pointers[17]);
-                if(!*ae->recipient) { freez(ae->recipient); ae->recipient = NULL; }
+            if(unlikely(ae->family)) freez(ae->family);
+            ae->family = strdupz(pointers[15]);
 
-                if(unlikely(ae->source)) freez(ae->source);
-                ae->source = strdupz(pointers[18]);
-                if(!*ae->source) { freez(ae->source); ae->source = NULL; }
+            if(unlikely(ae->exec)) freez(ae->exec);
+            ae->exec = strdupz(pointers[16]);
+            if(!*ae->exec) { freez(ae->exec); ae->exec = NULL; }
 
-                if(unlikely(ae->units)) freez(ae->units);
-                ae->units = strdupz(pointers[19]);
-                if(!*ae->units) { freez(ae->units); ae->units = NULL; }
+            if(unlikely(ae->recipient)) freez(ae->recipient);
+            ae->recipient = strdupz(pointers[17]);
+            if(!*ae->recipient) { freez(ae->recipient); ae->recipient = NULL; }
 
-                if(unlikely(ae->info)) freez(ae->info);
-                ae->info = strdupz(pointers[20]);
-                if(!*ae->info) { freez(ae->info); ae->info = NULL; }
+            if(unlikely(ae->source)) freez(ae->source);
+            ae->source = strdupz(pointers[18]);
+            if(!*ae->source) { freez(ae->source); ae->source = NULL; }
 
-                ae->exec_code   = atoi(pointers[21]);
-                ae->new_status  = atoi(pointers[22]);
-                ae->old_status  = atoi(pointers[23]);
-                ae->delay       = atoi(pointers[24]);
+            if(unlikely(ae->units)) freez(ae->units);
+            ae->units = strdupz(pointers[19]);
+            if(!*ae->units) { freez(ae->units); ae->units = NULL; }
 
-                ae->new_value   = strtold(pointers[25], NULL);
-                ae->old_value   = strtold(pointers[26], NULL);
+            if(unlikely(ae->info)) freez(ae->info);
+            ae->info = strdupz(pointers[20]);
+            if(!*ae->info) { freez(ae->info); ae->info = NULL; }
 
-                // add it to host if not already there
-                if(unlikely(*pointers[0] == 'A')) {
-                    ae->next = host->health_log.alarms;
-                    host->health_log.alarms = ae;
-                }
+            ae->exec_code   = atoi(pointers[21]);
+            ae->new_status  = atoi(pointers[22]);
+            ae->old_status  = atoi(pointers[23]);
+            ae->delay       = atoi(pointers[24]);
 
-                if(unlikely(ae->unique_id >= host->health_log.next_log_id))
-                    host->health_log.next_log_id = ae->unique_id + 1;
+            ae->new_value   = strtold(pointers[25], NULL);
+            ae->old_value   = strtold(pointers[26], NULL);
 
-                if(unlikely(ae->alarm_id >= host->health_log.next_alarm_id))
-                    host->health_log.next_alarm_id = ae->alarm_id + 1;
-            }
-            else {
-                error("Line %zu of file '%s' is invalid (unrecognized entry type '%s').", line, health.log_filename, pointers[0]);
+            // add it to host if not already there
+            if(unlikely(*pointers[0] == 'A')) {
+                ae->next = host->health_log.alarms;
+                host->health_log.alarms = ae;
+                loaded++;
             }
+            else updated++;
+
+            if(unlikely(ae->unique_id > max_unique_id))
+                max_unique_id = ae->unique_id;
+
+            if(unlikely(ae->alarm_id >= max_alarm_id))
+                max_alarm_id = ae->alarm_id;
         }
+        else {
+            error("Health: line %zu of file '%s' is invalid (unrecognized entry type '%s').", line, filename, pointers[0]);
+            errored++;
+        }
+    }
+
+    pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
+
+    freez(buf);
+
+    if(!max_unique_id) max_unique_id = (uint32_t)time(NULL);
+    if(!max_alarm_id)  max_alarm_id  = (uint32_t)time(NULL);
 
-        freez(buf);
+    host->health_log.next_log_id = max_unique_id + 1;
+    host->health_log.next_alarm_id = max_alarm_id + 1;
+
+    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);
+    return loaded;
+}
+
+static inline void health_alarm_log_load(RRDHOST *host) {
+    health_alarm_log_close();
+
+    char filename[FILENAME_MAX + 1];
+    snprintfz(filename, FILENAME_MAX, "%s.old", health.log_filename);
+    FILE *fp = fopen(filename, "r");
+    if(!fp)
+        error("Health: cannot open health file: %s", filename);
+    else {
+        health_alarm_log_read(host, fp, filename);
+        fclose(fp);
+    }
+
+    health.log_entries_written = 0;
+    fp = fopen(health.log_filename, "r");
+    if(!fp)
+        error("Health: cannot open health file: %s", health.log_filename);
+    else {
+        health_alarm_log_read(host, fp, health.log_filename);
         fclose(fp);
     }
 
     health_alarm_log_open();
 }
 
+
 // ----------------------------------------------------------------------------
 // health alarm log management
 
@@ -328,10 +423,9 @@ static inline void health_alarm_log(RRDHOST *host,
 
                 health_alarm_log_save(host, t);
             }
-            else {
-                // no need to continue
-                break;
-            }
+
+            // no need to continue
+            break;
         }
     }
     pthread_rwlock_unlock(&host->health_log.alarm_log_rwlock);
@@ -391,14 +485,17 @@ static inline void rrdvar_free(RRDHOST *host, avl_tree_lock *tree, RRDVAR *rv) {
 
     if(!rv) return;
 
-    if(tree)
-        rrdvar_index_del(tree, rv);
+    if(tree) {
+        debug(D_VARIABLES, "Deleting variable '%s'", rv->name);
+        if(unlikely(!rrdvar_index_del(tree, rv)))
+            error("Attempted to delete variable '%s' from host '%s', but it is not found.", rv->name, host->hostname);
+    }
 
     freez(rv->name);
     freez(rv);
 }
 
-static inline RRDVAR *rrdvar_create_and_index(const char *scope, avl_tree_lock *tree, const char *name, int type, calculated_number *value) {
+static inline RRDVAR *rrdvar_create_and_index(const char *scope, avl_tree_lock *tree, const char *name, int type, void *value) {
     char *variable = strdupz(name);
     rrdvar_fix_name(variable);
     uint32_t hash = simple_hash(variable);
@@ -423,19 +520,83 @@ static inline RRDVAR *rrdvar_create_and_index(const char *scope, avl_tree_lock *
             debug(D_VARIABLES, "Variable '%s' created in scope '%s'", variable, scope);
     }
     else {
+        debug(D_VARIABLES, "Variable '%s' is already found in scope '%s'.", variable, scope);
+
         // already exists
         freez(variable);
+
+        // this is important
+        // it must return NULL - not the existing variable - or double-free will happen
         rv = NULL;
     }
 
     return rv;
 }
 
+// ----------------------------------------------------------------------------
+// CUSTOM VARIABLES
+
+RRDVAR *rrdvar_custom_host_variable_create(RRDHOST *host, const char *name) {
+    calculated_number *v = callocz(1, sizeof(calculated_number));
+    *v = NAN;
+    RRDVAR *rv = rrdvar_create_and_index("host", &host->variables_root_index, name, RRDVAR_TYPE_CALCULATED_ALLOCATED, v);
+    if(unlikely(!rv)) {
+        free(v);
+        error("Requested variable '%s' already exists - possibly 2 plugins will be updating it at the same time", name);
+
+        char *variable = strdupz(name);
+        rrdvar_fix_name(variable);
+        uint32_t hash = simple_hash(variable);
+
+        rv = rrdvar_index_find(&host->variables_root_index, variable, hash);
+    }
+
+    return rv;
+}
+
+void rrdvar_custom_host_variable_destroy(RRDHOST *host, const char *name) {
+    char *variable = strdupz(name);
+    rrdvar_fix_name(variable);
+    uint32_t hash = simple_hash(variable);
+
+    RRDVAR *rv = rrdvar_index_find(&host->variables_root_index, variable, hash);
+    freez(variable);
+
+    if(!rv) {
+        error("Attempted to remove variable '%s' from host '%s', but it does not exist.", name, host->hostname);
+        return;
+    }
+
+    if(rv->type != RRDVAR_TYPE_CALCULATED_ALLOCATED) {
+        error("Attempted to remove variable '%s' from host '%s', but it does not a custom allocated variable.", name, host->hostname);
+        return;
+    }
+
+    if(!rrdvar_index_del(&host->variables_root_index, rv)) {
+        error("Attempted to remove variable '%s' from host '%s', but it cannot be found.", name, host->hostname);
+        return;
+    }
+
+    freez(rv->name);
+    freez(rv->value);
+    freez(rv);
+}
+
+void rrdvar_custom_host_variable_set(RRDVAR *rv, calculated_number value) {
+    if(rv->type != RRDVAR_TYPE_CALCULATED_ALLOCATED)
+        error("requested to set variable '%s' to value " CALCULATED_NUMBER_FORMAT " but the variable is not a custom one.", rv->name, value);
+    else {
+        calculated_number *v = rv->value;
+        *v = value;
+    }
+}
+
 // ----------------------------------------------------------------------------
 // RRDVAR lookup
 
-calculated_number rrdvar2number(RRDVAR *rv) {
+static calculated_number rrdvar2number(RRDVAR *rv) {
     switch(rv->type) {
+        case RRDVAR_TYPE_CALCULATED_ALLOCATED:
         case RRDVAR_TYPE_CALCULATED: {
             calculated_number *n = (calculated_number *)rv->value;
             return *n;
@@ -467,11 +628,6 @@ calculated_number rrdvar2number(RRDVAR *rv) {
     }
 }
 
-void dump_variable(void *data) {
-    RRDVAR *rv = (RRDVAR *)data;
-    debug(D_HEALTH, "%50s : %20.5Lf", rv->name, rrdvar2number(rv));
-}
-
 int health_variable_lookup(const char *variable, uint32_t hash, RRDCALC *rc, calculated_number *result) {
     RRDSET *st = rc->rrdset;
     RRDVAR *rv;
@@ -496,162 +652,217 @@ int health_variable_lookup(const char *variable, uint32_t hash, RRDCALC *rc, cal
         return 1;
     }
 
-    debug(D_HEALTH, "Available local chart '%s' variables:", st->id);
-    avl_traverse_lock(&st->variables_root_index, dump_variable);
+    return 0;
+}
 
-    debug(D_HEALTH, "Available family '%s' variables:", st->rrdfamily->family);
-    avl_traverse_lock(&st->rrdfamily->variables_root_index, dump_variable);
+// ----------------------------------------------------------------------------
+// RRDVAR to JSON
 
-    debug(D_HEALTH, "Available host '%s' variables:", st->rrdhost->hostname);
-    avl_traverse_lock(&st->rrdhost->variables_root_index, dump_variable);
+struct variable2json_helper {
+    BUFFER *buf;
+    size_t counter;
+};
 
-    return 0;
+static void single_variable2json(void *entry, void *data) {
+    struct variable2json_helper *helper = (struct variable2json_helper *)data;
+    RRDVAR *rv = (RRDVAR *)entry;
+    calculated_number value = rrdvar2number(rv);
+
+    if(unlikely(isnan(value) || isinf(value)))
+        buffer_sprintf(helper->buf, "%s\n\t\t\"%s\": null", helper->counter?",":"", rv->name);
+    else
+        buffer_sprintf(helper->buf, "%s\n\t\t\"%s\": %0.5Lf", helper->counter?",":"", rv->name, (long double)value);
+
+    helper->counter++;
+}
+
+void health_api_v1_chart_variables2json(RRDSET *st, BUFFER *buf) {
+    struct variable2json_helper helper = {
+            .buf = buf,
+            .counter = 0
+    };
+
+    buffer_sprintf(buf, "{\n\t\"chart\": \"%s.%s\",\n\t\"chart_name\": \"%s.%s\",\n\t\"chart_variables\": {", st->type, st->id, st->type, st->name);
+    avl_traverse_lock(&st->variables_root_index, single_variable2json, (void *)&helper);
+    buffer_sprintf(buf, "\n\t},\n\t\"family\": \"%s\",\n\t\"family_variables\": {", st->family);
+    helper.counter = 0;
+    avl_traverse_lock(&st->rrdfamily->variables_root_index, single_variable2json, (void *)&helper);
+    buffer_sprintf(buf, "\n\t},\n\t\"host\": \"%s\",\n\t\"host_variables\": {", st->rrdhost->hostname);
+    helper.counter = 0;
+    avl_traverse_lock(&st->rrdhost->variables_root_index, single_variable2json, (void *)&helper);
+    buffer_strcat(buf, "\n\t}\n}\n");
 }
 
+
 // ----------------------------------------------------------------------------
-// RRDSETVAR management
+// RRDDIMVAR management
+// DIMENSION VARIABLES
 
-RRDSETVAR *rrdsetvar_create(RRDSET *st, const char *variable, int type, void *value, uint32_t options) {
-    debug(D_VARIABLES, "RRDVARSET create for chart id '%s' name '%s' with variable name '%s'", st->id, st->name, variable);
-    RRDSETVAR *rs = (RRDSETVAR *)callocz(1, sizeof(RRDSETVAR));
+#define RRDDIMVAR_ID_MAX 1024
 
-    char buffer[RRDVAR_MAX_LENGTH + 1];
-    snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->id, variable);
-    rs->fullid = strdupz(buffer);
+static inline void rrddimvar_free_variables(RRDDIMVAR *rs) {
+    RRDDIM *rd = rs->rrddim;
+    RRDSET *st = rd->rrdset;
 
-    snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->name, variable);
-    rs->fullname = strdupz(buffer);
+    // CHART VARIABLES FOR THIS DIMENSION
 
-    rs->variable = strdupz(variable);
+    rrdvar_free(st->rrdhost, &st->variables_root_index, rs->var_local_id);
+    rs->var_local_id = NULL;
 
-    rs->type = type;
-    rs->value = value;
-    rs->options = options;
-    rs->rrdset = st;
+    rrdvar_free(st->rrdhost, &st->variables_root_index, rs->var_local_name);
+    rs->var_local_name = NULL;
 
-    rs->local       = rrdvar_create_and_index("local",  &st->variables_root_index, rs->variable, rs->type, rs->value);
-    rs->family      = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullid, rs->type, rs->value);
-    rs->host        = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullid, rs->type, rs->value);
-    rs->family_name = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullname, rs->type, rs->value);
-    rs->host_name   = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullname, rs->type, rs->value);
+    // FAMILY VARIABLES FOR THIS DIMENSION
 
-    rs->next = st->variables;
-    st->variables = rs;
+    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->var_family_id);
+    rs->var_family_id = NULL;
 
-    return rs;
-}
+    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->var_family_name);
+    rs->var_family_name = NULL;
 
-void rrdsetvar_rename_all(RRDSET *st) {
-    debug(D_VARIABLES, "RRDSETVAR rename for chart id '%s' name '%s'", st->id, st->name);
+    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->var_family_contextid);
+    rs->var_family_contextid = NULL;
 
-    // only these 2 can change name
-    // rs->family_name
-    // rs->host_name
+    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->var_family_contextname);
+    rs->var_family_contextname = NULL;
 
-    char buffer[RRDVAR_MAX_LENGTH + 1];
-    RRDSETVAR *rs, *next = st->variables;
-    while((rs = next)) {
-        next = rs->next;
+    // HOST VARIABLES FOR THIS DIMENSION
 
-        snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->name, rs->variable);
+    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->var_host_chartidid);
+    rs->var_host_chartidid = NULL;
 
-        if (strcmp(buffer, rs->fullname)) {
-            // name changed
-            rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
-            rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_name);
+    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->var_host_chartidname);
+    rs->var_host_chartidname = NULL;
 
-            freez(rs->fullname);
-            rs->fullname = strdupz(st->name);
-            rs->family_name = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->fullname, rs->type, rs->value);
-            rs->host_name   = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index, rs->fullname, rs->type, rs->value);
-        }
-    }
+    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->var_host_chartnameid);
+    rs->var_host_chartnameid = NULL;
 
-    rrdsetcalc_link_matching(st);
-}
+    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->var_host_chartnamename);
+    rs->var_host_chartnamename = NULL;
 
-void rrdsetvar_free(RRDSETVAR *rs) {
-    RRDSET *st = rs->rrdset;
-    debug(D_VARIABLES, "RRDSETVAR free for chart id '%s' name '%s', variable '%s'", st->id, st->name, rs->variable);
+    // KEYS
 
-    rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local);
-    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family);
-    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host);
-    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
-    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_name);
+    freez(rs->key_id);
+    rs->key_id = NULL;
 
-    if(st->variables == rs) {
-        st->variables = rs->next;
-    }
-    else {
-        RRDSETVAR *t;
-        for (t = st->variables; t && t->next != rs; t = t->next);
-        if(!t) error("RRDSETVAR '%s' not found in chart '%s' variables linked list", rs->fullname, st->id);
-        else t->next = rs->next;
-    }
+    freez(rs->key_name);
+    rs->key_name = NULL;
 
-    freez(rs->fullid);
-    freez(rs->fullname);
-    freez(rs->variable);
-    freez(rs);
-}
+    freez(rs->key_fullidid);
+    rs->key_fullidid = NULL;
 
-// ----------------------------------------------------------------------------
-// RRDDIMVAR management
+    freez(rs->key_fullidname);
+    rs->key_fullidname = NULL;
 
-#define RRDDIMVAR_ID_MAX 1024
+    freez(rs->key_contextid);
+    rs->key_contextid = NULL;
 
-RRDDIMVAR *rrddimvar_create(RRDDIM *rd, int type, const char *prefix, const char *suffix, void *value, uint32_t options) {
-    RRDSET *st = rd->rrdset;
+    freez(rs->key_contextname);
+    rs->key_contextname = NULL;
 
-    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:"");
+    freez(rs->key_fullnameid);
+    rs->key_fullnameid = NULL;
 
-    if(!prefix) prefix = "";
-    if(!suffix) suffix = "";
+    freez(rs->key_fullnamename);
+    rs->key_fullnamename = NULL;
+}
+
+static inline void rrddimvar_create_variables(RRDDIMVAR *rs) {
+    rrddimvar_free_variables(rs);
+
+    RRDDIM *rd = rs->rrddim;
+    RRDSET *st = rd->rrdset;
 
     char buffer[RRDDIMVAR_ID_MAX + 1];
-    RRDDIMVAR *rs = (RRDDIMVAR *)callocz(1, sizeof(RRDDIMVAR));
 
-    rs->prefix = strdupz(prefix);
-    rs->suffix = strdupz(suffix);
+    // KEYS
 
     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->id, rs->suffix);
-    rs->id = strdupz(buffer);
+    rs->key_id = strdupz(buffer);
 
     snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->name, rs->suffix);
-    rs->name = strdupz(buffer);
+    rs->key_name = strdupz(buffer);
+
+    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->id, rs->key_id);
+    rs->key_fullidid = strdupz(buffer);
+
+    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->id, rs->key_name);
+    rs->key_fullidname = strdupz(buffer);
+
+    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->context, rs->key_id);
+    rs->key_contextid = strdupz(buffer);
+
+    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->context, rs->key_name);
+    rs->key_contextname = strdupz(buffer);
+
+    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->name, rs->key_id);
+    rs->key_fullnameid = strdupz(buffer);
+
+    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->name, rs->key_name);
+    rs->key_fullnamename = strdupz(buffer);
+
+    // CHART VARIABLES FOR THIS DIMENSION
+    // -----------------------------------
+    //
+    // dimensions are available as:
+    // - $id
+    // - $name
+
+    rs->var_local_id           = rrdvar_create_and_index("local", &st->variables_root_index, rs->key_id, rs->type, rs->value);
+    rs->var_local_name         = rrdvar_create_and_index("local", &st->variables_root_index, rs->key_name, rs->type, rs->value);
+
+    // FAMILY VARIABLES FOR THIS DIMENSION
+    // -----------------------------------
+    //
+    // dimensions are available as:
+    // - $id                 (only the first, when multiple overlap)
+    // - $name               (only the first, when multiple overlap)
+    // - $chart-context.id
+    // - $chart-context.name
+
+    rs->var_family_id          = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->key_id, rs->type, rs->value);
+    rs->var_family_name        = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->key_name, rs->type, rs->value);
+    rs->var_family_contextid   = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->key_contextid, rs->type, rs->value);
+    rs->var_family_contextname = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->key_contextname, rs->type, rs->value);
+
+    // HOST VARIABLES FOR THIS DIMENSION
+    // -----------------------------------
+    //
+    // dimensions are available as:
+    // - $chart-id.id
+    // - $chart-id.name
+    // - $chart-name.id
+    // - $chart-name.name
+
+    rs->var_host_chartidid      = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->key_fullidid, rs->type, rs->value);
+    rs->var_host_chartidname    = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->key_fullidname, rs->type, rs->value);
+    rs->var_host_chartnameid    = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->key_fullnameid, rs->type, rs->value);
+    rs->var_host_chartnamename  = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->key_fullnamename, rs->type, rs->value);
+}
 
-    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->id, rs->id);
-    rs->fullidid = strdupz(buffer);
+RRDDIMVAR *rrddimvar_create(RRDDIM *rd, int type, const char *prefix, const char *suffix, void *value, uint32_t options) {
+    RRDSET *st = rd->rrdset;
 
-    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->id, rs->name);
-    rs->fullidname = strdupz(buffer);
+    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:"");
+
+    if(!prefix) prefix = "";
+    if(!suffix) suffix = "";
 
-    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->name, rs->id);
-    rs->fullnameid = strdupz(buffer);
+    RRDDIMVAR *rs = (RRDDIMVAR *)callocz(1, sizeof(RRDDIMVAR));
 
-    snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", rd->rrdset->name, rs->name);
-    rs->fullnamename = strdupz(buffer);
+    rs->prefix = strdupz(prefix);
+    rs->suffix = strdupz(suffix);
 
     rs->type = type;
     rs->value = value;
     rs->options = options;
     rs->rrddim = rd;
 
-    rs->local_id     = rrdvar_create_and_index("local", &st->variables_root_index, rs->id, rs->type, rs->value);
-    rs->local_name   = rrdvar_create_and_index("local", &st->variables_root_index, rs->name, rs->type, rs->value);
-
-    rs->family_id    = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->id, rs->type, rs->value);
-    rs->family_name  = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index, rs->name, rs->type, rs->value);
-
-    rs->host_fullidid     = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullidid, rs->type, rs->value);
-    rs->host_fullidname   = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullidname, rs->type, rs->value);
-    rs->host_fullnameid   = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullnameid, rs->type, rs->value);
-    rs->host_fullnamename = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index, rs->fullnamename, rs->type, rs->value);
-
     rs->next = rd->variables;
     rd->variables = rs;
 
+    rrddimvar_create_variables(rs);
+
     return rs;
 }
 
@@ -662,41 +873,7 @@ void rrddimvar_rename_all(RRDDIM *rd) {
     RRDDIMVAR *rs, *next = rd->variables;
     while((rs = next)) {
         next = rs->next;
-
-        if (strcmp(rd->name, rs->name)) {
-            char buffer[RRDDIMVAR_ID_MAX + 1];
-            // name changed
-
-            // name
-            rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_name);
-            freez(rs->name);
-            snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s%s%s", rs->prefix, rd->name, rs->suffix);
-            rs->name = strdupz(buffer);
-            rs->local_name = rrdvar_create_and_index("local", &st->variables_root_index, rs->name, rs->type, rs->value);
-
-            rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidname);
-            freez(rs->fullidname);
-            snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->id, rs->name);
-            rs->fullidname = strdupz(buffer);
-            rs->host_fullidname = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
-                                                             rs->fullidname, rs->type, rs->value);
-
-            // fullnameid
-            rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnameid);
-            freez(rs->fullnameid);
-            snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->name, rs->id);
-            rs->fullnameid = strdupz(buffer);
-            rs->host_fullnameid = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
-                                                          rs->fullnameid, rs->type, rs->value);
-
-            // fullnamename
-            rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnamename);
-            freez(rs->fullnamename);
-            snprintfz(buffer, RRDDIMVAR_ID_MAX, "%s.%s", st->name, rs->name);
-            rs->fullnamename = strdupz(buffer);
-            rs->host_fullnamename = rrdvar_create_and_index("host", &st->rrdhost->variables_root_index,
-                                                          rs->fullnamename, rs->type, rs->value);
-        }
+        rrddimvar_create_variables(rs);
     }
 }
 
@@ -705,16 +882,7 @@ void rrddimvar_free(RRDDIMVAR *rs) {
     RRDSET *st = rd->rrdset;
     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);
 
-    rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_id);
-    rrdvar_free(st->rrdhost, &st->variables_root_index, rs->local_name);
-
-    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_id);
-    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->family_name);
-
-    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidid);
-    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullidname);
-    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnameid);
-    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->host_fullnamename);
+    rrddimvar_free_variables(rs);
 
     if(rd->variables == rs) {
         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);
@@ -724,18 +892,129 @@ void rrddimvar_free(RRDDIMVAR *rs) {
         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);
         RRDDIMVAR *t;
         for (t = rd->variables; t && t->next != rs; t = t->next) ;
-        if(!t) error("RRDDIMVAR '%s' not found in dimension '%s/%s' variables linked list", rs->name, st->id, rd->id);
+        if(!t) error("RRDDIMVAR '%s' not found in dimension '%s/%s' variables linked list", rs->key_name, st->id, rd->id);
         else t->next = rs->next;
     }
 
     freez(rs->prefix);
     freez(rs->suffix);
-    freez(rs->id);
-    freez(rs->name);
-    freez(rs->fullidid);
-    freez(rs->fullidname);
-    freez(rs->fullnameid);
-    freez(rs->fullnamename);
+    freez(rs);
+}
+
+// ----------------------------------------------------------------------------
+// RRDSETVAR management
+// CHART VARIABLES
+
+static inline void rrdsetvar_free_variables(RRDSETVAR *rs) {
+    RRDSET *st = rs->rrdset;
+
+    // CHART
+
+    rrdvar_free(st->rrdhost, &st->variables_root_index, rs->var_local);
+    rs->var_local = NULL;
+
+    // FAMILY
+
+    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->var_family);
+    rs->var_family = NULL;
+
+    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->var_host);
+    rs->var_host = NULL;
+
+    // HOST
+
+    rrdvar_free(st->rrdhost, &st->rrdfamily->variables_root_index, rs->var_family_name);
+    rs->var_family_name = NULL;
+
+    rrdvar_free(st->rrdhost, &st->rrdhost->variables_root_index, rs->var_host_name);
+    rs->var_host_name = NULL;
+
+    // KEYS
+
+    freez(rs->key_fullid);
+    rs->key_fullid = NULL;
+
+    freez(rs->key_fullname);
+    rs->key_fullname = NULL;
+}
+
+static inline void rrdsetvar_create_variables(RRDSETVAR *rs) {
+    rrdsetvar_free_variables(rs);
+
+    RRDSET *st = rs->rrdset;
+
+    // KEYS
+
+    char buffer[RRDVAR_MAX_LENGTH + 1];
+    snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->id, rs->variable);
+    rs->key_fullid = strdupz(buffer);
+
+    snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->name, rs->variable);
+    rs->key_fullname = strdupz(buffer);
+
+    // CHART
+
+    rs->var_local       = rrdvar_create_and_index("local",  &st->variables_root_index,               rs->variable, rs->type, rs->value);
+
+    // FAMILY
+
+    rs->var_family      = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index,    rs->key_fullid,   rs->type, rs->value);
+    rs->var_family_name = rrdvar_create_and_index("family", &st->rrdfamily->variables_root_index,    rs->key_fullname, rs->type, rs->value);
+
+    // HOST
+
+    rs->var_host        = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index,      rs->key_fullid,   rs->type, rs->value);
+    rs->var_host_name   = rrdvar_create_and_index("host",   &st->rrdhost->variables_root_index,      rs->key_fullname, rs->type, rs->value);
+
+}
+
+RRDSETVAR *rrdsetvar_create(RRDSET *st, const char *variable, int type, void *value, uint32_t options) {
+    debug(D_VARIABLES, "RRDVARSET create for chart id '%s' name '%s' with variable name '%s'", st->id, st->name, variable);
+    RRDSETVAR *rs = (RRDSETVAR *)callocz(1, sizeof(RRDSETVAR));
+
+    rs->variable = strdupz(variable);
+    rs->type = type;
+    rs->value = value;
+    rs->options = options;
+    rs->rrdset = st;
+
+    rs->next = st->variables;
+    st->variables = rs;
+
+    rrdsetvar_create_variables(rs);
+
+    return rs;
+}
+
+void rrdsetvar_rename_all(RRDSET *st) {
+    debug(D_VARIABLES, "RRDSETVAR rename for chart id '%s' name '%s'", st->id, st->name);
+
+    RRDSETVAR *rs, *next = st->variables;
+    while((rs = next)) {
+        next = rs->next;
+        rrdsetvar_create_variables(rs);
+    }
+
+    rrdsetcalc_link_matching(st);
+}
+
+void rrdsetvar_free(RRDSETVAR *rs) {
+    RRDSET *st = rs->rrdset;
+    debug(D_VARIABLES, "RRDSETVAR free for chart id '%s' name '%s', variable '%s'", st->id, st->name, rs->variable);
+
+    if(st->variables == rs) {
+        st->variables = rs->next;
+    }
+    else {
+        RRDSETVAR *t;
+        for (t = st->variables; t && t->next != rs; t = t->next);
+        if(!t) error("RRDSETVAR '%s' not found in chart '%s' variables linked list", rs->key_fullname, st->id);
+        else t->next = rs->next;
+    }
+
+    rrdsetvar_free_variables(rs);
+
+    freez(rs->variable);
     freez(rs);
 }
 
@@ -1580,10 +1859,8 @@ int health_readfile(const char *path, const char *filename) {
     while((s = fgets(&buffer[append], (int)(HEALTH_CONF_MAX_LINE - append), fp)) || append) {
         int stop_appending = !s;
         line++;
-        // info("Line %zu of file '%s/%s': '%s'", line, path, filename, s);
         s = trim(buffer);
         if(!s) continue;
-        // info("Trimmed line %zu of file '%s/%s': '%s'", line, path, filename, s);
 
         append = strlen(s);
         if(!stop_appending && s[append - 1] == '\\') {
@@ -1620,7 +1897,6 @@ int health_readfile(const char *path, const char *filename) {
             continue;
         }
 
-        // info("Health file '%s/%s', key '%s', value '%s'", path, filename, key, value);
         uint32_t hash = simple_uhash(key);
 
         if(hash == hash_alarm && !strcasecmp(key, HEALTH_ALARM_KEY)) {
@@ -1672,7 +1948,7 @@ int health_readfile(const char *path, const char *filename) {
             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
                 if(rc->chart) {
                     if(strcmp(rc->chart, value))
-                        info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rc->name, key, rc->chart, value, value);
 
                     freez(rc->chart);
@@ -1687,14 +1963,14 @@ int health_readfile(const char *path, const char *filename) {
             }
             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
                 if(!health_parse_duration(value, &rc->update_every))
-                    info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' cannot parse duration: '%s'.",
+                    error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' cannot parse duration: '%s'.",
                          line, path, filename, rc->name, key, value);
             }
             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
                 char *e;
                 rc->green = strtold(value, &e);
                 if(e && *e) {
-                    info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
+                    error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
                          line, path, filename, rc->name, key, e);
                 }
             }
@@ -1702,7 +1978,7 @@ int health_readfile(const char *path, const char *filename) {
                 char *e;
                 rc->red = strtold(value, &e);
                 if(e && *e) {
-                    info("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
+                    error("Health configuration at line %zu of file '%s/%s' for alarm '%s' at key '%s' leaves this string unmatched: '%s'.",
                          line, path, filename, rc->name, key, e);
                 }
             }
@@ -1736,7 +2012,7 @@ int health_readfile(const char *path, const char *filename) {
             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
                 if(rc->exec) {
                     if(strcmp(rc->exec, value))
-                        info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rc->name, key, rc->exec, value, value);
 
                     freez(rc->exec);
@@ -1746,7 +2022,7 @@ int health_readfile(const char *path, const char *filename) {
             else if(hash == hash_recipient && !strcasecmp(key, HEALTH_RECIPIENT_KEY)) {
                 if(rc->recipient) {
                     if(strcmp(rc->recipient, value))
-                        info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rc->name, key, rc->recipient, value, value);
 
                     freez(rc->recipient);
@@ -1756,7 +2032,7 @@ int health_readfile(const char *path, const char *filename) {
             else if(hash == hash_units && !strcasecmp(key, HEALTH_UNITS_KEY)) {
                 if(rc->units) {
                     if(strcmp(rc->units, value))
-                        info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rc->name, key, rc->units, value, value);
 
                     freez(rc->units);
@@ -1767,7 +2043,7 @@ int health_readfile(const char *path, const char *filename) {
             else if(hash == hash_info && !strcasecmp(key, HEALTH_INFO_KEY)) {
                 if(rc->info) {
                     if(strcmp(rc->info, value))
-                        info("Health configuration at line %zu of file '%s/%s' for alarm '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rc->name, key, rc->info, value, value);
 
                     freez(rc->info);
@@ -1787,7 +2063,7 @@ int health_readfile(const char *path, const char *filename) {
             if(hash == hash_on && !strcasecmp(key, HEALTH_ON_KEY)) {
                 if(rt->context) {
                     if(strcmp(rt->context, value))
-                        info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rt->name, key, rt->context, value, value);
 
                     freez(rt->context);
@@ -1802,14 +2078,14 @@ int health_readfile(const char *path, const char *filename) {
             }
             else if(hash == hash_every && !strcasecmp(key, HEALTH_EVERY_KEY)) {
                 if(!health_parse_duration(value, &rt->update_every))
-                    info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' cannot parse duration: '%s'.",
+                    error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' cannot parse duration: '%s'.",
                          line, path, filename, rt->name, key, value);
             }
             else if(hash == hash_green && !strcasecmp(key, HEALTH_GREEN_KEY)) {
                 char *e;
                 rt->green = strtold(value, &e);
                 if(e && *e) {
-                    info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
+                    error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
                          line, path, filename, rt->name, key, e);
                 }
             }
@@ -1817,7 +2093,7 @@ int health_readfile(const char *path, const char *filename) {
                 char *e;
                 rt->red = strtold(value, &e);
                 if(e && *e) {
-                    info("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
+                    error("Health configuration at line %zu of file '%s/%s' for template '%s' at key '%s' leaves this string unmatched: '%s'.",
                          line, path, filename, rt->name, key, e);
                 }
             }
@@ -1851,7 +2127,7 @@ int health_readfile(const char *path, const char *filename) {
             else if(hash == hash_exec && !strcasecmp(key, HEALTH_EXEC_KEY)) {
                 if(rt->exec) {
                     if(strcmp(rt->exec, value))
-                        info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rt->name, key, rt->exec, value, value);
 
                     freez(rt->exec);
@@ -1861,7 +2137,7 @@ int health_readfile(const char *path, const char *filename) {
             else if(hash == hash_recipient && !strcasecmp(key, HEALTH_RECIPIENT_KEY)) {
                 if(rt->recipient) {
                     if(strcmp(rt->recipient, value))
-                        info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rt->name, key, rt->recipient, value, value);
 
                     freez(rt->recipient);
@@ -1871,7 +2147,7 @@ int health_readfile(const char *path, const char *filename) {
             else if(hash == hash_units && !strcasecmp(key, HEALTH_UNITS_KEY)) {
                 if(rt->units) {
                     if(strcmp(rt->units, value))
-                        info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rt->name, key, rt->units, value, value);
 
                     freez(rt->units);
@@ -1882,7 +2158,7 @@ int health_readfile(const char *path, const char *filename) {
             else if(hash == hash_info && !strcasecmp(key, HEALTH_INFO_KEY)) {
                 if(rt->info) {
                     if(strcmp(rt->info, value))
-                        info("Health configuration at line %zu of file '%s/%s' for template '%s' has key '%s' twice, once with value '%s' and later with value '%s'. Using ('%s').",
+                        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').",
                              line, path, filename, rt->name, key, rt->info, value, value);
 
                     freez(rt->info);
@@ -2307,23 +2583,34 @@ static inline int rrdcalc_value2status(calculated_number n) {
 static inline void health_alarm_execute(RRDHOST *host, ALARM_ENTRY *ae) {
     ae->flags |= HEALTH_ENTRY_FLAG_PROCESSED;
 
+    if(unlikely(ae->new_status < RRDCALC_STATUS_CLEAR)) {
+        // do not send notifications for internal statuses
+        goto done;
+    }
+
     // find the previous notification for the same alarm
+    // which we have run the exec script
     ALARM_ENTRY *t;
     for(t = ae->next; t ;t = t->next) {
         if(t->alarm_id == ae->alarm_id && t->flags & HEALTH_ENTRY_FLAG_EXEC_RUN)
             break;
     }
 
-    if(t && t->new_status == ae->new_status) {
-        // don't send the same notification again
-        info("Health not sending again notification for alarm '%s.%s' status %s", ae->chart, ae->name, rrdcalc_status2string(ae->new_status));
-        goto done;
+    if(likely(t)) {
+        // we have executed this alarm notification in the past
+        if (t && t->new_status == ae->new_status) {
+            // don't send the same notification again
+            debug(D_HEALTH, "Health not sending again notification for alarm '%s.%s' status %s", ae->chart, ae->name,
+                 rrdcalc_status2string(ae->new_status));
+            goto done;
+        }
     }
-
-    if((ae->old_status == RRDCALC_STATUS_UNDEFINED && ae->new_status == RRDCALC_STATUS_UNINITIALIZED)
-        || (ae->old_status == RRDCALC_STATUS_UNINITIALIZED && ae->new_status == RRDCALC_STATUS_CLEAR)) {
-        info("Health not sending notification for first initialization of alarm '%s.%s' status %s", ae->chart, ae->name, rrdcalc_status2string(ae->new_status));
-        goto done;
+    else {
+        // we have not executed this alarm notification in the past
+        if(unlikely(ae->old_status == RRDCALC_STATUS_UNINITIALIZED && ae->new_status == RRDCALC_STATUS_CLEAR)) {
+            debug(D_HEALTH, "Health not sending notification for first initialization of alarm '%s.%s' status %s", ae->chart, ae->name, rrdcalc_status2string(ae->new_status));
+            goto done;
+        }
     }
 
     char buffer[FILENAME_MAX + 1];
@@ -2381,7 +2668,7 @@ done:
 }
 
 static inline void health_process_notifications(RRDHOST *host, ALARM_ENTRY *ae) {
-    info("Health alarm '%s.%s' = %0.2Lf - changed status from %s to %s",
+    debug(D_HEALTH, "Health alarm '%s.%s' = %0.2Lf - changed status from %s to %s",
          ae->chart?ae->chart:"NOCHART", ae->name,
          ae->new_value,
          rrdcalc_status2string(ae->old_status),
@@ -2456,34 +2743,55 @@ static inline void health_alarm_log_process(RRDHOST *host) {
 }
 
 static inline int rrdcalc_isrunnable(RRDCALC *rc, time_t now, time_t *next_run) {
-    if (unlikely(!rc->rrdset)) {
+    if(unlikely(!rc->rrdset)) {
         debug(D_HEALTH, "Health not running alarm '%s.%s'. It is not linked to a chart.", rc->chart?rc->chart:"NOCHART", rc->name);
         return 0;
     }
 
-    if (unlikely(!rc->rrdset->last_collected_time.tv_sec)) {
-        debug(D_HEALTH, "Health not running alarm '%s.%s'. Chart is not yet collected.", rc->chart?rc->chart:"NOCHART", rc->name);
+    if(unlikely(rc->next_update > now)) {
+        if (unlikely(*next_run > rc->next_update)) {
+            // update the next_run time of the main loop
+            // to run this alarm precisely the time required
+            *next_run = rc->next_update;
+        }
+
+        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));
         return 0;
     }
 
-    if (unlikely(!rc->update_every)) {
+    if(unlikely(!rc->update_every)) {
         debug(D_HEALTH, "Health not running alarm '%s.%s'. It does not have an update frequency", rc->chart?rc->chart:"NOCHART", rc->name);
         return 0;
     }
 
-    if (unlikely(rc->next_update > now)) {
-        if (unlikely(*next_run > rc->next_update))
-            *next_run = rc->next_update;
+    if(unlikely(!rc->rrdset->last_collected_time.tv_sec || rc->rrdset->counter_done < 2)) {
+        debug(D_HEALTH, "Health not running alarm '%s.%s'. Chart is not fully collected yet.", rc->chart?rc->chart:"NOCHART", rc->name);
+        return 0;
+    }
 
-        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));
+    int update_every = rc->rrdset->update_every;
+    time_t first = rrdset_first_entry_t(rc->rrdset);
+    time_t last = rrdset_last_entry_t(rc->rrdset);
+
+    if(unlikely(now + update_every < first /* || now - update_every > last */)) {
+        debug(D_HEALTH
+              , "Health not examining alarm '%s.%s' yet (wanted time is out of bounds - we need %lu but got %lu - %lu)."
+              , rc->chart ? rc->chart : "NOCHART", rc->name, (unsigned long) now, (unsigned long) first
+              , (unsigned long) last);
         return 0;
     }
 
-    // FIXME
-    // we should check that the DB lookup is possible
-    // i.e.
-    // - the duration of the chart includes the required timeframe
-    // we SHOULD NOT check the dimensions - there might be alarms that refer non-existing dimensions (e.g. cpu steal)
+    if(RRDCALC_HAS_DB_LOOKUP(rc)) {
+        time_t needed = now + rc->before + rc->after;
+
+        if(needed + update_every < first || needed - update_every > last) {
+            debug(D_HEALTH
+                  , "Health not examining alarm '%s.%s' yet (not enough data yet - we need %lu but got %lu - %lu)."
+                  , rc->chart ? rc->chart : "NOCHART", rc->name, (unsigned long) needed, (unsigned long) first
+                  , (unsigned long) last);
+            return 0;
+        }
+    }
 
     return 1;
 }
@@ -2514,24 +2822,28 @@ void *health_main(void *ptr) {
         time_t next_run = now + min_run_every;
         RRDCALC *rc;
 
-        if (unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) != 0))
+        if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) != 0))
             error("Cannot set pthread cancel state to DISABLE.");
 
         rrdhost_rdlock(&localhost);
 
         // the first loop is to lookup values from the db
-        for (rc = localhost.alarms; rc; rc = rc->next) {
-            if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
+        for(rc = localhost.alarms; rc; rc = rc->next) {
+            if(unlikely(!rrdcalc_isrunnable(rc, now, &next_run))) {
+                if(unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_RUNNABLE))
+                    rc->rrdcalc_flags &= ~RRDCALC_FLAG_RUNNABLE;
                 continue;
+            }
 
             runnable++;
             rc->old_value = rc->value;
+            rc->rrdcalc_flags |= RRDCALC_FLAG_RUNNABLE;
 
             // 1. if there is database lookup, do it
             // 2. if there is calculation expression, run it
 
             if (unlikely(RRDCALC_HAS_DB_LOOKUP(rc))) {
-                time_t old_db_timestamp = rc->db_before;
+                /* time_t old_db_timestamp = rc->db_before; */
                 int value_is_null = 0;
 
                 int ret = rrd2value(rc->rrdset, wb, &rc->value,
@@ -2552,6 +2864,7 @@ void *health_main(void *ptr) {
                 else if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_DB_ERROR))
                     rc->rrdcalc_flags &= ~RRDCALC_FLAG_DB_ERROR;
 
+                /* - RRDCALC_FLAG_DB_STALE not currently used
                 if (unlikely(old_db_timestamp == rc->db_before)) {
                     // database is stale
 
@@ -2564,6 +2877,7 @@ void *health_main(void *ptr) {
                 }
                 else if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_DB_STALE))
                     rc->rrdcalc_flags &= ~RRDCALC_FLAG_DB_STALE;
+                */
 
                 if (unlikely(value_is_null)) {
                     // collected value is null
@@ -2592,23 +2906,24 @@ void *health_main(void *ptr) {
 
                     rc->value = NAN;
 
-                    debug(D_HEALTH, "Health alarm '%s.%s': failed to evaluate calculation with error: %s",
-                          rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
+                    debug(D_HEALTH, "Health alarm '%s.%s': expression '%s' failed: %s",
+                          rc->chart?rc->chart:"NOCHART", rc->name, rc->calculation->parsed_as, buffer_tostring(rc->calculation->error_msg));
 
                     if (unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_CALC_ERROR))) {
                         rc->rrdcalc_flags |= RRDCALC_FLAG_CALC_ERROR;
-                        error("Health alarm '%s.%s': failed to evaluate calculation with error: %s",
-                              rc->chart?rc->chart:"NOCHART", rc->name, buffer_tostring(rc->calculation->error_msg));
+                        error("Health alarm '%s.%s': expression '%s' failed: %s",
+                              rc->chart?rc->chart:"NOCHART", rc->name, rc->calculation->parsed_as, buffer_tostring(rc->calculation->error_msg));
                     }
                 }
                 else {
                     if (unlikely(rc->rrdcalc_flags & RRDCALC_FLAG_CALC_ERROR))
                         rc->rrdcalc_flags &= ~RRDCALC_FLAG_CALC_ERROR;
 
-                    debug(D_HEALTH, "Health alarm '%s.%s': calculation expression gave value "
+                    debug(D_HEALTH, "Health alarm '%s.%s': expression '%s' gave value "
                             CALCULATED_NUMBER_FORMAT
                             ": %s (source: %s)",
                           rc->chart?rc->chart:"NOCHART", rc->name,
+                          rc->calculation->parsed_as,
                           rc->calculation->result,
                           buffer_tostring(rc->calculation->error_msg),
                           rc->source
@@ -2620,11 +2935,11 @@ void *health_main(void *ptr) {
         }
         rrdhost_unlock(&localhost);
 
-        if (unlikely(runnable && !netdata_exit)) {
+        if(unlikely(runnable && !netdata_exit)) {
             rrdhost_rdlock(&localhost);
 
-            for (rc = localhost.alarms; rc; rc = rc->next) {
-                if (unlikely(!rrdcalc_isrunnable(rc, now, &next_run)))
+            for(rc = localhost.alarms; rc; rc = rc->next) {
+                if(unlikely(!(rc->rrdcalc_flags & RRDCALC_FLAG_RUNNABLE)))
                     continue;
 
                 int warning_status  = RRDCALC_STATUS_UNDEFINED;