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