]> arthur.barton.de Git - netdata.git/blobdiff - src/rrd2json.c
added a new element on all charts: context, which is the template upon the chart...
[netdata.git] / src / rrd2json.c
index 8e5095bab7690fcdbbf10b3a19ce3ad637b7aade..ad453cb687f957aa35a2a99f1928cc2af4bbc07b 100755 (executable)
@@ -2,9 +2,9 @@
 #include <config.h>
 #endif
 #include <pthread.h>
-#include <sys/time.h>
 #include <stdlib.h>
 #include <string.h>
+#include <stdint.h>
 
 #include "log.h"
 #include "common.h"
@@ -23,6 +23,7 @@ void rrd_stats_api_v1_chart(RRDSET *st, BUFFER *wb)
                "\t\t\t\"name\": \"%s\",\n"
                "\t\t\t\"type\": \"%s\",\n"
                "\t\t\t\"family\": \"%s\",\n"
+               "\t\t\t\"context\": \"%s\",\n"
                "\t\t\t\"title\": \"%s\",\n"
                "\t\t\t\"priority\": %ld,\n"
                "\t\t\t\"enabled\": %s,\n"
@@ -38,6 +39,7 @@ void rrd_stats_api_v1_chart(RRDSET *st, BUFFER *wb)
                , st->name
                , st->type
                , st->family
+               , st->context
                , st->title
                , st->priority
                , st->enabled?"true":"false"
@@ -122,6 +124,7 @@ unsigned long rrd_stats_one_json(RRDSET *st, char *options, BUFFER *wb)
                "\t\t\t\"name\": \"%s\",\n"
                "\t\t\t\"type\": \"%s\",\n"
                "\t\t\t\"family\": \"%s\",\n"
+               "\t\t\t\"context\": \"%s\",\n"
                "\t\t\t\"title\": \"%s\",\n"
                "\t\t\t\"priority\": %ld,\n"
                "\t\t\t\"enabled\": %d,\n"
@@ -144,6 +147,7 @@ unsigned long rrd_stats_one_json(RRDSET *st, char *options, BUFFER *wb)
                , st->name
                , st->type
                , st->family
+               , st->context
                , st->title
                , st->priority
                , st->enabled
@@ -259,22 +263,24 @@ void rrd_stats_all_json(BUFFER *wb)
 
 // ----------------------------------------------------------------------------
 
-// RRDR options
+// RRDR dimension options
 #define RRDR_EMPTY     0x01 // the dimension contains / the value is empty (null)
 #define RRDR_RESET     0x02 // the dimension contains / the value is reset
 #define RRDR_HIDDEN    0x04 // the dimension contains / the value is hidden
 #define RRDR_NONZERO   0x08 // the dimension contains / the value is non-zero
 
+// RRDR result options
+#define RRDR_RESULT_OPTION_ABSOLUTE 0x00000001
+#define RRDR_RESULT_OPTION_RELATIVE 0x00000002
 
 typedef struct rrdresult {
        RRDSET *st;                     // the chart this result refers to
 
-       int group;                              // how many collected values were grouped for each row
-       int update_every;               // what is the suggested update frequency in seconds
+       uint32_t result_options;        // RRDR_RESULT_OPTION_*
 
        int d;                                  // the number of dimensions
-       int n;                                  // the number of values in the arrays
-       int rows;                       // the number of rows used
+       long n;                                 // the number of values in the arrays
+       long rows;                          // the number of rows used
 
        uint8_t *od;                    // the options for the dimensions
 
@@ -282,7 +288,16 @@ typedef struct rrdresult {
        calculated_number *v;   // array n x d values
        uint8_t *o;                             // array n x d options
 
-       int c;                                  // current line ( -1 ~ n ), ( -1 = none, use rrdr_rows() to get number of rows )
+       long c;                                 // current line ( -1 ~ n ), ( -1 = none, use rrdr_rows() to get number of rows )
+
+       long group;                             // how many collected values were grouped for each row
+       long update_every;              // what is the suggested update frequency in seconds
+
+       calculated_number min;
+       calculated_number max;
+
+       time_t before;
+       time_t after;
 
        int has_st_lock;                // if st is read locked by us
 } RRDR;
@@ -365,17 +380,282 @@ void rrdr_disable_not_selected_dimensions(RRDR *r, const char *dims)
                for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
                        if(!strcmp(d->name, tok)) {
                                r->od[c] &= ~RRDR_HIDDEN;
+
+                               // since the user needs this dimension
+                               // make it appear as NONZERO, to return it
+                               // even if the dimension has only zeros
+                               r->od[c] |= RRDR_NONZERO;
                        }
                }
        }
 }
 
