]> arthur.barton.de Git - netdata.git/blob - src/rrd2json.c
Merge pull request #1003 from clinta/fpm-improvements
[netdata.git] / src / rrd2json.c
1 #include "common.h"
2
3 void rrd_stats_api_v1_chart(RRDSET *st, BUFFER *wb)
4 {
5     pthread_rwlock_rdlock(&st->rwlock);
6
7     buffer_sprintf(wb,
8         "\t\t{\n"
9         "\t\t\t\"id\": \"%s\",\n"
10         "\t\t\t\"name\": \"%s\",\n"
11         "\t\t\t\"type\": \"%s\",\n"
12         "\t\t\t\"family\": \"%s\",\n"
13         "\t\t\t\"context\": \"%s\",\n"
14         "\t\t\t\"title\": \"%s\",\n"
15         "\t\t\t\"priority\": %ld,\n"
16         "\t\t\t\"enabled\": %s,\n"
17         "\t\t\t\"units\": \"%s\",\n"
18         "\t\t\t\"data_url\": \"/api/v1/data?chart=%s\",\n"
19         "\t\t\t\"chart_type\": \"%s\",\n"
20         "\t\t\t\"duration\": %ld,\n"
21         "\t\t\t\"first_entry\": %ld,\n"
22         "\t\t\t\"last_entry\": %ld,\n"
23         "\t\t\t\"update_every\": %d,\n"
24         "\t\t\t\"dimensions\": {\n"
25         , st->id
26         , st->name
27         , st->type
28         , st->family
29         , st->context
30         , st->title
31         , st->priority
32         , st->enabled?"true":"false"
33         , st->units
34         , st->name
35         , rrdset_type_name(st->chart_type)
36         , st->entries * st->update_every
37         , rrdset_first_entry_t(st)
38         , rrdset_last_entry_t(st)
39         , st->update_every
40         );
41
42     unsigned long memory = st->memsize;
43
44     int c = 0;
45     RRDDIM *rd;
46     for(rd = st->dimensions; rd ; rd = rd->next) {
47         if(rd->flags & RRDDIM_FLAG_HIDDEN) continue;
48
49         memory += rd->memsize;
50
51         buffer_sprintf(wb,
52             "%s"
53             "\t\t\t\t\"%s\": { \"name\": \"%s\" }"
54             , c?",\n":""
55             , rd->id
56             , rd->name
57             );
58
59         c++;
60     }
61
62     buffer_strcat(wb, "\n\t\t\t},\n\t\t\t\"green\": ");
63     buffer_rrd_value(wb, st->green);
64     buffer_strcat(wb, ",\n\t\t\t\"red\": ");
65     buffer_rrd_value(wb, st->red);
66
67     buffer_sprintf(wb,
68         "\n\t\t}"
69         );
70
71     pthread_rwlock_unlock(&st->rwlock);
72 }
73
74 void rrd_stats_api_v1_charts(BUFFER *wb)
75 {
76     long c;
77     RRDSET *st;
78
79     buffer_sprintf(wb, "{\n"
80            "\t\"hostname\": \"%s\""
81         ",\n\t\"update_every\": %d"
82         ",\n\t\"history\": %d"
83         ",\n\t\"charts\": {"
84         , localhost.hostname
85         , rrd_update_every
86         , rrd_default_history_entries
87         );
88
89     pthread_rwlock_rdlock(&localhost.rrdset_root_rwlock);
90     for(st = localhost.rrdset_root, c = 0; st ; st = st->next) {
91         if(st->enabled && st->dimensions) {
92             if(c) buffer_strcat(wb, ",");
93             buffer_strcat(wb, "\n\t\t\"");
94             buffer_strcat(wb, st->id);
95             buffer_strcat(wb, "\": ");
96             rrd_stats_api_v1_chart(st, wb);
97             c++;
98         }
99     }
100     pthread_rwlock_unlock(&localhost.rrdset_root_rwlock);
101
102     buffer_strcat(wb, "\n\t}\n}\n");
103 }
104
105
106 unsigned long rrd_stats_one_json(RRDSET *st, char *options, BUFFER *wb)
107 {
108     time_t now = time(NULL);
109
110     pthread_rwlock_rdlock(&st->rwlock);
111
112     buffer_sprintf(wb,
113         "\t\t{\n"
114         "\t\t\t\"id\": \"%s\",\n"
115         "\t\t\t\"name\": \"%s\",\n"
116         "\t\t\t\"type\": \"%s\",\n"
117         "\t\t\t\"family\": \"%s\",\n"
118         "\t\t\t\"context\": \"%s\",\n"
119         "\t\t\t\"title\": \"%s\",\n"
120         "\t\t\t\"priority\": %ld,\n"
121         "\t\t\t\"enabled\": %d,\n"
122         "\t\t\t\"units\": \"%s\",\n"
123         "\t\t\t\"url\": \"/data/%s/%s\",\n"
124         "\t\t\t\"chart_type\": \"%s\",\n"
125         "\t\t\t\"counter\": %lu,\n"
126         "\t\t\t\"entries\": %ld,\n"
127         "\t\t\t\"first_entry_t\": %ld,\n"
128         "\t\t\t\"last_entry\": %lu,\n"
129         "\t\t\t\"last_entry_t\": %ld,\n"
130         "\t\t\t\"last_entry_secs_ago\": %ld,\n"
131         "\t\t\t\"update_every\": %d,\n"
132         "\t\t\t\"isdetail\": %d,\n"
133         "\t\t\t\"usec_since_last_update\": %llu,\n"
134         "\t\t\t\"collected_total\": " TOTAL_NUMBER_FORMAT ",\n"
135         "\t\t\t\"last_collected_total\": " TOTAL_NUMBER_FORMAT ",\n"
136         "\t\t\t\"dimensions\": [\n"
137         , st->id
138         , st->name
139         , st->type
140         , st->family
141         , st->context
142         , st->title
143         , st->priority
144         , st->enabled
145         , st->units
146         , st->name, options?options:""
147         , rrdset_type_name(st->chart_type)
148         , st->counter
149         , st->entries
150         , rrdset_first_entry_t(st)
151         , rrdset_last_slot(st)
152         , rrdset_last_entry_t(st)
153         , (now < rrdset_last_entry_t(st)) ? (time_t)0 : now - rrdset_last_entry_t(st)
154         , st->update_every
155         , st->isdetail
156         , st->usec_since_last_update
157         , st->collected_total
158         , st->last_collected_total
159         );
160
161     unsigned long memory = st->memsize;
162
163     RRDDIM *rd;
164     for(rd = st->dimensions; rd ; rd = rd->next) {
165
166         memory += rd->memsize;
167
168         buffer_sprintf(wb,
169             "\t\t\t\t{\n"
170             "\t\t\t\t\t\"id\": \"%s\",\n"
171             "\t\t\t\t\t\"name\": \"%s\",\n"
172             "\t\t\t\t\t\"entries\": %ld,\n"
173             "\t\t\t\t\t\"isHidden\": %d,\n"
174             "\t\t\t\t\t\"algorithm\": \"%s\",\n"
175             "\t\t\t\t\t\"multiplier\": %ld,\n"
176             "\t\t\t\t\t\"divisor\": %ld,\n"
177             "\t\t\t\t\t\"last_entry_t\": %ld,\n"
178             "\t\t\t\t\t\"collected_value\": " COLLECTED_NUMBER_FORMAT ",\n"
179             "\t\t\t\t\t\"calculated_value\": " CALCULATED_NUMBER_FORMAT ",\n"
180             "\t\t\t\t\t\"last_collected_value\": " COLLECTED_NUMBER_FORMAT ",\n"
181             "\t\t\t\t\t\"last_calculated_value\": " CALCULATED_NUMBER_FORMAT ",\n"
182             "\t\t\t\t\t\"memory\": %lu\n"
183             "\t\t\t\t}%s\n"
184             , rd->id
185             , rd->name
186             , rd->entries
187             , (rd->flags & RRDDIM_FLAG_HIDDEN)?1:0
188             , rrddim_algorithm_name(rd->algorithm)
189             , rd->multiplier
190             , rd->divisor
191             , rd->last_collected_time.tv_sec
192             , rd->collected_value
193             , rd->calculated_value
194             , rd->last_collected_value
195             , rd->last_calculated_value
196             , rd->memsize
197             , rd->next?",":""
198             );
199     }
200
201     buffer_sprintf(wb,
202         "\t\t\t],\n"
203         "\t\t\t\"memory\" : %lu\n"
204         "\t\t}"
205         , memory
206         );
207
208     pthread_rwlock_unlock(&st->rwlock);
209     return memory;
210 }
211
212 #define RRD_GRAPH_JSON_HEADER "{\n\t\"charts\": [\n"
213 #define RRD_GRAPH_JSON_FOOTER "\n\t]\n}\n"
214
215 void rrd_stats_graph_json(RRDSET *st, char *options, BUFFER *wb)
216 {
217     buffer_strcat(wb, RRD_GRAPH_JSON_HEADER);
218     rrd_stats_one_json(st, options, wb);
219     buffer_strcat(wb, RRD_GRAPH_JSON_FOOTER);
220 }
221
222 void rrd_stats_all_json(BUFFER *wb)
223 {
224     unsigned long memory = 0;
225     long c;
226     RRDSET *st;
227
228     buffer_strcat(wb, RRD_GRAPH_JSON_HEADER);
229
230     pthread_rwlock_rdlock(&localhost.rrdset_root_rwlock);
231     for(st = localhost.rrdset_root, c = 0; st ; st = st->next) {
232         if(st->enabled && st->dimensions) {
233             if(c) buffer_strcat(wb, ",\n");
234             memory += rrd_stats_one_json(st, NULL, wb);
235             c++;
236         }
237     }
238     pthread_rwlock_unlock(&localhost.rrdset_root_rwlock);
239
240     buffer_sprintf(wb, "\n\t],\n"
241         "\t\"hostname\": \"%s\",\n"
242         "\t\"update_every\": %d,\n"
243         "\t\"history\": %d,\n"
244         "\t\"memory\": %lu\n"
245         "}\n"
246         , localhost.hostname
247         , rrd_update_every
248         , rrd_default_history_entries
249         , memory
250         );
251 }
252
253
254
255 // ----------------------------------------------------------------------------
256
257 // RRDR dimension options
258 #define RRDR_EMPTY      0x01 // the dimension contains / the value is empty (null)
259 #define RRDR_RESET      0x02 // the dimension contains / the value is reset
260 #define RRDR_HIDDEN     0x04 // the dimension contains / the value is hidden
261 #define RRDR_NONZERO    0x08 // the dimension contains / the value is non-zero
262
263 // RRDR result options
264 #define RRDR_RESULT_OPTION_ABSOLUTE 0x00000001
265 #define RRDR_RESULT_OPTION_RELATIVE 0x00000002
266
267 typedef struct rrdresult {
268     RRDSET *st;         // the chart this result refers to
269
270     uint32_t result_options;    // RRDR_RESULT_OPTION_*
271
272     int d;                  // the number of dimensions
273     long n;                 // the number of values in the arrays
274     long rows;              // the number of rows used
275
276     uint8_t *od;            // the options for the dimensions
277
278     time_t *t;              // array of n timestamps
279     calculated_number *v;   // array n x d values
280     uint8_t *o;             // array n x d options
281
282     long c;                 // current line ( -1 ~ n ), ( -1 = none, use rrdr_rows() to get number of rows )
283
284     long group;             // how many collected values were grouped for each row
285     int update_every;       // what is the suggested update frequency in seconds
286
287     calculated_number min;
288     calculated_number max;
289
290     time_t before;
291     time_t after;
292
293     int has_st_lock;        // if st is read locked by us
294 } RRDR;
295
296 #define rrdr_rows(r) ((r)->rows)
297
298 /*
299 static void rrdr_dump(RRDR *r)
300 {
301     long c, i;
302     RRDDIM *d;
303
304     fprintf(stderr, "\nCHART %s (%s)\n", r->st->id, r->st->name);
305
306     for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
307         fprintf(stderr, "DIMENSION %s (%s), %s%s%s%s\n"
308                 , d->id
309                 , d->name
310                 , (r->od[c] & RRDR_EMPTY)?"EMPTY ":""
311                 , (r->od[c] & RRDR_RESET)?"RESET ":""
312                 , (r->od[c] & RRDR_HIDDEN)?"HIDDEN ":""
313                 , (r->od[c] & RRDR_NONZERO)?"NONZERO ":""
314                 );
315     }
316
317     if(r->rows <= 0) {
318         fprintf(stderr, "RRDR does not have any values in it.\n");
319         return;
320     }
321
322     fprintf(stderr, "RRDR includes %d values in it:\n", r->rows);
323
324     // for each line in the array
325     for(i = 0; i < r->rows ;i++) {
326         calculated_number *cn = &r->v[ i * r->d ];
327         uint8_t *co = &r->o[ i * r->d ];
328
329         // print the id and the timestamp of the line
330         fprintf(stderr, "%ld %ld ", i + 1, r->t[i]);
331
332         // for each dimension
333         for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
334             if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
335             if(unlikely(!(r->od[c] & RRDR_NONZERO))) continue;
336
337             if(co[c] & RRDR_EMPTY)
338                 fprintf(stderr, "null ");
339             else
340                 fprintf(stderr, CALCULATED_NUMBER_FORMAT " %s%s%s%s "
341                     , cn[c]
342                     , (co[c] & RRDR_EMPTY)?"E":" "
343                     , (co[c] & RRDR_RESET)?"R":" "
344                     , (co[c] & RRDR_HIDDEN)?"H":" "
345                     , (co[c] & RRDR_NONZERO)?"N":" "
346                     );
347         }
348
349         fprintf(stderr, "\n");
350     }
351 }
352 */
353
354 void rrdr_disable_not_selected_dimensions(RRDR *r, const char *dims)
355 {
356     char b[strlen(dims) + 1];
357     char *o = b, *tok;
358     strcpy(o, dims);
359
360     long c;
361     RRDDIM *d;
362
363     // disable all of them
364     for(c = 0, d = r->st->dimensions; d ;c++, d = d->next)
365         r->od[c] |= RRDR_HIDDEN;
366
367     while(o && *o && (tok = mystrsep(&o, ",|"))) {
368         if(!*tok) continue;
369         
370         uint32_t hash = simple_hash(tok);
371
372         // find it and enable it
373         for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
374             if(unlikely((hash == d->hash && !strcmp(d->id, tok)) || !strcmp(d->name, tok))) {
375                 r->od[c] &= ~RRDR_HIDDEN;
376
377                 // since the user needs this dimension
378                 // make it appear as NONZERO, to return it
379                 // even if the dimension has only zeros
380                 r->od[c] |= RRDR_NONZERO;
381             }
382         }
383     }
384 }
385
386 void rrdr_buffer_print_format(BUFFER *wb, uint32_t format)
387 {
388     switch(format) {
389     case DATASOURCE_JSON:
390         buffer_strcat(wb, DATASOURCE_FORMAT_JSON);
391         break;
392
393     case DATASOURCE_DATATABLE_JSON:
394         buffer_strcat(wb, DATASOURCE_FORMAT_DATATABLE_JSON);
395         break;
396
397     case DATASOURCE_DATATABLE_JSONP:
398         buffer_strcat(wb, DATASOURCE_FORMAT_DATATABLE_JSONP);
399         break;
400
401     case DATASOURCE_JSONP:
402         buffer_strcat(wb, DATASOURCE_FORMAT_JSONP);
403         break;
404
405     case DATASOURCE_SSV:
406         buffer_strcat(wb, DATASOURCE_FORMAT_SSV);
407         break;
408
409     case DATASOURCE_CSV:
410         buffer_strcat(wb, DATASOURCE_FORMAT_CSV);
411         break;
412
413     case DATASOURCE_TSV:
414         buffer_strcat(wb, DATASOURCE_FORMAT_TSV);
415         break;
416
417     case DATASOURCE_HTML:
418         buffer_strcat(wb, DATASOURCE_FORMAT_HTML);
419         break;
420
421     case DATASOURCE_JS_ARRAY:
422         buffer_strcat(wb, DATASOURCE_FORMAT_JS_ARRAY);
423         break;
424
425     case DATASOURCE_SSV_COMMA:
426         buffer_strcat(wb, DATASOURCE_FORMAT_SSV_COMMA);
427         break;
428
429     default:
430         buffer_strcat(wb, "unknown");
431         break;
432     }
433 }
434
435 uint32_t rrdr_check_options(RRDR *r, uint32_t options, const char *dims)
436 {
437     if(options & RRDR_OPTION_NONZERO) {
438         long i;
439
440         if(dims && *dims) {
441             // the caller wants specific dimensions
442             // disable NONZERO option
443             // to make sure we don't accidentally prevent
444             // the specific dimensions from being returned
445             i = 0;
446         }
447         else {
448             // find how many dimensions are not zero
449             long c;
450             RRDDIM *rd;
451             for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ; c++, rd = rd->next) {
452                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
453                 if(unlikely(!(r->od[c] & RRDR_NONZERO))) continue;
454                 i++;
455             }
456         }
457
458         // if with nonzero we get i = 0 (no dimensions will be returned)
459         // disable nonzero to show all dimensions
460         if(!i) options &= ~RRDR_OPTION_NONZERO;
461     }
462
463     return options;
464 }
465
466 void rrdr_json_wrapper_begin(RRDR *r, BUFFER *wb, uint32_t format, uint32_t options, int string_value)
467 {
468     long rows = rrdr_rows(r);
469     long c, i;
470     RRDDIM *rd;
471
472     //info("JSONWRAPPER(): %s: BEGIN", r->st->id);
473     char kq[2] = "",                    // key quote
474         sq[2] = "";                     // string quote
475
476     if( options & RRDR_OPTION_GOOGLE_JSON ) {
477         kq[0] = '\0';
478         sq[0] = '\'';
479     }
480     else {
481         kq[0] = '"';
482         sq[0] = '"';
483     }
484
485     buffer_sprintf(wb, "{\n"
486             "   %sapi%s: 1,\n"
487             "   %sid%s: %s%s%s,\n"
488             "   %sname%s: %s%s%s,\n"
489             "   %sview_update_every%s: %d,\n"
490             "   %supdate_every%s: %d,\n"
491             "   %sfirst_entry%s: %u,\n"
492             "   %slast_entry%s: %u,\n"
493             "   %sbefore%s: %u,\n"
494             "   %safter%s: %u,\n"
495             "   %sdimension_names%s: ["
496             , kq, kq
497             , kq, kq, sq, r->st->id, sq
498             , kq, kq, sq, r->st->name, sq
499             , kq, kq, r->update_every
500             , kq, kq, r->st->update_every
501             , kq, kq, (uint32_t)rrdset_first_entry_t(r->st)
502             , kq, kq, (uint32_t)rrdset_last_entry_t(r->st)
503             , kq, kq, (uint32_t)r->before
504             , kq, kq, (uint32_t)r->after
505             , kq, kq);
506
507     for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
508         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
509         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
510
511         if(i) buffer_strcat(wb, ", ");
512         buffer_strcat(wb, sq);
513         buffer_strcat(wb, rd->name);
514         buffer_strcat(wb, sq);
515         i++;
516     }
517     if(!i) {
518 #ifdef NETDATA_INTERNAL_CHECKS
519         error("RRDR is empty for %s (RRDR has %d dimensions, options is 0x%08x)", r->st->id, r->d, options);
520 #endif
521         rows = 0;
522         buffer_strcat(wb, sq);
523         buffer_strcat(wb, "no data");
524         buffer_strcat(wb, sq);
525     }
526
527     buffer_sprintf(wb, "],\n"
528             "   %sdimension_ids%s: ["
529             , kq, kq);
530
531     for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
532         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
533         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
534
535         if(i) buffer_strcat(wb, ", ");
536         buffer_strcat(wb, sq);
537         buffer_strcat(wb, rd->id);
538         buffer_strcat(wb, sq);
539         i++;
540     }
541     if(!i) {
542         rows = 0;
543         buffer_strcat(wb, sq);
544         buffer_strcat(wb, "no data");
545         buffer_strcat(wb, sq);
546     }
547
548     buffer_sprintf(wb, "],\n"
549             "   %slatest_values%s: ["
550             , kq, kq);
551
552     for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
553         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
554         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
555
556         if(i) buffer_strcat(wb, ", ");
557         i++;
558
559         storage_number n = rd->values[rrdset_last_slot(r->st)];
560
561         if(!does_storage_number_exist(n))
562             buffer_strcat(wb, "null");
563         else
564             buffer_rrd_value(wb, unpack_storage_number(n));
565     }
566     if(!i) {
567         rows = 0;
568         buffer_strcat(wb, "null");
569     }
570
571     buffer_sprintf(wb, "],\n"
572             "   %sview_latest_values%s: ["
573             , kq, kq);
574
575     i = 0;
576     if(rows) {
577         for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
578             if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
579             if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
580
581             if(i) buffer_strcat(wb, ", ");
582             i++;
583
584             calculated_number *cn = &r->v[ (0) * r->d ];
585             uint8_t *co = &r->o[ (0) * r->d ];
586
587             if(co[c] & RRDR_EMPTY)
588                 buffer_strcat(wb, "null");
589             else
590                 buffer_rrd_value(wb, cn[c]);
591         }
592     }
593     if(!i) {
594         rows = 0;
595         buffer_strcat(wb, "null");
596     }
597
598     buffer_sprintf(wb, "],\n"
599             "   %sdimensions%s: %ld,\n"
600             "   %spoints%s: %ld,\n"
601             "   %sformat%s: %s"
602             , kq, kq, i
603             , kq, kq, rows
604             , kq, kq, sq
605             );
606
607     rrdr_buffer_print_format(wb, format);
608
609     buffer_sprintf(wb, "%s,\n"
610             "   %sresult%s: "
611             , sq
612             , kq, kq
613             );
614
615     if(string_value) buffer_strcat(wb, sq);
616     //info("JSONWRAPPER(): %s: END", r->st->id);
617 }
618
619 void rrdr_json_wrapper_end(RRDR *r, BUFFER *wb, uint32_t format, uint32_t options, int string_value)
620 {
621     (void)format;
622
623     char kq[2] = "",                    // key quote
624         sq[2] = "";                     // string quote
625
626     if( options & RRDR_OPTION_GOOGLE_JSON ) {
627         kq[0] = '\0';
628         sq[0] = '\'';
629     }
630     else {
631         kq[0] = '"';
632         sq[0] = '"';
633     }
634
635     if(string_value) buffer_strcat(wb, sq);
636
637     buffer_sprintf(wb, ",\n %smin%s: ", kq, kq);
638     buffer_rrd_value(wb, r->min);
639     buffer_sprintf(wb, ",\n %smax%s: ", kq, kq);
640     buffer_rrd_value(wb, r->max);
641     buffer_strcat(wb, "\n}\n");
642 }
643
644 #define JSON_DATES_JS 1
645 #define JSON_DATES_TIMESTAMP 2
646
647 static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
648 {
649     //info("RRD2JSON(): %s: BEGIN", r->st->id);
650     int row_annotations = 0, dates, dates_with_new = 0;
651     char kq[2] = "",                    // key quote
652         sq[2] = "",                     // string quote
653         pre_label[101] = "",            // before each label
654         post_label[101] = "",           // after each label
655         pre_date[101] = "",             // the beginning of line, to the date
656         post_date[101] = "",            // closing the date
657         pre_value[101] = "",            // before each value
658         post_value[101] = "",           // after each value
659         post_line[101] = "",            // at the end of each row
660         normal_annotation[201] = "",    // default row annotation
661         overflow_annotation[201] = "",  // overflow row annotation
662         data_begin[101] = "",           // between labels and values
663         finish[101] = "";               // at the end of everything
664
665     if(datatable) {
666         dates = JSON_DATES_JS;
667         if( options & RRDR_OPTION_GOOGLE_JSON ) {
668             kq[0] = '\0';
669             sq[0] = '\'';
670         }
671         else {
672             kq[0] = '"';
673             sq[0] = '"';
674         }
675         row_annotations = 1;
676         snprintfz(pre_date,   100, "        {%sc%s:[{%sv%s:%s", kq, kq, kq, kq, sq);
677         snprintfz(post_date,  100, "%s}", sq);
678         snprintfz(pre_label,  100, ",\n     {%sid%s:%s%s,%slabel%s:%s", kq, kq, sq, sq, kq, kq, sq);
679         snprintfz(post_label, 100, "%s,%spattern%s:%s%s,%stype%s:%snumber%s}", sq, kq, kq, sq, sq, kq, kq, sq, sq);
680         snprintfz(pre_value,  100, ",{%sv%s:", kq, kq);
681         strcpy(post_value,         "}");
682         strcpy(post_line,          "]}");
683         snprintfz(data_begin, 100, "\n  ],\n    %srows%s:\n [\n", kq, kq);
684         strcpy(finish,             "\n  ]\n}");
685
686         snprintfz(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);
687         snprintfz(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
688
689         buffer_sprintf(wb, "{\n %scols%s:\n [\n", kq, kq);
690         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);
691         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);
692         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);
693
694         // remove the valueobjects flag
695         // google wants its own keys
696         if(options & RRDR_OPTION_OBJECTSROWS)
697             options &= ~RRDR_OPTION_OBJECTSROWS;
698     }
699     else {
700         kq[0] = '"';
701         sq[0] = '"';
702         if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
703             dates = JSON_DATES_TIMESTAMP;
704             dates_with_new = 0;
705         }
706         else {
707             dates = JSON_DATES_JS;
708             dates_with_new = 1;
709         }
710         if( options & RRDR_OPTION_OBJECTSROWS )
711             strcpy(pre_date, "      { ");
712         else
713             strcpy(pre_date, "      [ ");
714         strcpy(pre_label,  ", \"");
715         strcpy(post_label, "\"");
716         strcpy(pre_value,  ", ");
717         if( options & RRDR_OPTION_OBJECTSROWS )
718             strcpy(post_line, "}");
719         else
720             strcpy(post_line, "]");
721         snprintfz(data_begin, 100, "],\n    %sdata%s:\n [\n", kq, kq);
722         strcpy(finish,             "\n  ]\n}");
723
724         buffer_sprintf(wb, "{\n %slabels%s: [", kq, kq);
725         buffer_sprintf(wb, "%stime%s", sq, sq);
726     }
727
728     // -------------------------------------------------------------------------
729     // print the JSON header
730
731     long c, i;
732     RRDDIM *rd;
733
734     // print the header lines
735     for(c = 0, i = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
736         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
737         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
738
739         buffer_strcat(wb, pre_label);
740         buffer_strcat(wb, rd->name);
741         buffer_strcat(wb, post_label);
742         i++;
743     }
744     if(!i) {
745         buffer_strcat(wb, pre_label);
746         buffer_strcat(wb, "no data");
747         buffer_strcat(wb, post_label);
748     }
749
750     // print the begin of row data
751     buffer_strcat(wb, data_begin);
752
753     // if all dimensions are hidden, print a null
754     if(!i) {
755         buffer_strcat(wb, finish);
756         return;
757     }
758
759     long start = 0, end = rrdr_rows(r), step = 1;
760     if((options & RRDR_OPTION_REVERSED)) {
761         start = rrdr_rows(r) - 1;
762         end = -1;
763         step = -1;
764     }
765
766     // for each line in the array
767     calculated_number total = 1;
768     for(i = start; i != end ;i += step) {
769         calculated_number *cn = &r->v[ i * r->d ];
770         uint8_t *co = &r->o[ i * r->d ];
771
772         time_t now = r->t[i];
773
774         if(dates == JSON_DATES_JS) {
775             // generate the local date time
776             struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
777             if(!tm) { error("localtime_r() failed."); continue; }
778
779             if(likely(i != start)) buffer_strcat(wb, ",\n");
780             buffer_strcat(wb, pre_date);
781
782             if( options & RRDR_OPTION_OBJECTSROWS )
783                 buffer_sprintf(wb, "%stime%s: ", kq, kq);
784
785             if(dates_with_new)
786                 buffer_strcat(wb, "new ");
787
788             buffer_jsdate(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
789
790             buffer_strcat(wb, post_date);
791
792             if(row_annotations) {
793                 // google supports one annotation per row
794                 int annotation_found = 0;
795                 for(c = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
796                     if(co[c] & RRDR_RESET) {
797                         buffer_strcat(wb, overflow_annotation);
798                         annotation_found = 1;
799                         break;
800                     }
801                 }
802                 if(!annotation_found)
803                     buffer_strcat(wb, normal_annotation);
804             }
805         }
806         else {
807             // print the timestamp of the line
808             if(likely(i != start)) buffer_strcat(wb, ",\n");
809             buffer_strcat(wb, pre_date);
810
811             if( options & RRDR_OPTION_OBJECTSROWS )
812                 buffer_sprintf(wb, "%stime%s: ", kq, kq);
813
814             buffer_rrd_value(wb, (calculated_number)r->t[i]);
815             // in ms
816             if(options & RRDR_OPTION_MILLISECONDS) buffer_strcat(wb, "000");
817
818             buffer_strcat(wb, post_date);
819         }
820
821         if(unlikely(options & RRDR_OPTION_PERCENTAGE)) {
822             total = 0;
823             for(c = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
824                 calculated_number n = cn[c];
825
826                 if(likely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
827                     n = -n;
828
829                 total += n;
830             }
831             // prevent a division by zero
832             if(total == 0) total = 1;
833         }
834
835         // for each dimension
836         for(c = 0, rd = r->st->dimensions; rd && c < r->d ;c++, rd = rd->next) {
837             if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
838             if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
839
840             calculated_number n = cn[c];
841
842             buffer_strcat(wb, pre_value);
843
844             if( options & RRDR_OPTION_OBJECTSROWS )
845                 buffer_sprintf(wb, "%s%s%s: ", kq, rd->name, kq);
846
847             if(co[c] & RRDR_EMPTY) {
848                 if(options & RRDR_OPTION_NULL2ZERO)
849                     buffer_strcat(wb, "0");
850                 else
851                     buffer_strcat(wb, "null");
852             }
853             else {
854                 if(unlikely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
855                     n = -n;
856
857                 if(unlikely(options & RRDR_OPTION_PERCENTAGE))
858                     n = n * 100 / total;
859
860                 buffer_rrd_value(wb, n);
861             }
862
863             buffer_strcat(wb, post_value);
864         }
865
866         buffer_strcat(wb, post_line);
867     }
868
869     buffer_strcat(wb, finish);
870     //info("RRD2JSON(): %s: END", r->st->id);
871 }
872
873 static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startline, const char *separator, const char *endline, const char *betweenlines)
874 {
875     //info("RRD2CSV(): %s: BEGIN", r->st->id);
876     long c, i;
877     RRDDIM *d;
878
879     // print the csv header
880     for(c = 0, i = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
881         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
882         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
883
884         if(!i) {
885             buffer_strcat(wb, startline);
886             if(options & RRDR_OPTION_LABEL_QUOTES) buffer_strcat(wb, "\"");
887             buffer_strcat(wb, "time");
888             if(options & RRDR_OPTION_LABEL_QUOTES) buffer_strcat(wb, "\"");
889         }
890         buffer_strcat(wb, separator);
891         if(options & RRDR_OPTION_LABEL_QUOTES) buffer_strcat(wb, "\"");
892         buffer_strcat(wb, d->name);
893         if(options & RRDR_OPTION_LABEL_QUOTES) buffer_strcat(wb, "\"");
894         i++;
895     }
896     buffer_strcat(wb, endline);
897
898     if(!i) {
899         // no dimensions present
900         return;
901     }
902
903     long start = 0, end = rrdr_rows(r), step = 1;
904     if((options & RRDR_OPTION_REVERSED)) {
905         start = rrdr_rows(r) - 1;
906         end = -1;
907         step = -1;
908     }
909
910     // for each line in the array
911     calculated_number total = 1;
912     for(i = start; i != end ;i += step) {
913         calculated_number *cn = &r->v[ i * r->d ];
914         uint8_t *co = &r->o[ i * r->d ];
915
916         buffer_strcat(wb, betweenlines);
917         buffer_strcat(wb, startline);
918
919         time_t now = r->t[i];
920
921         if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
922             // print the timestamp of the line
923             buffer_rrd_value(wb, (calculated_number)now);
924             // in ms
925             if(options & RRDR_OPTION_MILLISECONDS) buffer_strcat(wb, "000");
926         }
927         else {
928             // generate the local date time
929             struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
930             if(!tm) { error("localtime() failed."); continue; }
931             buffer_date(wb, tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
932         }
933
934         if(unlikely(options & RRDR_OPTION_PERCENTAGE)) {
935             total = 0;
936             for(c = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
937                 calculated_number n = cn[c];
938
939                 if(likely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
940                     n = -n;
941
942                 total += n;
943             }
944             // prevent a division by zero
945             if(total == 0) total = 1;
946         }
947
948         // for each dimension
949         for(c = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
950             if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
951             if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
952
953             buffer_strcat(wb, separator);
954
955             calculated_number n = cn[c];
956
957             if(co[c] & RRDR_EMPTY) {
958                 if(options & RRDR_OPTION_NULL2ZERO)
959                     buffer_strcat(wb, "0");
960                 else
961                     buffer_strcat(wb, "null");
962             }
963             else {
964                 if(unlikely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
965                     n = -n;
966
967                 if(unlikely(options & RRDR_OPTION_PERCENTAGE))
968                     n = n * 100 / total;
969
970                 buffer_rrd_value(wb, n);
971             }
972         }
973
974         buffer_strcat(wb, endline);
975     }
976     //info("RRD2CSV(): %s: END", r->st->id);
977 }
978
979 inline static calculated_number rrdr2value(RRDR *r, long i, uint32_t options, int *all_values_are_null) {
980     long c;
981     RRDDIM *d;
982
983     calculated_number *cn = &r->v[ i * r->d ];
984     uint8_t *co = &r->o[ i * r->d ];
985
986     calculated_number sum = 0, min = 0, max = 0, v;
987     int all_null = 1, init = 1;
988
989     calculated_number total = 1;
990     if(unlikely(options & RRDR_OPTION_PERCENTAGE)) {
991         total = 0;
992         for(c = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
993             calculated_number n = cn[c];
994
995             if(likely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
996                 n = -n;
997
998             total += n;
999         }
1000         // prevent a division by zero
1001         if(total == 0) total = 1;
1002     }
1003
1004     // for each dimension
1005     for(c = 0, d = r->st->dimensions; d && c < r->d ;c++, d = d->next) {
1006         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
1007         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
1008
1009         calculated_number n = cn[c];
1010
1011         if(likely((options & RRDR_OPTION_ABSOLUTE) && n < 0))
1012             n = -n;
1013
1014         if(unlikely(options & RRDR_OPTION_PERCENTAGE))
1015             n = n * 100 / total;
1016
1017         if(unlikely(init)) {
1018             if(n > 0) {
1019                 min = 0;
1020                 max = n;
1021             }
1022             else {
1023                 min = n;
1024                 max = 0;
1025             }
1026             init = 0;
1027         }
1028
1029         if(likely(!(co[c] & RRDR_EMPTY))) {
1030             all_null = 0;
1031             sum += n;
1032         }
1033
1034         if(n < min) min = n;
1035         if(n > max) max = n;
1036     }
1037
1038     if(unlikely(all_null)) {
1039         if(likely(all_values_are_null))
1040             *all_values_are_null = 1;
1041         return 0;
1042     }
1043     else {
1044         if(likely(all_values_are_null))
1045             *all_values_are_null = 0;
1046     }
1047
1048     if(options & RRDR_OPTION_MIN2MAX)
1049         v = max - min;
1050     else
1051         v = sum;
1052
1053     return v;
1054 }
1055
1056 static void rrdr2ssv(RRDR *r, BUFFER *wb, uint32_t options, const char *prefix, const char *separator, const char *suffix)
1057 {
1058     //info("RRD2SSV(): %s: BEGIN", r->st->id);
1059     long i;
1060
1061     buffer_strcat(wb, prefix);
1062     long start = 0, end = rrdr_rows(r), step = 1;
1063     if((options & RRDR_OPTION_REVERSED)) {
1064         start = rrdr_rows(r) - 1;
1065         end = -1;
1066         step = -1;
1067     }
1068
1069     // for each line in the array
1070     for(i = start; i != end ;i += step) {
1071         int all_values_are_null = 0;
1072         calculated_number v = rrdr2value(r, i, options, &all_values_are_null);
1073
1074         if(likely(i != start)) {
1075             if(r->min > v) r->min = v;
1076             if(r->max < v) r->max = v;
1077         }
1078         else {
1079             r->min = v;
1080             r->max = v;
1081         }
1082
1083         if(likely(i != start))
1084             buffer_strcat(wb, separator);
1085
1086         if(all_values_are_null) {
1087             if(options & RRDR_OPTION_NULL2ZERO)
1088                 buffer_strcat(wb, "0");
1089             else
1090                 buffer_strcat(wb, "null");
1091         }
1092         else
1093             buffer_rrd_value(wb, v);
1094     }
1095     buffer_strcat(wb, suffix);
1096     //info("RRD2SSV(): %s: END", r->st->id);
1097 }
1098
1099 inline static calculated_number *rrdr_line_values(RRDR *r)
1100 {
1101     return &r->v[ r->c * r->d ];
1102 }
1103
1104 inline static uint8_t *rrdr_line_options(RRDR *r)
1105 {
1106     return &r->o[ r->c * r->d ];
1107 }
1108
1109 inline static int rrdr_line_init(RRDR *r, time_t t)
1110 {
1111     r->c++;
1112
1113     if(unlikely(r->c >= r->n)) {
1114         error("requested to step above RRDR size for chart %s", r->st->name);
1115         r->c = r->n - 1;
1116     }
1117
1118     // save the time
1119     r->t[r->c] = t;
1120
1121     return 1;
1122 }
1123
1124 inline static void rrdr_lock_rrdset(RRDR *r) {
1125     if(unlikely(!r)) {
1126         error("NULL value given!");
1127         return;
1128     }
1129
1130     pthread_rwlock_rdlock(&r->st->rwlock);
1131     r->has_st_lock = 1;
1132 }
1133
1134 inline static void rrdr_unlock_rrdset(RRDR *r) {
1135     if(unlikely(!r)) {
1136         error("NULL value given!");
1137         return;
1138     }
1139
1140     if(likely(r->has_st_lock)) {
1141         pthread_rwlock_unlock(&r->st->rwlock);
1142         r->has_st_lock = 0;
1143     }
1144 }
1145
1146 inline static void rrdr_free(RRDR *r)
1147 {
1148     if(unlikely(!r)) {
1149         error("NULL value given!");
1150         return;
1151     }
1152
1153     rrdr_unlock_rrdset(r);
1154     freez(r->t);
1155     freez(r->v);
1156     freez(r->o);
1157     freez(r->od);
1158     freez(r);
1159 }
1160
1161 inline void rrdr_done(RRDR *r)
1162 {
1163     r->rows = r->c + 1;
1164     r->c = 0;
1165 }
1166
1167 static RRDR *rrdr_create(RRDSET *st, long n)
1168 {
1169     if(unlikely(!st)) {
1170         error("NULL value given!");
1171         return NULL;
1172     }
1173
1174     RRDR *r = callocz(1, sizeof(RRDR));
1175     r->st = st;
1176
1177     rrdr_lock_rrdset(r);
1178
1179     RRDDIM *rd;
1180     for(rd = st->dimensions ; rd ; rd = rd->next) r->d++;
1181
1182     r->n = n;
1183
1184     r->t = mallocz(n * sizeof(time_t));
1185     r->v = mallocz(n * r->d * sizeof(calculated_number));
1186     r->o = mallocz(n * r->d * sizeof(uint8_t));
1187     r->od = mallocz(r->d * sizeof(uint8_t));
1188
1189     // set the hidden flag on hidden dimensions
1190     int c;
1191     for(c = 0, rd = st->dimensions ; rd ; c++, rd = rd->next) {
1192         if(unlikely(rd->flags & RRDDIM_FLAG_HIDDEN)) r->od[c] = RRDR_HIDDEN;
1193         else r->od[c] = 0;
1194     }
1195
1196     r->c = -1;
1197     r->group = 1;
1198     r->update_every = 1;
1199
1200     return r;
1201 }
1202
1203 RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int group_method, int aligned)
1204 {
1205     int debug = st->debug;
1206     int absolute_period_requested = -1;
1207
1208     time_t first_entry_t = rrdset_first_entry_t(st);
1209     time_t last_entry_t  = rrdset_last_entry_t(st);
1210
1211     if(before == 0 && after == 0) {
1212         before = last_entry_t;
1213         after = first_entry_t;
1214         absolute_period_requested = 0;
1215     }
1216
1217     // allow relative for before and after (smaller than 3 years)
1218     if(((before < 0)?-before:before) <= (3 * 365 * 86400)) {
1219         before = last_entry_t + before;
1220         absolute_period_requested = 0;
1221     }
1222
1223     if(((after < 0)?-after:after) <= (3 * 365 * 86400)) {
1224         if(after == 0) after = -st->update_every;
1225         after = before + after;
1226         absolute_period_requested = 0;
1227     }
1228
1229     if(absolute_period_requested == -1)
1230         absolute_period_requested = 1;
1231
1232     // make sure they are within our timeframe
1233     if(before > last_entry_t)  before = last_entry_t;
1234     if(before < first_entry_t) before = first_entry_t;
1235
1236     if(after > last_entry_t)  after = last_entry_t;
1237     if(after < first_entry_t) after = first_entry_t;
1238
1239     // check if they are upside down
1240     if(after > before) {
1241         time_t tmp = before;
1242         before = after;
1243         after = tmp;
1244     }
1245
1246     // the duration of the chart
1247     time_t duration = before - after;
1248     long available_points = duration / st->update_every;
1249
1250     if(duration <= 0 || available_points <= 0)
1251         return rrdr_create(st, 1);
1252
1253     // check the wanted points
1254     if(points < 0) points = -points;
1255     if(points > available_points) points = available_points;
1256     if(points == 0) points = available_points;
1257
1258     // calculate proper grouping of source data
1259     long group = available_points / points;
1260     if(group <= 0) group = 1;
1261
1262     // round group to the closest integer
1263     if(available_points % points > points / 2) group++;
1264
1265     time_t after_new  = (aligned) ? (after  - (after  % (group * st->update_every))) : after;
1266     time_t before_new = (aligned) ? (before - (before % (group * st->update_every))) : before;
1267     long points_new   = (before_new - after_new) / st->update_every / group;
1268
1269     // find the starting and ending slots in our round robin db
1270     long    start_at_slot = rrdset_time2slot(st, before_new),
1271             stop_at_slot  = rrdset_time2slot(st, after_new);
1272
1273 #ifdef NETDATA_INTERNAL_CHECKS
1274     if(after_new < first_entry_t) {
1275         error("after_new %u is too small, minimum %u", (uint32_t)after_new, (uint32_t)first_entry_t);
1276     }
1277     if(after_new > last_entry_t) {
1278         error("after_new %u is too big, maximum %u", (uint32_t)after_new, (uint32_t)last_entry_t);
1279     }
1280     if(before_new < first_entry_t) {
1281         error("before_new %u is too small, minimum %u", (uint32_t)before_new, (uint32_t)first_entry_t);
1282     }
1283     if(before_new > last_entry_t) {
1284         error("before_new %u is too big, maximum %u", (uint32_t)before_new, (uint32_t)last_entry_t);
1285     }
1286     if(start_at_slot < 0 || start_at_slot >= st->entries) {
1287         error("start_at_slot is invalid %ld, expected 0 to %ld", start_at_slot, st->entries - 1);
1288     }
1289     if(stop_at_slot < 0 || stop_at_slot >= st->entries) {
1290         error("stop_at_slot is invalid %ld, expected 0 to %ld", stop_at_slot, st->entries - 1);
1291     }
1292     if(points_new > (before_new - after_new) / group / st->update_every + 1) {
1293         error("points_new %ld is more than points %ld", points_new, (before_new - after_new) / group / st->update_every + 1);
1294     }
1295 #endif
1296
1297     //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);
1298
1299     after = after_new;
1300     before = before_new;
1301     duration = before - after;
1302     points = points_new;
1303
1304     // Now we have:
1305     // before = the end time of the calculation
1306     // after = the start time of the calculation
1307     // duration = the duration of the calculation
1308     // group = the number of source points to aggregate / group together
1309     // method = the method of grouping source points
1310     // points = the number of points to generate
1311
1312
1313     // -------------------------------------------------------------------------
1314     // initialize our result set
1315
1316     RRDR *r = rrdr_create(st, points);
1317     if(!r) {
1318 #ifdef NETDATA_INTERNAL_CHECKS
1319         error("Cannot create RRDR for %s, after=%u, before=%u, duration=%u, points=%ld", st->id, (uint32_t)after, (uint32_t)before, (uint32_t)duration, points);
1320 #endif
1321         return NULL;
1322     }
1323     if(!r->d) {
1324 #ifdef NETDATA_INTERNAL_CHECKS
1325         error("Returning empty RRDR (no dimensions in RRDSET) for %s, after=%u, before=%u, duration=%u, points=%ld", st->id, (uint32_t)after, (uint32_t)before, (uint32_t)duration, points);
1326 #endif
1327         return r;
1328     }
1329
1330     if(absolute_period_requested == 1)
1331         r->result_options |= RRDR_RESULT_OPTION_ABSOLUTE;
1332     else
1333         r->result_options |= RRDR_RESULT_OPTION_RELATIVE;
1334
1335     // find how many dimensions we have
1336     long dimensions = r->d;
1337
1338
1339     // -------------------------------------------------------------------------
1340     // checks for debugging
1341
1342     if(debug) debug(D_RRD_STATS, "INFO %s first_t: %u, last_t: %u, all_duration: %u, after: %u, before: %u, duration: %u, points: %ld, group: %ld"
1343             , st->id
1344             , (uint32_t)first_entry_t
1345             , (uint32_t)last_entry_t
1346             , (uint32_t)(last_entry_t - first_entry_t)
1347             , (uint32_t)after
1348             , (uint32_t)before
1349             , (uint32_t)duration
1350             , points
1351             , group
1352             );
1353
1354
1355     // -------------------------------------------------------------------------
1356     // temp arrays for keeping values per dimension
1357
1358     calculated_number   last_values[dimensions]; // keep the last value of each dimension
1359     calculated_number   group_values[dimensions]; // keep sums when grouping
1360     long                group_counts[dimensions]; // keep the number of values added to group_values
1361     uint8_t             group_options[dimensions];
1362     uint8_t             found_non_zero[dimensions];
1363
1364
1365     // initialize them
1366     RRDDIM *rd;
1367     long c;
1368     for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1369         last_values[c] = 0;
1370         group_values[c] = (group_method == GROUP_MAX || group_method == GROUP_MIN)?NAN:0;
1371         group_counts[c] = 0;
1372         group_options[c] = 0;
1373         found_non_zero[c] = 0;
1374     }
1375
1376
1377     // -------------------------------------------------------------------------
1378     // the main loop
1379
1380     time_t  now = rrdset_slot2time(st, start_at_slot),
1381             dt = st->update_every,
1382             group_start_t = 0;
1383
1384     if(unlikely(debug)) debug(D_RRD_STATS, "BEGIN %s after_t: %u (stop_at_t: %ld), before_t: %u (start_at_t: %ld), start_t(now): %u, current_entry: %ld, entries: %ld"
1385             , st->id
1386             , (uint32_t)after
1387             , stop_at_slot
1388             , (uint32_t)before
1389             , start_at_slot
1390             , (uint32_t)now
1391             , st->current_entry
1392             , st->entries
1393             );
1394
1395     r->group = group;
1396     r->update_every = group * st->update_every;
1397     r->before = now;
1398     r->after = now;
1399
1400     //info("RRD2RRDR(): %s: STARTING", st->id);
1401
1402     long slot = start_at_slot, counter = 0, stop_now = 0, added = 0, group_count = 0, add_this = 0;
1403     for(; !stop_now ; now -= dt, slot--, counter++) {
1404         if(unlikely(slot < 0)) slot = st->entries - 1;
1405         if(unlikely(slot == stop_at_slot)) stop_now = counter;
1406
1407         if(unlikely(debug)) debug(D_RRD_STATS, "ROW %s slot: %ld, entries_counter: %ld, group_count: %ld, added: %ld, now: %ld, %s %s"
1408                 , st->id
1409                 , slot
1410                 , counter
1411                 , group_count + 1
1412                 , added
1413                 , now
1414                 , (group_count + 1 == group)?"PRINT":"  -  "
1415                 , (now >= after && now <= before)?"RANGE":"  -  "
1416                 );
1417
1418         // make sure we return data in the proper time range
1419         if(unlikely(now > before)) continue;
1420         if(unlikely(now < after)) break;
1421
1422         if(unlikely(group_count == 0)) {
1423             group_start_t = now;
1424         }
1425         group_count++;
1426
1427         if(unlikely(group_count == group)) {
1428             if(unlikely(added >= points)) break;
1429             add_this = 1;
1430         }
1431
1432         // do the calculations
1433         for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1434             storage_number n = rd->values[slot];
1435             if(unlikely(!does_storage_number_exist(n))) continue;
1436
1437             group_counts[c]++;
1438
1439             calculated_number value = unpack_storage_number(n);
1440             if(likely(value != 0.0)) {
1441                 group_options[c] |= RRDR_NONZERO;
1442                 found_non_zero[c] = 1;
1443             }
1444
1445             if(unlikely(did_storage_number_reset(n)))
1446                 group_options[c] |= RRDR_RESET;
1447
1448             switch(group_method) {
1449                 case GROUP_MIN:
1450                     if(unlikely(isnan(group_values[c])) ||
1451                             fabsl(value) < fabsl(group_values[c]))
1452                         group_values[c] = value;
1453                     break;
1454
1455                 case GROUP_MAX:
1456                     if(unlikely(isnan(group_values[c])) ||
1457                             fabsl(value) > fabsl(group_values[c]))
1458                         group_values[c] = value;
1459                     break;
1460
1461                 default:
1462                 case GROUP_SUM:
1463                 case GROUP_AVERAGE:
1464                 case GROUP_UNDEFINED:
1465                     group_values[c] += value;
1466                     break;
1467
1468                 case GROUP_INCREMENTAL_SUM:
1469                     if(unlikely(slot == start_at_slot))
1470                         last_values[c] = value;
1471
1472                     group_values[c] += last_values[c] - value;
1473                     last_values[c] = value;
1474                     break;
1475             }
1476         }
1477
1478         // added it
1479         if(unlikely(add_this)) {
1480             if(unlikely(!rrdr_line_init(r, group_start_t))) break;
1481
1482             r->after = now;
1483
1484             calculated_number *cn = rrdr_line_values(r);
1485             uint8_t *co = rrdr_line_options(r);
1486
1487             for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1488
1489                 // update the dimension options
1490                 if(likely(found_non_zero[c])) r->od[c] |= RRDR_NONZERO;
1491
1492                 // store the specific point options
1493                 co[c] = group_options[c];
1494
1495                 // store the value
1496                 if(unlikely(group_counts[c] == 0)) {
1497                     cn[c] = 0.0;
1498                     co[c] |= RRDR_EMPTY;
1499                     group_values[c] = (group_method == GROUP_MAX || group_method == GROUP_MIN)?NAN:0;
1500                 }
1501                 else {
1502                     switch(group_method) {
1503                         case GROUP_MIN:
1504                         case GROUP_MAX:
1505                             if(unlikely(isnan(group_values[c])))
1506                                 cn[c] = 0;
1507                             else {
1508                                 cn[c] = group_values[c];
1509                                 group_values[c] = NAN;
1510                             }
1511                             break;
1512
1513                         case GROUP_SUM:
1514                         case GROUP_INCREMENTAL_SUM:
1515                             cn[c] = group_values[c];
1516                             group_values[c] = 0;
1517                             break;
1518
1519                         default:
1520                         case GROUP_AVERAGE:
1521                         case GROUP_UNDEFINED:
1522                             cn[c] = group_values[c] / group_counts[c];
1523                             group_values[c] = 0;
1524                             break;
1525                     }
1526
1527                     if(cn[c] < r->min) r->min = cn[c];
1528                     if(cn[c] > r->max) r->max = cn[c];
1529                 }
1530
1531                 // reset for the next loop
1532                 group_counts[c] = 0;
1533                 group_options[c] = 0;
1534             }
1535
1536             added++;
1537             group_count = 0;
1538             add_this = 0;
1539         }
1540     }
1541
1542     rrdr_done(r);
1543     //info("RRD2RRDR(): %s: END %ld loops made, %ld points generated", st->id, counter, rrdr_rows(r));
1544     //error("SHIFT: %s: wanted %ld points, got %ld", st->id, points, rrdr_rows(r));
1545     return r;
1546 }
1547
1548 int rrd2value(RRDSET *st, BUFFER *wb, calculated_number *n, const char *dimensions, long points, long long after, long long before, int group_method, uint32_t options, time_t *db_after, time_t *db_before, int *value_is_null)
1549 {
1550     RRDR *r = rrd2rrdr(st, points, after, before, group_method, !(options & RRDR_OPTION_NOT_ALIGNED));
1551     if(!r) {
1552         if(value_is_null) *value_is_null = 1;
1553         return 500;
1554     }
1555
1556     if(rrdr_rows(r) == 0) {
1557         rrdr_free(r);
1558
1559         if(db_after)  *db_after  = 0;
1560         if(db_before) *db_before = 0;
1561         if(value_is_null) *value_is_null = 1;
1562
1563         return 400;
1564     }
1565
1566     if(r->result_options & RRDR_RESULT_OPTION_RELATIVE)
1567         buffer_no_cacheable(wb);
1568     else if(r->result_options & RRDR_RESULT_OPTION_ABSOLUTE)
1569         buffer_cacheable(wb);
1570
1571     options = rrdr_check_options(r, options, dimensions);
1572
1573     if(dimensions)
1574         rrdr_disable_not_selected_dimensions(r, dimensions);
1575
1576     if(db_after)  *db_after  = r->after;
1577     if(db_before) *db_before = r->before;
1578
1579     long i = (options & RRDR_OPTION_REVERSED)?rrdr_rows(r) - 1:0;
1580     *n = rrdr2value(r, i, options, value_is_null);
1581
1582     rrdr_free(r);
1583     return 200;
1584 }
1585
1586 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)
1587 {
1588     RRDR *r = rrd2rrdr(st, points, after, before, group_method, !(options & RRDR_OPTION_NOT_ALIGNED));
1589     if(!r) {
1590         buffer_strcat(wb, "Cannot generate output with these parameters on this chart.");
1591         return 500;
1592     }
1593
1594     if(r->result_options & RRDR_RESULT_OPTION_RELATIVE)
1595         buffer_no_cacheable(wb);
1596     else if(r->result_options & RRDR_RESULT_OPTION_ABSOLUTE)
1597         buffer_cacheable(wb);
1598
1599     options = rrdr_check_options(r, options, (dimensions)?buffer_tostring(dimensions):NULL);
1600
1601     if(dimensions)
1602         rrdr_disable_not_selected_dimensions(r, buffer_tostring(dimensions));
1603
1604     if(latest_timestamp && rrdr_rows(r) > 0)
1605         *latest_timestamp = r->before;
1606
1607     switch(format) {
1608     case DATASOURCE_SSV:
1609         if(options & RRDR_OPTION_JSON_WRAP) {
1610             wb->contenttype = CT_APPLICATION_JSON;
1611             rrdr_json_wrapper_begin(r, wb, format, options, 1);
1612             rrdr2ssv(r, wb, options, "", " ", "");
1613             rrdr_json_wrapper_end(r, wb, format, options, 1);
1614         }
1615         else {
1616             wb->contenttype = CT_TEXT_PLAIN;
1617             rrdr2ssv(r, wb, options, "", " ", "");
1618         }
1619         break;
1620
1621     case DATASOURCE_SSV_COMMA:
1622         if(options & RRDR_OPTION_JSON_WRAP) {
1623             wb->contenttype = CT_APPLICATION_JSON;
1624             rrdr_json_wrapper_begin(r, wb, format, options, 1);
1625             rrdr2ssv(r, wb, options, "", ",", "");
1626             rrdr_json_wrapper_end(r, wb, format, options, 1);
1627         }
1628         else {
1629             wb->contenttype = CT_TEXT_PLAIN;
1630             rrdr2ssv(r, wb, options, "", ",", "");
1631         }
1632         break;
1633
1634     case DATASOURCE_JS_ARRAY:
1635         if(options & RRDR_OPTION_JSON_WRAP) {
1636             wb->contenttype = CT_APPLICATION_JSON;
1637             rrdr_json_wrapper_begin(r, wb, format, options, 0);
1638             rrdr2ssv(r, wb, options, "[", ",", "]");
1639             rrdr_json_wrapper_end(r, wb, format, options, 0);
1640         }
1641         else {
1642             wb->contenttype = CT_APPLICATION_JSON;
1643             rrdr2ssv(r, wb, options, "[", ",", "]");
1644         }
1645         break;
1646
1647     case DATASOURCE_CSV:
1648         if(options & RRDR_OPTION_JSON_WRAP) {
1649             wb->contenttype = CT_APPLICATION_JSON;
1650             rrdr_json_wrapper_begin(r, wb, format, options, 1);
1651             rrdr2csv(r, wb, options, "", ",", "\\n", "");
1652             rrdr_json_wrapper_end(r, wb, format, options, 1);
1653         }
1654         else {
1655             wb->contenttype = CT_TEXT_PLAIN;
1656             rrdr2csv(r, wb, options, "", ",", "\r\n", "");
1657         }
1658         break;
1659
1660     case DATASOURCE_CSV_JSON_ARRAY:
1661         wb->contenttype = CT_APPLICATION_JSON;
1662         if(options & RRDR_OPTION_JSON_WRAP) {
1663             rrdr_json_wrapper_begin(r, wb, format, options, 0);
1664             buffer_strcat(wb, "[\n");
1665             rrdr2csv(r, wb, options + RRDR_OPTION_LABEL_QUOTES, "[", ",", "]", ",\n");
1666             buffer_strcat(wb, "\n]");
1667             rrdr_json_wrapper_end(r, wb, format, options, 0);
1668         }
1669         else {
1670             wb->contenttype = CT_TEXT_PLAIN;
1671             buffer_strcat(wb, "[\n");
1672             rrdr2csv(r, wb, options + RRDR_OPTION_LABEL_QUOTES, "[", ",", "]", ",\n");
1673             buffer_strcat(wb, "\n]");
1674         }
1675         break;
1676
1677     case DATASOURCE_TSV:
1678         if(options & RRDR_OPTION_JSON_WRAP) {
1679             wb->contenttype = CT_APPLICATION_JSON;
1680             rrdr_json_wrapper_begin(r, wb, format, options, 1);
1681             rrdr2csv(r, wb, options, "", "\t", "\\n", "");
1682             rrdr_json_wrapper_end(r, wb, format, options, 1);
1683         }
1684         else {
1685             wb->contenttype = CT_TEXT_PLAIN;
1686             rrdr2csv(r, wb, options, "", "\t", "\r\n", "");
1687         }
1688         break;
1689
1690     case DATASOURCE_HTML:
1691         if(options & RRDR_OPTION_JSON_WRAP) {
1692             wb->contenttype = CT_APPLICATION_JSON;
1693             rrdr_json_wrapper_begin(r, wb, format, options, 1);
1694             buffer_strcat(wb, "<html>\\n<center>\\n<table border=\\\"0\\\" cellpadding=\\\"5\\\" cellspacing=\\\"5\\\">\\n");
1695             rrdr2csv(r, wb, options, "<tr><td>", "</td><td>", "</td></tr>\\n", "");
1696             buffer_strcat(wb, "</table>\\n</center>\\n</html>\\n");
1697             rrdr_json_wrapper_end(r, wb, format, options, 1);
1698         }
1699         else {
1700             wb->contenttype = CT_TEXT_HTML;
1701             buffer_strcat(wb, "<html>\n<center>\n<table border=\"0\" cellpadding=\"5\" cellspacing=\"5\">\n");
1702             rrdr2csv(r, wb, options, "<tr><td>", "</td><td>", "</td></tr>\n", "");
1703             buffer_strcat(wb, "</table>\n</center>\n</html>\n");
1704         }
1705         break;
1706
1707     case DATASOURCE_DATATABLE_JSONP:
1708         wb->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1709
1710         if(options & RRDR_OPTION_JSON_WRAP)
1711             rrdr_json_wrapper_begin(r, wb, format, options, 0);
1712
1713         rrdr2json(r, wb, options, 1);
1714
1715         if(options & RRDR_OPTION_JSON_WRAP)
1716             rrdr_json_wrapper_end(r, wb, format, options, 0);
1717         break;
1718
1719     case DATASOURCE_DATATABLE_JSON:
1720         wb->contenttype = CT_APPLICATION_JSON;
1721
1722         if(options & RRDR_OPTION_JSON_WRAP)
1723             rrdr_json_wrapper_begin(r, wb, format, options, 0);
1724
1725         rrdr2json(r, wb, options, 1);
1726
1727         if(options & RRDR_OPTION_JSON_WRAP)
1728             rrdr_json_wrapper_end(r, wb, format, options, 0);
1729         break;
1730
1731     case DATASOURCE_JSONP:
1732         wb->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1733         if(options & RRDR_OPTION_JSON_WRAP)
1734             rrdr_json_wrapper_begin(r, wb, format, options, 0);
1735
1736         rrdr2json(r, wb, options, 0);
1737
1738         if(options & RRDR_OPTION_JSON_WRAP)
1739             rrdr_json_wrapper_end(r, wb, format, options, 0);
1740         break;
1741
1742     case DATASOURCE_JSON:
1743     default:
1744         wb->contenttype = CT_APPLICATION_JSON;
1745
1746         if(options & RRDR_OPTION_JSON_WRAP)
1747             rrdr_json_wrapper_begin(r, wb, format, options, 0);
1748
1749         rrdr2json(r, wb, options, 0);
1750
1751         if(options & RRDR_OPTION_JSON_WRAP)
1752             rrdr_json_wrapper_end(r, wb, format, options, 0);
1753         break;
1754     }
1755
1756     rrdr_free(r);
1757     return 200;
1758 }
1759
1760 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)
1761 {
1762     int c;
1763     pthread_rwlock_rdlock(&st->rwlock);
1764
1765
1766     // -------------------------------------------------------------------------
1767     // switch from JSON to google JSON
1768
1769     char kq[2] = "\"";
1770     char sq[2] = "\"";
1771     switch(type) {
1772         case DATASOURCE_DATATABLE_JSON:
1773         case DATASOURCE_DATATABLE_JSONP:
1774             kq[0] = '\0';
1775             sq[0] = '\'';
1776             break;
1777
1778         case DATASOURCE_JSON:
1779         default:
1780             break;
1781     }
1782
1783
1784     // -------------------------------------------------------------------------
1785     // validate the parameters
1786
1787     if(points < 1) points = 1;
1788     if(group < 1) group = 1;
1789
1790     if(before == 0 || before > rrdset_last_entry_t(st)) before = rrdset_last_entry_t(st);
1791     if(after  == 0 || after < rrdset_first_entry_t(st)) after = rrdset_first_entry_t(st);
1792
1793     // ---
1794
1795     // our return value (the last timestamp printed)
1796     // this is required to detect re-transmit in google JSONP
1797     time_t last_timestamp = 0;
1798
1799
1800     // -------------------------------------------------------------------------
1801     // find how many dimensions we have
1802
1803     int dimensions = 0;
1804     RRDDIM *rd;
1805     for( rd = st->dimensions ; rd ; rd = rd->next) dimensions++;
1806     if(!dimensions) {
1807         pthread_rwlock_unlock(&st->rwlock);
1808         buffer_strcat(wb, "No dimensions yet.");
1809         return 0;
1810     }
1811
1812
1813     // -------------------------------------------------------------------------
1814     // prepare various strings, to speed up the loop
1815
1816     char overflow_annotation[201]; snprintfz(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);
1817     char normal_annotation[201];   snprintfz(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
1818     char pre_date[51];             snprintfz(pre_date,             50, "        {%sc%s:[{%sv%s:%s", kq, kq, kq, kq, sq);
1819     char post_date[21];            snprintfz(post_date,            20, "%s}", sq);
1820     char pre_value[21];            snprintfz(pre_value,            20, ",{%sv%s:", kq, kq);
1821     char post_value[21];           strcpy(post_value,                  "}");
1822
1823
1824     // -------------------------------------------------------------------------
1825     // checks for debugging
1826
1827     if(st->debug) {
1828         debug(D_RRD_STATS, "%s first_entry_t = %ld, last_entry_t = %ld, duration = %ld, after = %ld, before = %ld, duration = %ld, entries_to_show = %ld, group = %ld"
1829             , st->id
1830             , rrdset_first_entry_t(st)
1831             , rrdset_last_entry_t(st)
1832             , rrdset_last_entry_t(st) - rrdset_first_entry_t(st)
1833             , after
1834             , before
1835             , before - after
1836             , points
1837             , group
1838             );
1839
1840         if(before < after)
1841             debug(D_RRD_STATS, "WARNING: %s The newest value in the database (%ld) is earlier than the oldest (%ld)", st->name, before, after);
1842
1843         if((before - after) > st->entries * st->update_every)
1844             debug(D_RRD_STATS, "WARNING: %s The time difference between the oldest and the newest entries (%ld) is higher than the capacity of the database (%ld)", st->name, before - after, st->entries * st->update_every);
1845     }
1846
1847
1848     // -------------------------------------------------------------------------
1849     // temp arrays for keeping values per dimension
1850
1851     calculated_number group_values[dimensions]; // keep sums when grouping
1852     int               print_hidden[dimensions]; // keep hidden flags
1853     int               found_non_zero[dimensions];
1854     int               found_non_existing[dimensions];
1855
1856     // initialize them
1857     for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1858         group_values[c] = 0;
1859         print_hidden[c] = (rd->flags & RRDDIM_FLAG_HIDDEN)?1:0;
1860         found_non_zero[c] = 0;
1861         found_non_existing[c] = 0;
1862     }
1863
1864
1865     // error("OLD: points=%d after=%d before=%d group=%d, duration=%d", entries_to_show, before - (st->update_every * group * entries_to_show), before, group, before - after + 1);
1866     // rrd2array(st, entries_to_show, before - (st->update_every * group * entries_to_show), before, group_method, only_non_zero);
1867     // rrd2rrdr(st, entries_to_show, before - (st->update_every * group * entries_to_show), before, group_method);
1868
1869     // -------------------------------------------------------------------------
1870     // remove dimensions that contain only zeros
1871
1872     int max_loop = 1;
1873     if(only_non_zero) max_loop = 2;
1874
1875     for(; max_loop ; max_loop--) {
1876
1877         // -------------------------------------------------------------------------
1878         // print the JSON header
1879
1880         buffer_sprintf(wb, "{\n %scols%s:\n [\n", kq, kq);
1881         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);
1882         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);
1883         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);
1884
1885         // print the header for each dimension
1886         // and update the print_hidden array for the dimensions that should be hidden
1887         int pc = 0;
1888         for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1889             if(!print_hidden[c]) {
1890                 pc++;
1891                 buffer_sprintf(wb, ",\n     {%sid%s:%s%s,%slabel%s:%s%s%s,%spattern%s:%s%s,%stype%s:%snumber%s}", kq, kq, sq, sq, kq, kq, sq, rd->name, sq, kq, kq, sq, sq, kq, kq, sq, sq);
1892             }
1893         }
1894         if(!pc) {
1895             buffer_sprintf(wb, ",\n     {%sid%s:%s%s,%slabel%s:%s%s%s,%spattern%s:%s%s,%stype%s:%snumber%s}", kq, kq, sq, sq, kq, kq, sq, "no data", sq, kq, kq, sq, sq, kq, kq, sq, sq);
1896         }
1897
1898         // print the begin of row data
1899         buffer_sprintf(wb, "\n  ],\n    %srows%s:\n [\n", kq, kq);
1900
1901
1902         // -------------------------------------------------------------------------
1903         // the main loop
1904
1905         int annotate_reset = 0;
1906         int annotation_count = 0;
1907
1908         long    t = rrdset_time2slot(st, before),
1909                 stop_at_t = rrdset_time2slot(st, after),
1910                 stop_now = 0;
1911
1912         t -= t % group;
1913
1914         time_t  now = rrdset_slot2time(st, t),
1915                 dt = st->update_every;
1916
1917         long count = 0, printed = 0, group_count = 0;
1918         last_timestamp = 0;
1919
1920         if(st->debug) debug(D_RRD_STATS, "%s: REQUEST after:%u before:%u, points:%ld, group:%ld, CHART cur:%ld first: %u last:%u, CALC start_t:%ld, stop_t:%ld"
1921                     , st->id
1922                     , (uint32_t)after
1923                     , (uint32_t)before
1924                     , points
1925                     , group
1926                     , st->current_entry
1927                     , (uint32_t)rrdset_first_entry_t(st)
1928                     , (uint32_t)rrdset_last_entry_t(st)
1929                     , t
1930                     , stop_at_t
1931                     );
1932
1933         long counter = 0;
1934         for(; !stop_now ; now -= dt, t--, counter++) {
1935             if(t < 0) t = st->entries - 1;
1936             if(t == stop_at_t) stop_now = counter;
1937
1938             int print_this = 0;
1939
1940             if(st->debug) debug(D_RRD_STATS, "%s t = %ld, count = %ld, group_count = %ld, printed = %ld, now = %ld, %s %s"
1941                     , st->id
1942                     , t
1943                     , count + 1
1944                     , group_count + 1
1945                     , printed
1946                     , now
1947                     , (group_count + 1 == group)?"PRINT":"  -  "
1948                     , (now >= after && now <= before)?"RANGE":"  -  "
1949                     );
1950
1951
1952             // make sure we return data in the proper time range
1953             if(now > before) continue;
1954             if(now < after) break;
1955
1956             //if(rrdset_slot2time(st, t) != now)
1957             //  error("%s: slot=%ld, now=%ld, slot2time=%ld, diff=%ld, last_entry_t=%ld, rrdset_last_slot=%ld", st->id, t, now, rrdset_slot2time(st,t), now - rrdset_slot2time(st,t), rrdset_last_entry_t(st), rrdset_last_slot(st));
1958
1959             count++;
1960             group_count++;
1961
1962             // check if we have to print this now
1963             if(group_count == group) {
1964                 if(printed >= points) {
1965                     // debug(D_RRD_STATS, "Already printed all rows. Stopping.");
1966                     break;
1967                 }
1968
1969                 // generate the local date time
1970                 struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
1971                 if(!tm) { error("localtime() failed."); continue; }
1972                 if(now > last_timestamp) last_timestamp = now;
1973
1974                 if(printed) buffer_strcat(wb, "]},\n");
1975                 buffer_strcat(wb, pre_date);
1976                 buffer_jsdate(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
1977                 buffer_strcat(wb, post_date);
1978
1979                 print_this = 1;
1980             }
1981
1982             // do the calculations
1983             for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1984                 storage_number n = rd->values[t];
1985                 calculated_number value = unpack_storage_number(n);
1986
1987                 if(!does_storage_number_exist(n)) {
1988                     value = 0.0;
1989                     found_non_existing[c]++;
1990                 }
1991                 if(did_storage_number_reset(n)) annotate_reset = 1;
1992
1993                 switch(group_method) {
1994                     case GROUP_MAX:
1995                         if(abs(value) > abs(group_values[c])) group_values[c] = value;
1996                         break;
1997
1998                     case GROUP_SUM:
1999                         group_values[c] += value;
2000                         break;
2001
2002                     default:
2003                     case GROUP_AVERAGE:
2004                         group_values[c] += value;
2005                         if(print_this) group_values[c] /= ( group_count - found_non_existing[c] );
2006                         break;
2007                 }
2008             }
2009
2010             if(print_this) {
2011                 if(annotate_reset) {
2012                     annotation_count++;
2013                     buffer_strcat(wb, overflow_annotation);
2014                     annotate_reset = 0;
2015                 }
2016                 else
2017                     buffer_strcat(wb, normal_annotation);
2018
2019                 pc = 0;
2020                 for(c = 0 ; c < dimensions ; c++) {
2021                     if(found_non_existing[c] == group_count) {
2022                         // all entries are non-existing
2023                         pc++;
2024                         buffer_strcat(wb, pre_value);
2025                         buffer_strcat(wb, "null");
2026                         buffer_strcat(wb, post_value);
2027                     }
2028                     else if(!print_hidden[c]) {
2029                         pc++;
2030                         buffer_strcat(wb, pre_value);
2031                         buffer_rrd_value(wb, group_values[c]);
2032                         buffer_strcat(wb, post_value);
2033
2034                         if(group_values[c]) found_non_zero[c]++;
2035                     }
2036
2037                     // reset them for the next loop
2038                     group_values[c] = 0;
2039                     found_non_existing[c] = 0;
2040                 }
2041
2042                 // if all dimensions are hidden, print a null
2043                 if(!pc) {
2044                     buffer_strcat(wb, pre_value);
2045                     buffer_strcat(wb, "null");
2046                     buffer_strcat(wb, post_value);
2047                 }
2048
2049                 printed++;
2050                 group_count = 0;
2051             }
2052         }
2053
2054         if(printed) buffer_strcat(wb, "]}");
2055         buffer_strcat(wb, "\n   ]\n}\n");
2056
2057         if(only_non_zero && max_loop > 1) {
2058             int changed = 0;
2059             for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
2060                 group_values[c] = 0;
2061                 found_non_existing[c] = 0;
2062
2063                 if(!print_hidden[c] && !found_non_zero[c]) {
2064                     changed = 1;
2065                     print_hidden[c] = 1;
2066                 }
2067             }
2068
2069             if(changed) buffer_flush(wb);
2070             else break;
2071         }
2072         else break;
2073
2074     } // max_loop
2075
2076     debug(D_RRD_STATS, "RRD_STATS_JSON: %s total %lu bytes", st->name, wb->len);
2077
2078     pthread_rwlock_unlock(&st->rwlock);
2079     return last_timestamp;
2080 }