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