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