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