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