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