+void rrdr_buffer_print_format(BUFFER *wb, uint32_t format)
+{
+       switch(format) {
+       case DATASOURCE_JSON:
+               buffer_strcat(wb, DATASOURCE_FORMAT_JSON);
+               break;
+
+       case DATASOURCE_DATATABLE_JSON:
+               buffer_strcat(wb, DATASOURCE_FORMAT_DATATABLE_JSON);
+               break;
+
+       case DATASOURCE_DATATABLE_JSONP:
+               buffer_strcat(wb, DATASOURCE_FORMAT_DATATABLE_JSONP);
+               break;
+
+       case DATASOURCE_JSONP:
+               buffer_strcat(wb, DATASOURCE_FORMAT_JSONP);
+               break;
+
+       case DATASOURCE_SSV:
+               buffer_strcat(wb, DATASOURCE_FORMAT_SSV);
+               break;
+
+       case DATASOURCE_CSV:
+               buffer_strcat(wb, DATASOURCE_FORMAT_CSV);
+               break;
+
+       case DATASOURCE_TSV:
+               buffer_strcat(wb, DATASOURCE_FORMAT_TSV);
+               break;
+
+       case DATASOURCE_HTML:
+               buffer_strcat(wb, DATASOURCE_FORMAT_HTML);
+               break;
+
+       case DATASOURCE_JS_ARRAY:
+               buffer_strcat(wb, DATASOURCE_FORMAT_JS_ARRAY);
+               break;
+
+       case DATASOURCE_SSV_COMMA:
+               buffer_strcat(wb, DATASOURCE_FORMAT_SSV_COMMA);
+               break;
+
+       default:
+               buffer_strcat(wb, "unknown");
+               break;
+       }
+}
+
+uint32_t rrdr_check_options(RRDR *r, uint32_t options, const char *dims)
+{
+       if(options & RRDR_OPTION_NONZERO) {
+               long i;
+
+               if(dims && *dims) {
+                       // the caller wants specific dimensions
+                       // disable NONZERO option
+                       // to make sure we don't accidentally prevent
+                       // the specific dimensions from being returned
+                       i = 0;
+               }
+               else {
+                       // find how many dimensions are not zero
+                       long c;
+                       RRDDIM *rd;
+                       for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ; c++, rd = rd->next) {
+                               if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
+                               if(unlikely(!(r->od[c] & RRDR_NONZERO))) continue;
+                               i++;
+                       }
+               }
+
+               // if with nonzero we get i = 0 (no dimensions will be returned)
+               // disable nonzero to show all dimensions
+               if(!i) options &= ~RRDR_OPTION_NONZERO;
+       }
+
+       return options;
+}
+
+void rrdr_json_wrapper_begin(RRDR *r, BUFFER *wb, uint32_t format, uint32_t options, int string_value)
+{
+       long rows = rrdr_rows(r);
+       long c, i;
+       RRDDIM *rd;
+
+       //info("JSONWRAPPER(): %s: BEGIN", r->st->id);
+       char kq[2] = "",                                        // key quote
+               sq[2] = "";                                             // string quote
+
+       if( options & RRDR_OPTION_GOOGLE_JSON ) {
+               kq[0] = '\0';
+               sq[0] = '\'';
+       }
+       else {
+               kq[0] = '"';
+               sq[0] = '"';
+       }
+
+       buffer_sprintf(wb, "{\n"
+                       "       %sapi%s: 1,\n"
+                       "       %sid%s: %s%s%s,\n"
+                       "       %sname%s: %s%s%s,\n"
+                       "       %sview_update_every%s: %d,\n"
+                       "       %supdate_every%s: %d,\n"
+                       "       %sfirst_entry%s: %u,\n"
+                       "       %slast_entry%s: %u,\n"
+                       "       %sbefore%s: %u,\n"
+                       "       %safter%s: %u,\n"
+                       "       %sdimension_names%s: ["
+                       , kq, kq
+                       , kq, kq, sq, r->st->id, sq
+                       , kq, kq, sq, r->st->name, sq
+                       , kq, kq, r->update_every
+                       , kq, kq, r->st->update_every
+                       , kq, kq, rrdset_first_entry_t(r->st)
+                       , kq, kq, rrdset_last_entry_t(r->st)
+                       , kq, kq, r->before
+                       , kq, kq, r->after
+                       , kq, kq);
+
+       for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
+               if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
+               if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
+
+               if(i) buffer_strcat(wb, ", ");
+               buffer_strcat(wb, sq);
+               buffer_strcat(wb, rd->name);
+               buffer_strcat(wb, sq);
+               i++;
+       }
+       if(!i) {
+#ifdef NETDATA_INTERNAL_CHECKS
+               error("RRDR is empty for %s (RRDR has %d dimensions, options is 0x%08x)", r->st->id, r->d, options);
+#endif
+               rows = 0;
+               buffer_strcat(wb, sq);
+               buffer_strcat(wb, "no data");
+               buffer_strcat(wb, sq);
+       }
+
+       buffer_sprintf(wb, "],\n"
+                       "       %sdimension_ids%s: ["
+                       , kq, kq);
+
+       for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
+               if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
+               if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
+
+               if(i) buffer_strcat(wb, ", ");
+               buffer_strcat(wb, sq);
+               buffer_strcat(wb, rd->id);
+               buffer_strcat(wb, sq);
+               i++;
+       }
+       if(!i) {
+               rows = 0;
+               buffer_strcat(wb, sq);
+               buffer_strcat(wb, "no data");
+               buffer_strcat(wb, sq);
+       }
+
+       buffer_sprintf(wb, "],\n"
+                       "       %slatest_values%s: ["
+                       , kq, kq);
+
+       for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
+               if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
+               if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
+
+               if(i) buffer_strcat(wb, ", ");
+               i++;
+
+               storage_number n = rd->values[rrdset_last_slot(r->st)];
+
+               if(!does_storage_number_exist(n))
+                       buffer_strcat(wb, "null");
+               else
+                       buffer_rrd_value(wb, unpack_storage_number(n));
+       }
+       if(!i) {
+               rows = 0;
+               buffer_strcat(wb, "null");
+       }
+
+       buffer_sprintf(wb, "],\n"
+                       "       %sview_latest_values%s: ["
+                       , kq, kq);
+
+       i = 0;
+       if(rows) {
+               for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
+                       if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
+                       if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
+
+                       if(i) buffer_strcat(wb, ", ");
+                       i++;
+
+                       calculated_number *cn = &r->v[ (0) * r->d ];
+                       uint8_t *co = &r->o[ (0) * r->d ];
+
+                       if(co[c] & RRDR_EMPTY)
+                               buffer_strcat(wb, "null");
+                       else
+                               buffer_rrd_value(wb, cn[c]);
+               }
+       }
+       if(!i) {
+               rows = 0;
+               buffer_strcat(wb, "null");
+       }
+
+       buffer_sprintf(wb, "],\n"
+                       "       %sdimensions%s: %d,\n"
+                       "       %spoints%s: %d,\n"
+                       "       %sformat%s: %s"
+                       , kq, kq, i
+                       , kq, kq, rows
+                       , kq, kq, sq
+                       );
+
+       rrdr_buffer_print_format(wb, format);
+
+       buffer_sprintf(wb, "%s,\n"
+                       "       %sresult%s: "
+                       , sq
+                       , kq, kq
+                       );
+
+       if(string_value) buffer_strcat(wb, sq);
+       //info("JSONWRAPPER(): %s: END", r->st->id);
+}
+
+void rrdr_json_wrapper_end(RRDR *r, BUFFER *wb, uint32_t format, uint32_t options, int string_value)
+{
+       if(r) {;}
+       if(format) {;}
+
+       char kq[2] = "",                                        // key quote
+               sq[2] = "";                                             // string quote
+
+       if( options & RRDR_OPTION_GOOGLE_JSON ) {
+               kq[0] = '\0';
+               sq[0] = '\'';
+       }
+       else {
+               kq[0] = '"';
+               sq[0] = '"';
+       }
+
+       if(string_value) buffer_strcat(wb, sq);
+
+       buffer_sprintf(wb, ",\n %smin%s: ", kq, kq);
+       buffer_rrd_value(wb, r->min);
+       buffer_sprintf(wb, ",\n %smax%s: ", kq, kq);
+       buffer_rrd_value(wb, r->max);
+       buffer_strcat(wb, "\n}\n");
+}
+
 #define JSON_DATES_JS 1
 #define JSON_DATES_TIMESTAMP 2
 
 static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
 {
-       int row_annotations = 0, dates = JSON_DATES_JS, dates_with_new = 0;
+       //info("RRD2JSON(): %s: BEGIN", r->st->id);
+       int row_annotations = 0, dates, dates_with_new = 0;
        char kq[2] = "",                                        // key quote
                sq[2] = "",                                             // string quote
                pre_label[101] = "",                    // before each label
@@ -409,12 +689,12 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
                snprintf(post_value, 100, "}");
                snprintf(post_line,  100, "]}");
                snprintf(data_begin, 100, "\n   ],\n    %srows%s:\n     [\n", kq, kq);
-               snprintf(finish,     100, "\n   ]\n}\n");
+               snprintf(finish,     100, "\n   ]\n}");
 
                snprintf(overflow_annotation, 200, ",{%sv%s:%sRESET OR OVERFLOW%s},{%sv%s:%sThe counters have been wrapped.%s}", kq, kq, sq, sq, kq, kq, sq, sq);
                snprintf(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
 
-               buffer_sprintf(wb, "{\n %supdate_every%s: %d,\n %scols%s:\n     [\n", kq, kq, r->update_every, kq, kq, kq, kq);
+               buffer_sprintf(wb, "{\n %scols%s:\n     [\n", kq, kq, kq, kq);
                buffer_sprintf(wb, "            {%sid%s:%s%s,%slabel%s:%stime%s,%spattern%s:%s%s,%stype%s:%sdatetime%s},\n", kq, kq, sq, sq, kq, kq, sq, sq, kq, kq, sq, sq, kq, kq, sq, sq);
                buffer_sprintf(wb, "            {%sid%s:%s%s,%slabel%s:%s%s,%spattern%s:%s%s,%stype%s:%sstring%s,%sp%s:{%srole%s:%sannotation%s}},\n", kq, kq, sq, sq, kq, kq, sq, sq, kq, kq, sq, sq, kq, kq, sq, sq, kq, kq, kq, kq, sq, sq);
                buffer_sprintf(wb, "            {%sid%s:%s%s,%slabel%s:%s%s,%spattern%s:%s%s,%stype%s:%sstring%s,%sp%s:{%srole%s:%sannotationText%s}}", kq, kq, sq, sq, kq, kq, sq, sq, kq, kq, sq, sq, kq, kq, sq, sq, kq, kq, kq, kq, sq, sq);
@@ -447,9 +727,9 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
                else
                        snprintf(post_line,  100, "]");
                snprintf(data_begin, 100, "],\n %sdata%s:\n     [\n", kq, kq);
-               snprintf(finish,     100, "\n   ]\n}\n");
+               snprintf(finish,     100, "\n   ]\n}");
 
-               buffer_sprintf(wb, "{\n %supdate_every%s: %d,\n %slabels%s: [", kq, kq, r->update_every, kq, kq);
+               buffer_sprintf(wb, "{\n %slabels%s: [", kq, kq);
                buffer_sprintf(wb, "%stime%s", sq, sq);
        }
 
@@ -460,7 +740,7 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
        RRDDIM *rd;
 
        // print the header lines
-       for(c = 0, i = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
+       for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
                if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
                if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
 
@@ -480,12 +760,8 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
 
        // if all dimensions are hidden, print a null
        if(!i) {
-               buffer_strcat(wb, pre_value);
-               if(options & RRDR_OPTION_NULL2ZERO)
-                       buffer_strcat(wb, "0");
-               else
-                       buffer_strcat(wb, "null");
-               buffer_strcat(wb, post_value);
+               buffer_strcat(wb, finish);
+               return;
        }
 
        long start = 0, end = rrdr_rows(r), step = 1;
@@ -496,6 +772,7 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
        }
 
        // for each line in the array
+       calculated_number total = 1;
        for(i = start; i != end ;i += step) {
                calculated_number *cn = &r->v[ i * r->d ];
                uint8_t *co = &r->o[ i * r->d ];
@@ -504,8 +781,8 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
 
                if(dates == JSON_DATES_JS) {
                        // generate the local date time
-                       struct tm *tm = localtime(&now);
-                       if(!tm) { error("localtime() failed."); continue; }
+                       struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
+                       if(!tm) { error("localtime_r() failed."); continue; }
 
                        if(likely(i != start)) buffer_strcat(wb, ",\n");
                        buffer_strcat(wb, pre_date);
@@ -549,8 +826,22 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
                        buffer_strcat(wb, post_date);
                }
 
+               if(unlikely(options & RRDR_OPTION_PERCENTAGE)) {
+                       total = 0;
+                       for(c = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
+                               calculated_number n = cn[c];
+
+                               if(likely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
+                                       n = -n;
+
+                               total += n;
+                       }
+                       // prevent a division by zero
+                       if(total == 0) total = 1;
+               }
+
                // for each dimension
-               for(c = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
+               for(c = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
                        if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
                        if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
 
@@ -567,10 +858,15 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
                                else
                                        buffer_strcat(wb, "null");
                        }
-                       else if((options & RRDR_OPTION_ABSOLUTE))
-                               buffer_rrd_value(wb, (n<0)?-n:n);
-                       else
+                       else {
+                               if(unlikely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
+                                       n = -n;
+
+                               if(unlikely(options & RRDR_OPTION_PERCENTAGE))
+                                       n = n * 100 / total;
+
                                buffer_rrd_value(wb, n);
+                       }
 
                        buffer_strcat(wb, post_value);
                }
@@ -579,24 +875,30 @@ static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
        }
 
        buffer_strcat(wb, finish);
+       //info("RRD2JSON(): %s: END", r->st->id);
 }
 
-static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startline, const char *separator, const char *endline)
+static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startline, const char *separator, const char *endline, const char *betweenlines)
 {
+       //info("RRD2CSV(): %s: BEGIN", r->st->id);
        long c, i;
        RRDDIM *d;
 
        // print the csv header
-       for(c = 0, i = 0, d = r->st->dimensions; d ;c++, d = d->next) {
+       for(c = 0, i = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
                if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
                if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
 
                if(!i) {
                        buffer_strcat(wb, startline);
+                       if(options & RRDR_OPTION_LABEL_QUOTES) buffer_strcat(wb, "\"");
                        buffer_strcat(wb, "time");
+                       if(options & RRDR_OPTION_LABEL_QUOTES) buffer_strcat(wb, "\"");
                }
                buffer_strcat(wb, separator);
+               if(options & RRDR_OPTION_LABEL_QUOTES) buffer_strcat(wb, "\"");
                buffer_strcat(wb, d->name);
+               if(options & RRDR_OPTION_LABEL_QUOTES) buffer_strcat(wb, "\"");
                i++;
        }
        buffer_strcat(wb, endline);
@@ -614,10 +916,12 @@ static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startlin
        }
 
        // for each line in the array
+       calculated_number total = 1;
        for(i = start; i != end ;i += step) {
                calculated_number *cn = &r->v[ i * r->d ];
                uint8_t *co = &r->o[ i * r->d ];
 
+               buffer_strcat(wb, betweenlines);
                buffer_strcat(wb, startline);
 
                time_t now = r->t[i];
@@ -630,13 +934,27 @@ static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startlin
                }
                else {
                        // generate the local date time
-                       struct tm *tm = localtime(&now);
+                       struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
                        if(!tm) { error("localtime() failed."); continue; }
                        buffer_date(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
                }
 
+               if(unlikely(options & RRDR_OPTION_PERCENTAGE)) {
+                       total = 0;
+                       for(c = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
+                               calculated_number n = cn[c];
+
+                               if(likely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
+                                       n = -n;
+
+                               total += n;
+                       }
+                       // prevent a division by zero
+                       if(total == 0) total = 1;
+               }
+
                // for each dimension
-               for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
+               for(c = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
                        if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
                        if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
 
@@ -650,22 +968,29 @@ static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startlin
                                else
                                        buffer_strcat(wb, "null");
                        }
-                       else if((options & RRDR_OPTION_ABSOLUTE))
-                               buffer_rrd_value(wb, (n<0)?-n:n);
-                       else
+                       else {
+                               if(unlikely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
+                                       n = -n;
+
+                               if(unlikely(options & RRDR_OPTION_PERCENTAGE))
+                                       n = n * 100 / total;
+
                                buffer_rrd_value(wb, n);
+                       }
                }
 
                buffer_strcat(wb, endline);
        }
+       //info("RRD2CSV(): %s: END", r->st->id);
 }
 
-static void rrdr2ssv(RRDR *r, BUFFER *out, uint32_t options, const char *prefix, const char *separator, const char *suffix)
+static void rrdr2ssv(RRDR *r, BUFFER *wb, uint32_t options, const char *prefix, const char *separator, const char *suffix)
 {
+       //info("RRD2SSV(): %s: BEGIN", r->st->id);
        long c, i;
        RRDDIM *d;
 
-       buffer_strcat(out, prefix);
+       buffer_strcat(wb, prefix);
        long start = 0, end = rrdr_rows(r), step = 1;
        if((options & RRDR_OPTION_REVERSED)) {
                start = rrdr_rows(r) - 1;
@@ -674,21 +999,42 @@ static void rrdr2ssv(RRDR *r, BUFFER *out, uint32_t options, const char *prefix,
        }
 
        // for each line in the array
+       calculated_number total = 1;
        for(i = start; i != end ;i += step) {
 
                calculated_number *cn = &r->v[ i * r->d ];
                uint8_t *co = &r->o[ i * r->d ];
 
-               calculated_number sum = 0, min = 0, max = 0;
+               calculated_number sum = 0, min = 0, max = 0, v;
                int all_null = 1, init = 1;
 
+               if(unlikely(options & RRDR_OPTION_PERCENTAGE)) {
+                       total = 0;
+                       for(c = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
+                               calculated_number n = cn[c];
+
+                               if(likely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
+                                       n = -n;
+
+                               total += n;
+                       }
+                       // prevent a division by zero
+                       if(total == 0) total = 1;
+               }
+
                // for each dimension
-               for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
+               for(c = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
                        if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
                        if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
 
                        calculated_number n = cn[c];
 
+                       if(likely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
+                               n = -n;
+
+                       if(unlikely(options & RRDR_OPTION_PERCENTAGE))
+                               n = n * 100 / total;
+
                        if(unlikely(init)) {
                                if(n > 0) {
                                        min = 0;
@@ -703,7 +1049,6 @@ static void rrdr2ssv(RRDR *r, BUFFER *out, uint32_t options, const char *prefix,
 
                        if(likely(!(co[c] & RRDR_EMPTY))) {
                                all_null = 0;
-                               if((options & RRDR_OPTION_ABSOLUTE) && n < 0) n = -n;
                                sum += n;
                        }
 
@@ -712,20 +1057,34 @@ static void rrdr2ssv(RRDR *r, BUFFER *out, uint32_t options, const char *prefix,
                }
 
                if(likely(i != start))
-                       buffer_strcat(out, separator);
+                       buffer_strcat(wb, separator);
 
                if(all_null) {
                        if(options & RRDR_OPTION_NULL2ZERO)
-                               buffer_strcat(out, "0");
+                               buffer_strcat(wb, "0");
                        else
-                               buffer_strcat(out, "null");
+                               buffer_strcat(wb, "null");
+               }
+               else {
+                       if(options & RRDR_OPTION_MIN2MAX)
+                               v = max - min;
+                       else
+                               v = sum;
+
+                       if(likely(i != start)) {
+                               if(r->min > v) r->min = v;
+                               if(r->max < v) r->max = v;
+                       }
+                       else {
+                               r->min = v;
+                               r->max = v;
+                       }
+
+                       buffer_rrd_value(wb, v);
                }
-               else if(options & RRDR_OPTION_MIN2MAX)
-                       buffer_rrd_value(out, max - min);
-               else
-                       buffer_rrd_value(out, sum);
        }
-       buffer_strcat(out, suffix);
+       buffer_strcat(wb, suffix);
+       //info("RRD2SSV(): %s: END", r->st->id);
 }
 
 inline static calculated_number *rrdr_line_values(RRDR *r)
@@ -796,7 +1155,7 @@ inline void rrdr_done(RRDR *r)
        r->c = 0;
 }
 
-static RRDR *rrdr_create(RRDSET *st, int n)
+static RRDR *rrdr_create(RRDSET *st, long n)
 {
        if(unlikely(!st)) {
                error("NULL value given!");
@@ -815,25 +1174,34 @@ static RRDR *rrdr_create(RRDSET *st, int n)
 
        r->n = n;
 
-       r->t = calloc(n, sizeof(time_t));
+       r->t = malloc(n * sizeof(time_t));
        if(unlikely(!r->t)) goto cleanup;
 
-       r->v = calloc(n * r->d, sizeof(calculated_number));
+       r->v = malloc(n * r->d * sizeof(calculated_number));
        if(unlikely(!r->v)) goto cleanup;
 
-       r->o = calloc(n * r->d, sizeof(uint8_t));
+       r->o = malloc(n * r->d * sizeof(uint8_t));
        if(unlikely(!r->o)) goto cleanup;
 
-       r->od = calloc(r->d, sizeof(uint8_t));
+       r->od = malloc(r->d * sizeof(uint8_t));
        if(unlikely(!r->od)) goto cleanup;
 
+       // set the hidden flag on hidden dimensions
+       int c;
+       for(c = 0, rd = st->dimensions ; rd ; c++, rd = rd->next) {
+               if(unlikely(rd->flags & RRDDIM_FLAG_HIDDEN)) r->od[c] = RRDR_HIDDEN;
+               else r->od[c] = 0;
+       }
+
        r->c = -1;
-       r->rows = 0;
+
+       r->group = 1;
+       r->update_every = 1;
 
        return r;
 
 cleanup:
-       error("Cannot allocate memory");
+       error("Cannot allocate RRDR memory for %d entries", n);
        if(likely(r)) rrdr_free(r);
        return NULL;
 }
@@ -841,6 +1209,7 @@ cleanup:
 RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int group_method)
 {
        int debug = st->debug;
+       int absolute_period_requested = -1;
 
        time_t first_entry_t = rrdset_first_entry_t(st);
        time_t last_entry_t = rrdset_last_entry_t(st);
@@ -848,11 +1217,22 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
        if(before == 0 && after == 0) {
                before = last_entry_t;
                after = first_entry_t;
+               absolute_period_requested = 0;
        }
 
        // allow relative for before and after
-       if(before <= st->update_every * st->entries) before = last_entry_t + before;
-       if(after <= st->update_every * st->entries) after = last_entry_t + after;
+       if(before <= st->update_every * st->entries) {
+               before = last_entry_t + before;
+               absolute_period_requested = 0;
+       }
+
+       if(after <= st->update_every * st->entries) {
+               after = last_entry_t + after;
+               absolute_period_requested = 0;
+       }
+
+       if(absolute_period_requested == -1)
+               absolute_period_requested = 1;
 
        // make sure they are within our timeframe
        if(before > last_entry_t) before = last_entry_t;
@@ -870,18 +1250,61 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
 
        // the duration of the chart
        time_t duration = before - after;
-       if(duration <= 0) return NULL;
+       long available_points = duration / st->update_every;
+
+       if(duration <= 0 || available_points <= 0)
+               return rrdr_create(st, 1);
 
-       // check the required points
-       if(points > duration / st->update_every) points = 0;
-       if(points <= 0) points = duration / st->update_every;
+       // check the wanted points
+       if(points < 0) points = -points;
+       if(points > available_points) points = available_points;
+       if(points == 0) points = available_points;
 
        // calculate proper grouping of source data
-       long group = duration / points;
+       long group = available_points / points;
        if(group <= 0) group = 1;
-       if(duration / group > points) group++;
 
-       // error("NEW: points=%d after=%d before=%d group=%d, duration=%d", points, after, before, group, duration);
+       // round group to the closest integer
+       if(available_points % points > points / 2) group++;
+
+       time_t after_new = after - (after % (group * st->update_every));
+       time_t before_new = before - (before % (group * st->update_every));
+       long points_new = (before_new - after_new) / st->update_every / group;
+
+       // find the starting and ending slots in our round robin db
+       long    start_at_slot = rrdset_time2slot(st, before_new),
+                       stop_at_slot = rrdset_time2slot(st, after_new);
+
+#ifdef NETDATA_INTERNAL_CHECKS
+       if(after_new < first_entry_t) {
+               error("after_new %u is too small, minimum %u", after_new, first_entry_t);
+       }
+       if(after_new > last_entry_t) {
+               error("after_new %u is too big, maximum %u", after_new, last_entry_t);
+       }
+       if(before_new < first_entry_t) {
+               error("before_new %u is too small, minimum %u", before_new, first_entry_t);
+       }
+       if(before_new > last_entry_t) {
+               error("before_new %u is too big, maximum %u", before_new, last_entry_t);
+       }
+       if(start_at_slot < 0 || start_at_slot >= st->entries) {
+               error("start_at_slot is invalid %ld, expected %ld to %ld", start_at_slot, 0, st->entries - 1);
+       }
+       if(stop_at_slot < 0 || stop_at_slot >= st->entries) {
+               error("stop_at_slot is invalid %ld, expected %ld to %ld", stop_at_slot, 0, st->entries - 1);
+       }
+       if(points_new > (before_new - after_new) / group / st->update_every + 1) {
+               error("points_new %ld is more than points %ld", points_new, (before_new - after_new) / group / st->update_every + 1);
+       }
+#endif
+
+       //info("RRD2RRDR(): %s: wanted %ld points, got %ld - group=%ld, wanted duration=%u, got %u - wanted %ld - %ld, got %ld - %ld", st->id, points, points_new, group, before - after, before_new - after_new, after, before, after_new, before_new);
+
+       after = after_new;
+       before = before_new;
+       duration = before - after;
+       points = points_new;
 
        // Now we have:
        // before = the end time of the calculation
@@ -896,11 +1319,23 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
        // initialize our result set
 
        RRDR *r = rrdr_create(st, points);
-       if(!r) return NULL;
-       if(!r->d) {
-               rrdr_free(r);
+       if(!r) {
+#ifdef NETDATA_INTERNAL_CHECKS
+               error("Cannot create RRDR for %s, after=%u, before=%u, duration=%u, points=%d", st->id, after, before, duration, points);
+#endif
                return NULL;
        }
+       if(!r->d) {
+#ifdef NETDATA_INTERNAL_CHECKS
+               error("Returning empty RRDR (no dimensions in RRDSET) for %s, after=%u, before=%u, duration=%u, points=%d", st->id, after, before, duration, points);
+#endif
+               return r;
+       }
+
+       if(absolute_period_requested == 1)
+               r->result_options |= RRDR_RESULT_OPTION_ABSOLUTE;
+       else
+               r->result_options |= RRDR_RESULT_OPTION_RELATIVE;
 
        // find how many dimensions we have
        long dimensions = r->d;
@@ -945,29 +1380,10 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
        // -------------------------------------------------------------------------
        // the main loop
 
-       long    start_at_slot = rrdset_time2slot(st, before), // rrdset_last_slot(st),
-                       stop_at_slot = rrdset_time2slot(st, after);
-
        time_t  now = rrdset_slot2time(st, start_at_slot),
                        dt = st->update_every,
                        group_start_t = 0;
 
-       if(unlikely(debug)) debug(D_RRD_STATS, "INFO  %s after_t: %lu (stop_at_t: %ld), before_t: %lu (start_at_t: %ld), start_t(now): %lu, current_entry: %ld, entries: %ld"
-                       , st->id
-                       , after
-                       , stop_at_slot
-                       , before
-                       , start_at_slot
-                       , now
-                       , st->current_entry
-                       , st->entries
-                       );
-
-       // align to group for proper panning of data
-       start_at_slot -= start_at_slot % group;
-       stop_at_slot -= stop_at_slot % group;
-       now = rrdset_slot2time(st, start_at_slot);
-
        if(unlikely(debug)) debug(D_RRD_STATS, "BEGIN %s after_t: %lu (stop_at_t: %ld), before_t: %lu (start_at_t: %ld), start_t(now): %lu, current_entry: %ld, entries: %ld"
                        , st->id
                        , after
@@ -981,6 +1397,10 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
 
        r->group = group;
        r->update_every = group * st->update_every;
+       r->before = now;
+       r->after = now;
+
+       //info("RRD2RRDR(): %s: STARTING", st->id);
 
        long slot = start_at_slot, counter = 0, stop_now = 0, added = 0, group_count = 0, add_this = 0;
        for(; !stop_now ; now -= dt, slot--, counter++) {
@@ -1002,7 +1422,9 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
                if(unlikely(now > before)) continue;
                if(unlikely(now < after)) break;
 
-               if(unlikely(group_count == 0)) group_start_t = now;
+               if(unlikely(group_count == 0)) {
+                       group_start_t = now;
+               }
                group_count++;
 
                if(unlikely(group_count == group)) {
@@ -1011,7 +1433,7 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
                }
 
                // do the calculations
-               for(rd = st->dimensions, c = 0 ; likely(rd && c < dimensions) ; rd = rd->next, c++) {
+               for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
                        storage_number n = rd->values[slot];
                        if(unlikely(!does_storage_number_exist(n))) continue;
 
@@ -1044,14 +1466,15 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
                if(unlikely(add_this)) {
                        if(unlikely(!rrdr_line_init(r, group_start_t))) break;
 
+                       r->after = now;
+
                        calculated_number *cn = rrdr_line_values(r);
                        uint8_t *co = rrdr_line_options(r);
 
-                       for(rd = st->dimensions, c = 0 ; likely(rd && c < dimensions) ; rd = rd->next, c++) {
+                       for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
 
                                // update the dimension options
                                if(likely(found_non_zero[c])) r->od[c] |= RRDR_NONZERO;
-                               if(unlikely(rd->flags & RRDDIM_FLAG_HIDDEN)) r->od[c] |= RRDR_HIDDEN;
 
                                // store the specific point options
                                co[c] = group_options[c];
@@ -1068,6 +1491,9 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
                                        cn[c] = group_values[c];
                                }
 
+                               if(cn[c] < r->min) r->min = cn[c];
+                               if(cn[c] > r->max) r->max = cn[c];
+
                                // reset them for the next loop
                                group_values[c] = 0;
                                group_counts[c] = 0;
@@ -1081,83 +1507,186 @@ RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int g
        }
 
        rrdr_done(r);
+       //info("RRD2RRDR(): %s: END %ld loops made, %ld points generated", st->id, counter, rrdr_rows(r));
+       //error("SHIFT: %s: wanted %ld points, got %ld", st->id, points, rrdr_rows(r));
        return r;
 }
 
-int rrd2format(RRDSET *st, BUFFER *out, BUFFER *dimensions, uint32_t format, long points, long long after, long long before, int group_method, uint32_t options, time_t *latest_timestamp)
+int rrd2format(RRDSET *st, BUFFER *wb, BUFFER *dimensions, uint32_t format, long points, long long after, long long before, int group_method, uint32_t options, time_t *latest_timestamp)
 {
-       RRDR *rrdr = rrd2rrdr(st, points, after, before, group_method);
-       if(!rrdr) {
-               buffer_strcat(out, "Cannot generate output with these parameters on this chart.");
+       RRDR *r = rrd2rrdr(st, points, after, before, group_method);
+       if(!r) {
+               buffer_strcat(wb, "Cannot generate output with these parameters on this chart.");
                return 500;
        }
 
+       if(r->result_options & RRDR_RESULT_OPTION_RELATIVE)
+               wb->options |= WB_CONTENT_NO_CACHEABLE;
+       else if(r->result_options & RRDR_RESULT_OPTION_ABSOLUTE)
+               wb->options |= WB_CONTENT_CACHEABLE;
+
+       options = rrdr_check_options(r, options, (dimensions)?buffer_tostring(dimensions):NULL);
+
        if(dimensions)
-               rrdr_disable_not_selected_dimensions(rrdr, buffer_tostring(dimensions));
+               rrdr_disable_not_selected_dimensions(r, buffer_tostring(dimensions));
 
-       if(latest_timestamp && rrdr_rows(rrdr) > 0)
-               *latest_timestamp = rrdr->t[rrdr_rows(rrdr) - 1];
+       if(latest_timestamp && rrdr_rows(r) > 0)
+               *latest_timestamp = r->before;
 
        switch(format) {
        case DATASOURCE_SSV:
-               out->contenttype = CT_TEXT_PLAIN;
-               rrdr2ssv(rrdr, out, options, "", " ", "");
+               if(options & RRDR_OPTION_JSON_WRAP) {
+                       wb->contenttype = CT_APPLICATION_JSON;
+                       rrdr_json_wrapper_begin(r, wb, format, options, 1);
+                       rrdr2ssv(r, wb, options, "", " ", "");
+                       rrdr_json_wrapper_end(r, wb, format, options, 1);
+               }
+               else {
+                       wb->contenttype = CT_TEXT_PLAIN;
+                       rrdr2ssv(r, wb, options, "", " ", "");
+               }
                break;
 
        case DATASOURCE_SSV_COMMA:
-               out->contenttype = CT_TEXT_PLAIN;
-               rrdr2ssv(rrdr, out, options, "", ",", "");
+               if(options & RRDR_OPTION_JSON_WRAP) {
+                       wb->contenttype = CT_APPLICATION_JSON;
+                       rrdr_json_wrapper_begin(r, wb, format, options, 1);
+                       rrdr2ssv(r, wb, options, "", ",", "");
+                       rrdr_json_wrapper_end(r, wb, format, options, 1);
+               }
+               else {
+                       wb->contenttype = CT_TEXT_PLAIN;
+                       rrdr2ssv(r, wb, options, "", ",", "");
+               }
                break;
 
        case DATASOURCE_JS_ARRAY:
-               out->contenttype = CT_APPLICATION_JSON;
-               rrdr2ssv(rrdr, out, options, "[", ",", "]");
+               if(options & RRDR_OPTION_JSON_WRAP) {
+                       wb->contenttype = CT_APPLICATION_JSON;
+                       rrdr_json_wrapper_begin(r, wb, format, options, 0);
+                       rrdr2ssv(r, wb, options, "[", ",", "]");
+                       rrdr_json_wrapper_end(r, wb, format, options, 0);
+               }
+               else {
+                       wb->contenttype = CT_APPLICATION_JSON;
+                       rrdr2ssv(r, wb, options, "[", ",", "]");
+               }
                break;
 
        case DATASOURCE_CSV:
-               out->contenttype = CT_TEXT_PLAIN;
-               rrdr2csv(rrdr, out, options, "", ",", "\r\n");
+               if(options & RRDR_OPTION_JSON_WRAP) {
+                       wb->contenttype = CT_APPLICATION_JSON;
+                       rrdr_json_wrapper_begin(r, wb, format, options, 1);
+                       rrdr2csv(r, wb, options, "", ",", "\\n", "");
+                       rrdr_json_wrapper_end(r, wb, format, options, 1);
+               }
+               else {
+                       wb->contenttype = CT_TEXT_PLAIN;
+                       rrdr2csv(r, wb, options, "", ",", "\r\n", "");
+               }
+               break;
+
+       case DATASOURCE_CSV_JSON_ARRAY:
+               wb->contenttype = CT_APPLICATION_JSON;
+               if(options & RRDR_OPTION_JSON_WRAP) {
+                       rrdr_json_wrapper_begin(r, wb, format, options, 0);
+                       buffer_strcat(wb, "[\n");
+                       rrdr2csv(r, wb, options + RRDR_OPTION_LABEL_QUOTES, "[", ",", "]", ",\n");
+                       buffer_strcat(wb, "\n]");
+                       rrdr_json_wrapper_end(r, wb, format, options, 0);
+               }
+               else {
+                       wb->contenttype = CT_TEXT_PLAIN;
+                       buffer_strcat(wb, "[\n");
+                       rrdr2csv(r, wb, options + RRDR_OPTION_LABEL_QUOTES, "[", ",", "]", ",\n");
+                       buffer_strcat(wb, "\n]");
+               }
                break;
 
        case DATASOURCE_TSV:
-               out->contenttype = CT_TEXT_PLAIN;
-               rrdr2csv(rrdr, out, options, "", "\t", "\r\n");
+               if(options & RRDR_OPTION_JSON_WRAP) {
+                       wb->contenttype = CT_APPLICATION_JSON;
+                       rrdr_json_wrapper_begin(r, wb, format, options, 1);
+                       rrdr2csv(r, wb, options, "", "\t", "\\n", "");
+                       rrdr_json_wrapper_end(r, wb, format, options, 1);
+               }
+               else {
+                       wb->contenttype = CT_TEXT_PLAIN;
+                       rrdr2csv(r, wb, options, "", "\t", "\r\n", "");
+               }
                break;
 
        case DATASOURCE_HTML:
-               out->contenttype = CT_TEXT_HTML;
-               buffer_strcat(out, "<html>\n<center><table border=\"0\" cellpadding=\"5\" cellspacing=\"5\">");
-               rrdr2csv(rrdr, out, options, "<tr><td>", "</td><td>", "</td></tr>\n");
-               buffer_strcat(out, "</table>\n</center>\n</html>\n");
+               if(options & RRDR_OPTION_JSON_WRAP) {
+                       wb->contenttype = CT_APPLICATION_JSON;
+                       rrdr_json_wrapper_begin(r, wb, format, options, 1);
+                       buffer_strcat(wb, "<html>\\n<center>\\n<table border=\\\"0\\\" cellpadding=\\\"5\\\" cellspacing=\\\"5\\\">\\n");
+                       rrdr2csv(r, wb, options, "<tr><td>", "</td><td>", "</td></tr>\\n", "");
+                       buffer_strcat(wb, "</table>\\n</center>\\n</html>\\n");
+                       rrdr_json_wrapper_end(r, wb, format, options, 1);
+               }
+               else {
+                       wb->contenttype = CT_TEXT_HTML;
+                       buffer_strcat(wb, "<html>\n<center>\n<table border=\"0\" cellpadding=\"5\" cellspacing=\"5\">\n");
+                       rrdr2csv(r, wb, options, "<tr><td>", "</td><td>", "</td></tr>\n", "");
+                       buffer_strcat(wb, "</table>\n</center>\n</html>\n");
+               }
                break;
 
        case DATASOURCE_DATATABLE_JSONP:
-               out->contenttype = CT_APPLICATION_X_JAVASCRIPT;
-               rrdr2json(rrdr, out, options, 1);
+               wb->contenttype = CT_APPLICATION_X_JAVASCRIPT;
+
+               if(options & RRDR_OPTION_JSON_WRAP)
+                       rrdr_json_wrapper_begin(r, wb, format, options, 0);
+
+               rrdr2json(r, wb, options, 1);
+
+               if(options & RRDR_OPTION_JSON_WRAP)
+                       rrdr_json_wrapper_end(r, wb, format, options, 0);
                break;
 
        case DATASOURCE_DATATABLE_JSON:
-               out->contenttype = CT_APPLICATION_JSON;
-               rrdr2json(rrdr, out, options, 1);
+               wb->contenttype = CT_APPLICATION_JSON;
+
+               if(options & RRDR_OPTION_JSON_WRAP)
+                       rrdr_json_wrapper_begin(r, wb, format, options, 0);
+
+               rrdr2json(r, wb, options, 1);
+
+               if(options & RRDR_OPTION_JSON_WRAP)
+                       rrdr_json_wrapper_end(r, wb, format, options, 0);
                break;
 
        case DATASOURCE_JSONP:
-               out->contenttype = CT_APPLICATION_X_JAVASCRIPT;
-               rrdr2json(rrdr, out, options, 0);
+               wb->contenttype = CT_APPLICATION_X_JAVASCRIPT;
+               if(options & RRDR_OPTION_JSON_WRAP)
+                       rrdr_json_wrapper_begin(r, wb, format, options, 0);
+
+               rrdr2json(r, wb, options, 0);
+
+               if(options & RRDR_OPTION_JSON_WRAP)
+                       rrdr_json_wrapper_end(r, wb, format, options, 0);
                break;
 
        case DATASOURCE_JSON:
        default:
-               out->contenttype = CT_APPLICATION_JSON;
-               rrdr2json(rrdr, out, options, 0);
+               wb->contenttype = CT_APPLICATION_JSON;
+
+               if(options & RRDR_OPTION_JSON_WRAP)
+                       rrdr_json_wrapper_begin(r, wb, format, options, 0);
+
+               rrdr2json(r, wb, options, 0);
+
+               if(options & RRDR_OPTION_JSON_WRAP)
+                       rrdr_json_wrapper_end(r, wb, format, options, 0);
                break;
        }
 
-       rrdr_free(rrdr);
+       rrdr_free(r);
        return 200;
 }
 
-unsigned long rrd_stats_json(int type, RRDSET *st, BUFFER *wb, int points, int group, int group_method, time_t after, time_t before, int only_non_zero)
+time_t rrd_stats_json(int type, RRDSET *st, BUFFER *wb, long points, long group, int group_method, time_t after, time_t before, int only_non_zero)
 {
        int c;
        pthread_rwlock_rdlock(&st->rwlock);
@@ -1330,9 +1859,10 @@ unsigned long rrd_stats_json(int type, RRDSET *st, BUFFER *wb, int points, int g
                                        , stop_at_t
                                        );
 
-               for(; !stop_now ; now -= dt, t--) {
+               long counter = 0;
+               for(; !stop_now ; now -= dt, t--, counter++) {
                        if(t < 0) t = st->entries - 1;
-                       if(t == stop_at_t) stop_now = 1;
+                       if(t == stop_at_t) stop_now = counter;
 
                        int print_this = 0;
 
@@ -1366,7 +1896,7 @@ unsigned long rrd_stats_json(int type, RRDSET *st, BUFFER *wb, int points, int g
                                }
 
                                // generate the local date time
-                               struct tm *tm = localtime(&now);
+                               struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
                                if(!tm) { error("localtime() failed."); continue; }
                                if(now > last_timestamp) last_timestamp = now;