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