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