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