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