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