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