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