]> arthur.barton.de Git - netdata.git/blob - src/rrd2json.c
new dashboard; now charts support pan and zoom; dygraphs are also synchronized
[netdata.git] / src / rrd2json.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <pthread.h>
5 #include <sys/time.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 #include "log.h"
10 #include "common.h"
11 #include "rrd2json.h"
12
13 #define HOSTNAME_MAX 1024
14 char *hostname = "unknown";
15
16 void rrd_stats_api_v1_chart(RRDSET *st, BUFFER *wb)
17 {
18         pthread_rwlock_rdlock(&st->rwlock);
19
20         buffer_sprintf(wb,
21                 "\t\t{\n"
22                 "\t\t\t\"id\": \"%s\",\n"
23                 "\t\t\t\"name\": \"%s\",\n"
24                 "\t\t\t\"type\": \"%s\",\n"
25                 "\t\t\t\"family\": \"%s\",\n"
26                 "\t\t\t\"title\": \"%s\",\n"
27                 "\t\t\t\"priority\": %ld,\n"
28                 "\t\t\t\"enabled\": %s,\n"
29                 "\t\t\t\"units\": \"%s\",\n"
30                 "\t\t\t\"data_url\": \"/api/v1/data?chart=%s\",\n"
31                 "\t\t\t\"chart_type\": \"%s\",\n"
32                 "\t\t\t\"duration\": %ld,\n"
33                 "\t\t\t\"first_entry\": %lu,\n"
34                 "\t\t\t\"last_entry\": %lu,\n"
35                 "\t\t\t\"update_every\": %d,\n"
36                 "\t\t\t\"dimensions\": {\n"
37                 , st->id
38                 , st->name
39                 , st->type
40                 , st->family
41                 , st->title
42                 , st->priority
43                 , st->enabled?"true":"false"
44                 , st->units
45                 , st->name
46                 , rrdset_type_name(st->chart_type)
47                 , st->entries * st->update_every
48                 , rrdset_first_entry_t(st)
49                 , rrdset_last_entry_t(st)
50                 , st->update_every
51                 );
52
53         unsigned long memory = st->memsize;
54
55         int c = 0;
56         RRDDIM *rd;
57         for(rd = st->dimensions; rd ; rd = rd->next) {
58                 if(rd->flags & RRDDIM_FLAG_HIDDEN) continue;
59
60                 memory += rd->memsize;
61
62                 buffer_sprintf(wb,
63                         "%s"
64                         "\t\t\t\t\"%s\": { \"name\": \"%s\" }"
65                         , c?",\n":""
66                         , rd->id
67                         , rd->name
68                         );
69
70                 c++;
71         }
72
73         buffer_sprintf(wb,
74                 "\n\t\t\t}\n"
75                 "\t\t}"
76                 );
77
78         pthread_rwlock_unlock(&st->rwlock);
79 }
80
81 void rrd_stats_api_v1_charts(BUFFER *wb)
82 {
83         long c;
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                 , hostname
92                 , rrd_update_every
93                 , rrd_default_history_entries
94                 );
95
96         pthread_rwlock_rdlock(&rrdset_root_rwlock);
97         for(st = rrdset_root, c = 0; st ; st = st->next) {
98                 if(st->enabled) {
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(st, wb);
104                         c++;
105                 }
106         }
107         pthread_rwlock_unlock(&rrdset_root_rwlock);
108
109         buffer_strcat(wb, "\n\t}\n}\n");
110 }
111
112
113 unsigned long rrd_stats_one_json(RRDSET *st, char *options, BUFFER *wb)
114 {
115         time_t now = time(NULL);
116
117         pthread_rwlock_rdlock(&st->rwlock);
118
119         buffer_sprintf(wb,
120                 "\t\t{\n"
121                 "\t\t\t\"id\": \"%s\",\n"
122                 "\t\t\t\"name\": \"%s\",\n"
123                 "\t\t\t\"type\": \"%s\",\n"
124                 "\t\t\t\"family\": \"%s\",\n"
125                 "\t\t\t\"title\": \"%s\",\n"
126                 "\t\t\t\"priority\": %ld,\n"
127                 "\t\t\t\"enabled\": %d,\n"
128                 "\t\t\t\"units\": \"%s\",\n"
129                 "\t\t\t\"url\": \"/data/%s/%s\",\n"
130                 "\t\t\t\"chart_type\": \"%s\",\n"
131                 "\t\t\t\"counter\": %ld,\n"
132                 "\t\t\t\"entries\": %ld,\n"
133                 "\t\t\t\"first_entry_t\": %lu,\n"
134                 "\t\t\t\"last_entry\": %ld,\n"
135                 "\t\t\t\"last_entry_t\": %lu,\n"
136                 "\t\t\t\"last_entry_secs_ago\": %lu,\n"
137                 "\t\t\t\"update_every\": %d,\n"
138                 "\t\t\t\"isdetail\": %d,\n"
139                 "\t\t\t\"usec_since_last_update\": %llu,\n"
140                 "\t\t\t\"collected_total\": " TOTAL_NUMBER_FORMAT ",\n"
141                 "\t\t\t\"last_collected_total\": " TOTAL_NUMBER_FORMAT ",\n"
142                 "\t\t\t\"dimensions\": [\n"
143                 , st->id
144                 , st->name
145                 , st->type
146                 , st->family
147                 , st->title
148                 , st->priority
149                 , st->enabled
150                 , st->units
151                 , st->name, options?options:""
152                 , rrdset_type_name(st->chart_type)
153                 , st->counter
154                 , st->entries
155                 , rrdset_first_entry_t(st)
156                 , rrdset_last_slot(st)
157                 , rrdset_last_entry_t(st)
158                 , (now < rrdset_last_entry_t(st)) ? (time_t)0 : now - rrdset_last_entry_t(st)
159                 , st->update_every
160                 , st->isdetail
161                 , st->usec_since_last_update
162                 , st->collected_total
163                 , st->last_collected_total
164                 );
165
166         unsigned long memory = st->memsize;
167
168         RRDDIM *rd;
169         for(rd = st->dimensions; rd ; rd = rd->next) {
170
171                 memory += rd->memsize;
172
173                 buffer_sprintf(wb,
174                         "\t\t\t\t{\n"
175                         "\t\t\t\t\t\"id\": \"%s\",\n"
176                         "\t\t\t\t\t\"name\": \"%s\",\n"
177                         "\t\t\t\t\t\"entries\": %ld,\n"
178                         "\t\t\t\t\t\"isHidden\": %d,\n"
179                         "\t\t\t\t\t\"algorithm\": \"%s\",\n"
180                         "\t\t\t\t\t\"multiplier\": %ld,\n"
181                         "\t\t\t\t\t\"divisor\": %ld,\n"
182                         "\t\t\t\t\t\"last_entry_t\": %lu,\n"
183                         "\t\t\t\t\t\"collected_value\": " COLLECTED_NUMBER_FORMAT ",\n"
184                         "\t\t\t\t\t\"calculated_value\": " CALCULATED_NUMBER_FORMAT ",\n"
185                         "\t\t\t\t\t\"last_collected_value\": " COLLECTED_NUMBER_FORMAT ",\n"
186                         "\t\t\t\t\t\"last_calculated_value\": " CALCULATED_NUMBER_FORMAT ",\n"
187                         "\t\t\t\t\t\"memory\": %lu\n"
188                         "\t\t\t\t}%s\n"
189                         , rd->id
190                         , rd->name
191                         , rd->entries
192                         , (rd->flags & RRDDIM_FLAG_HIDDEN)?1:0
193                         , rrddim_algorithm_name(rd->algorithm)
194                         , rd->multiplier
195                         , rd->divisor
196                         , rd->last_collected_time.tv_sec
197                         , rd->collected_value
198                         , rd->calculated_value
199                         , rd->last_collected_value
200                         , rd->last_calculated_value
201                         , rd->memsize
202                         , rd->next?",":""
203                         );
204         }
205
206         buffer_sprintf(wb,
207                 "\t\t\t],\n"
208                 "\t\t\t\"memory\" : %lu\n"
209                 "\t\t}"
210                 , memory
211                 );
212
213         pthread_rwlock_unlock(&st->rwlock);
214         return memory;
215 }
216
217 #define RRD_GRAPH_JSON_HEADER "{\n\t\"charts\": [\n"
218 #define RRD_GRAPH_JSON_FOOTER "\n\t]\n}\n"
219
220 void rrd_stats_graph_json(RRDSET *st, char *options, BUFFER *wb)
221 {
222         buffer_strcat(wb, RRD_GRAPH_JSON_HEADER);
223         rrd_stats_one_json(st, options, wb);
224         buffer_strcat(wb, RRD_GRAPH_JSON_FOOTER);
225 }
226
227 void rrd_stats_all_json(BUFFER *wb)
228 {
229         unsigned long memory = 0;
230         long c;
231         RRDSET *st;
232
233         buffer_strcat(wb, RRD_GRAPH_JSON_HEADER);
234
235         pthread_rwlock_rdlock(&rrdset_root_rwlock);
236         for(st = rrdset_root, c = 0; st ; st = st->next) {
237                 if(st->enabled) {
238                         if(c) buffer_strcat(wb, ",\n");
239                         memory += rrd_stats_one_json(st, NULL, wb);
240                         c++;
241                 }
242         }
243         pthread_rwlock_unlock(&rrdset_root_rwlock);
244
245         buffer_sprintf(wb, "\n\t],\n"
246                 "\t\"hostname\": \"%s\",\n"
247                 "\t\"update_every\": %d,\n"
248                 "\t\"history\": %d,\n"
249                 "\t\"memory\": %lu\n"
250                 "}\n"
251                 , hostname
252                 , rrd_update_every
253                 , rrd_default_history_entries
254                 , memory
255                 );
256 }
257
258
259
260 // ----------------------------------------------------------------------------
261
262 // RRDR options
263 #define RRDR_EMPTY      0x01 // the dimension contains / the value is empty (null)
264 #define RRDR_RESET      0x02 // the dimension contains / the value is reset
265 #define RRDR_HIDDEN     0x04 // the dimension contains / the value is hidden
266 #define RRDR_NONZERO    0x08 // the dimension contains / the value is non-zero
267
268
269 typedef struct rrdresult {
270         RRDSET *st;                     // the chart this result refers to
271
272         int d;                                  // the number of dimensions
273         int n;                                  // the number of values in the arrays
274         int rows;                       // the number of rows used
275
276         uint8_t *od;                    // the options for the dimensions
277
278         time_t *t;                              // array of n timestamps
279         calculated_number *v;   // array n x d values
280         uint8_t *o;                             // array n x d options
281
282         int c;                                  // current line ( -1 ~ n ), ( -1 = none, use rrdr_rows() to get number of rows )
283
284         int group;                              // how many collected values were grouped for each row
285         int update_every;               // what is the suggested update frequency in seconds
286
287         calculated_number min;
288         calculated_number max;
289
290         time_t before;
291         time_t after;
292
293         int has_st_lock;                // if st is read locked by us
294 } RRDR;
295
296 #define rrdr_rows(r) ((r)->rows)
297
298 /*
299 static void rrdr_dump(RRDR *r)
300 {
301         long c, i;
302         RRDDIM *d;
303
304         fprintf(stderr, "\nCHART %s (%s)\n", r->st->id, r->st->name);
305
306         for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
307                 fprintf(stderr, "DIMENSION %s (%s), %s%s%s%s\n"
308                                 , d->id
309                                 , d->name
310                                 , (r->od[c] & RRDR_EMPTY)?"EMPTY ":""
311                                 , (r->od[c] & RRDR_RESET)?"RESET ":""
312                                 , (r->od[c] & RRDR_HIDDEN)?"HIDDEN ":""
313                                 , (r->od[c] & RRDR_NONZERO)?"NONZERO ":""
314                                 );
315         }
316
317         if(r->rows <= 0) {
318                 fprintf(stderr, "RRDR does not have any values in it.\n");
319                 return;
320         }
321
322         fprintf(stderr, "RRDR includes %d values in it:\n", r->rows);
323
324         // for each line in the array
325         for(i = 0; i < r->rows ;i++) {
326                 calculated_number *cn = &r->v[ i * r->d ];
327                 uint8_t *co = &r->o[ i * r->d ];
328
329                 // print the id and the timestamp of the line
330                 fprintf(stderr, "%ld %ld ", i + 1, r->t[i]);
331
332                 // for each dimension
333                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
334                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
335                         if(unlikely(!(r->od[c] & RRDR_NONZERO))) continue;
336
337                         if(co[c] & RRDR_EMPTY)
338                                 fprintf(stderr, "null ");
339                         else
340                                 fprintf(stderr, CALCULATED_NUMBER_FORMAT " %s%s%s%s "
341                                         , cn[c]
342                                         , (co[c] & RRDR_EMPTY)?"E":" "
343                                         , (co[c] & RRDR_RESET)?"R":" "
344                                         , (co[c] & RRDR_HIDDEN)?"H":" "
345                                         , (co[c] & RRDR_NONZERO)?"N":" "
346                                         );
347                 }
348
349                 fprintf(stderr, "\n");
350         }
351 }
352 */
353
354 void rrdr_disable_not_selected_dimensions(RRDR *r, const char *dims)
355 {
356         char b[strlen(dims) + 1];
357         char *o = b, *tok;
358         strcpy(o, dims);
359
360         long c;
361         RRDDIM *d;
362
363         // disable all of them
364         for(c = 0, d = r->st->dimensions; d ;c++, d = d->next)
365                 r->od[c] |= RRDR_HIDDEN;
366
367         while(o && *o && (tok = mystrsep(&o, ", |"))) {
368                 if(!*tok) continue;
369
370                 // find it and enable it
371                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
372                         if(!strcmp(d->name, tok)) {
373                                 r->od[c] &= ~RRDR_HIDDEN;
374                         }
375                 }
376         }
377 }
378
379 void rrdr_buffer_print_format(BUFFER *wb, uint32_t format)
380 {
381         switch(format) {
382         case DATASOURCE_JSON:
383                 buffer_strcat(wb, DATASOURCE_FORMAT_JSON);
384                 break;
385
386         case DATASOURCE_DATATABLE_JSON:
387                 buffer_strcat(wb, DATASOURCE_FORMAT_DATATABLE_JSON);
388                 break;
389
390         case DATASOURCE_DATATABLE_JSONP:
391                 buffer_strcat(wb, DATASOURCE_FORMAT_DATATABLE_JSONP);
392                 break;
393
394         case DATASOURCE_JSONP:
395                 buffer_strcat(wb, DATASOURCE_FORMAT_JSONP);
396                 break;
397
398         case DATASOURCE_SSV:
399                 buffer_strcat(wb, DATASOURCE_FORMAT_SSV);
400                 break;
401
402         case DATASOURCE_CSV:
403                 buffer_strcat(wb, DATASOURCE_FORMAT_CSV);
404                 break;
405
406         case DATASOURCE_TSV:
407                 buffer_strcat(wb, DATASOURCE_FORMAT_TSV);
408                 break;
409
410         case DATASOURCE_HTML:
411                 buffer_strcat(wb, DATASOURCE_FORMAT_HTML);
412                 break;
413
414         case DATASOURCE_JS_ARRAY:
415                 buffer_strcat(wb, DATASOURCE_FORMAT_JS_ARRAY);
416                 break;
417
418         case DATASOURCE_SSV_COMMA:
419                 buffer_strcat(wb, DATASOURCE_FORMAT_SSV_COMMA);
420                 break;
421
422         default:
423                 buffer_strcat(wb, "unknown");
424                 break;
425         }
426 }
427
428 void rrdr_json_wrapper_begin(RRDR *r, BUFFER *wb, uint32_t format, uint32_t options, int string_value)
429 {
430         char kq[2] = "",                                        // key quote
431                 sq[2] = "";                                             // string quote
432
433         if( options & RRDR_OPTION_GOOGLE_JSON ) {
434                 kq[0] = '\0';
435                 sq[0] = '\'';
436         }
437         else {
438                 kq[0] = '"';
439                 sq[0] = '"';
440         }
441
442         buffer_sprintf(wb, "{\n"
443                         "       %sid%s: %s%s%s,\n"
444                         "       %sname%s: %s%s%s,\n"
445                         "       %sview_update_every%s: %d,\n"
446                         "       %supdate_every%s: %d,\n"
447                         "       %sfirst_entry_t%s: %u, \n"
448                         "       %slast_entry_t%s: %u, \n"
449                         "       %smin%s: "
450                         , kq, kq, sq, r->st->id, sq
451                         , kq, kq, sq, r->st->name, sq
452                         , kq, kq, r->update_every
453                         , kq, kq, r->st->update_every
454                         , kq, kq, rrdset_first_entry_t(r->st)
455                         , kq, kq, rrdset_last_entry_t(r->st)
456                         , kq, kq);
457
458         buffer_rrd_value(wb, r->min);
459         buffer_sprintf(wb, ",\n %smax%s: ", kq, kq);
460         buffer_rrd_value(wb, r->max);
461         buffer_sprintf(wb, ",\n"
462                         "       %sbefore%s: %u,\n"
463                         "       %safter%s: %u,\n"
464                         "       %sdimension_names%s: ["
465                         , kq, kq, r->before
466                         , kq, kq, r->after
467                         , kq, kq);
468
469
470         long c, i;
471         RRDDIM *rd;
472         for(c = 0, i = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
473                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
474                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
475
476                 if(i) buffer_strcat(wb, ", ");
477                 buffer_strcat(wb, sq);
478                 buffer_strcat(wb, rd->name);
479                 buffer_strcat(wb, sq);
480                 i++;
481         }
482         buffer_sprintf(wb, "],\n"
483                         "       %sdimension_ids%s: ["
484                         , kq, kq);
485
486         for(c = 0, i = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
487                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
488                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
489
490                 if(i) buffer_strcat(wb, ", ");
491                 buffer_strcat(wb, sq);
492                 buffer_strcat(wb, rd->id);
493                 buffer_strcat(wb, sq);
494                 i++;
495         }
496         buffer_sprintf(wb, "],\n"
497                         "       %sdimensions%s: %d,\n"
498                         "       %spoints%s: %d,\n"
499                         "       %sformat%s: %s"
500                         , kq, kq, i
501                         , kq, kq, rrdr_rows(r)
502                         , kq, kq, sq
503                         );
504
505         rrdr_buffer_print_format(wb, format);
506
507         buffer_sprintf(wb, "%s,\n"
508                         "       %sresult%s: "
509                         , sq
510                         , kq, kq
511                         );
512
513         if(string_value) buffer_strcat(wb, sq);
514 }
515
516 void rrdr_json_wrapper_end(RRDR *r, BUFFER *wb, uint32_t format, uint32_t options, int string_value)
517 {
518         if(r) {;}
519         if(format) {;}
520
521         char sq[2] = "";                                                // string quote
522
523         if( options & RRDR_OPTION_GOOGLE_JSON )
524                 sq[0] = '\'';
525         else
526                 sq[0] = '"';
527
528         if(string_value) buffer_strcat(wb, sq);
529         buffer_strcat(wb, "\n}\n");
530 }
531
532 #define JSON_DATES_JS 1
533 #define JSON_DATES_TIMESTAMP 2
534
535 static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
536 {
537         int row_annotations = 0, dates = JSON_DATES_JS, dates_with_new = 0;
538         char kq[2] = "",                                        // key quote
539                 sq[2] = "",                                             // string quote
540                 pre_label[101] = "",                    // before each label
541                 post_label[101] = "",                   // after each label
542                 pre_date[101] = "",                             // the beginning of line, to the date
543                 post_date[101] = "",                    // closing the date
544                 pre_value[101] = "",                    // before each value
545                 post_value[101] = "",                   // after each value
546                 post_line[101] = "",                    // at the end of each row
547                 normal_annotation[201] = "",    // default row annotation
548                 overflow_annotation[201] = "",  // overflow row annotation
549                 data_begin[101] = "",                   // between labels and values
550                 finish[101] = "";                               // at the end of everything
551
552         if(datatable) {
553                 dates = JSON_DATES_JS;
554                 if( options & RRDR_OPTION_GOOGLE_JSON ) {
555                         kq[0] = '\0';
556                         sq[0] = '\'';
557                 }
558                 else {
559                         kq[0] = '"';
560                         sq[0] = '"';
561                 }
562                 row_annotations = 1;
563                 snprintf(pre_date,   100, "             {%sc%s:[{%sv%s:%s", kq, kq, kq, kq, sq);
564                 snprintf(post_date,  100, "%s}", sq);
565                 snprintf(pre_label,  100, ",\n          {%sid%s:%s%s,%slabel%s:%s", kq, kq, sq, sq, kq, kq, sq);
566                 snprintf(post_label, 100, "%s,%spattern%s:%s%s,%stype%s:%snumber%s}", sq, kq, kq, sq, sq, kq, kq, sq, sq);
567                 snprintf(pre_value,  100, ",{%sv%s:", kq, kq);
568                 snprintf(post_value, 100, "}");
569                 snprintf(post_line,  100, "]}");
570                 snprintf(data_begin, 100, "\n   ],\n    %srows%s:\n     [\n", kq, kq);
571                 snprintf(finish,     100, "\n   ]\n}\n");
572
573                 snprintf(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);
574                 snprintf(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
575
576                 buffer_sprintf(wb, "{\n %scols%s:\n     [\n", kq, kq, kq, kq);
577                 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);
578                 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);
579                 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);
580
581                 // remove the valueobjects flag
582                 // google wants its own keys
583                 if(options & RRDR_OPTION_OBJECTSROWS)
584                         options &= ~RRDR_OPTION_OBJECTSROWS;
585         }
586         else {
587                 kq[0] = '"';
588                 sq[0] = '"';
589                 if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
590                         dates = JSON_DATES_TIMESTAMP;
591                         dates_with_new = 0;
592                 }
593                 else {
594                         dates = JSON_DATES_JS;
595                         dates_with_new = 1;
596                 }
597                 if( options & RRDR_OPTION_OBJECTSROWS )
598                         snprintf(pre_date,   100, "             { ");
599                 else
600                         snprintf(pre_date,   100, "             [ ");
601                 snprintf(pre_label,  100, ", \"");
602                 snprintf(post_label, 100, "\"");
603                 snprintf(pre_value,  100, ", ");
604                 if( options & RRDR_OPTION_OBJECTSROWS )
605                         snprintf(post_line,  100, "}");
606                 else
607                         snprintf(post_line,  100, "]");
608                 snprintf(data_begin, 100, "],\n %sdata%s:\n     [\n", kq, kq);
609                 snprintf(finish,     100, "\n   ]\n}\n");
610
611                 buffer_sprintf(wb, "{\n %slabels%s: [", kq, kq);
612                 buffer_sprintf(wb, "%stime%s", sq, sq);
613         }
614
615         // -------------------------------------------------------------------------
616         // print the JSON header
617
618         long c, i;
619         RRDDIM *rd;
620
621         // print the header lines
622         for(c = 0, i = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
623                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
624                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
625
626                 buffer_strcat(wb, pre_label);
627                 buffer_strcat(wb, rd->name);
628                 buffer_strcat(wb, post_label);
629                 i++;
630         }
631         if(!i) {
632                 buffer_strcat(wb, pre_label);
633                 buffer_strcat(wb, "no data");
634                 buffer_strcat(wb, post_label);
635         }
636
637         // print the begin of row data
638         buffer_strcat(wb, data_begin);
639
640         // if all dimensions are hidden, print a null
641         if(!i) {
642                 buffer_strcat(wb, pre_value);
643                 if(options & RRDR_OPTION_NULL2ZERO)
644                         buffer_strcat(wb, "0");
645                 else
646                         buffer_strcat(wb, "null");
647                 buffer_strcat(wb, post_value);
648         }
649
650         long start = 0, end = rrdr_rows(r), step = 1;
651         if((options & RRDR_OPTION_REVERSED)) {
652                 start = rrdr_rows(r) - 1;
653                 end = -1;
654                 step = -1;
655         }
656
657         // for each line in the array
658         for(i = start; i != end ;i += step) {
659                 calculated_number *cn = &r->v[ i * r->d ];
660                 uint8_t *co = &r->o[ i * r->d ];
661
662                 time_t now = r->t[i];
663
664                 if(dates == JSON_DATES_JS) {
665                         // generate the local date time
666                         struct tm *tm = localtime(&now);
667                         if(!tm) { error("localtime() failed."); continue; }
668
669                         if(likely(i != start)) buffer_strcat(wb, ",\n");
670                         buffer_strcat(wb, pre_date);
671
672                         if( options & RRDR_OPTION_OBJECTSROWS )
673                                 buffer_sprintf(wb, "%stime%s: ", kq, kq);
674
675                         if(dates_with_new)
676                                 buffer_strcat(wb, "new ");
677
678                         buffer_jsdate(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
679
680                         buffer_strcat(wb, post_date);
681
682                         if(row_annotations) {
683                                 // google supports one annotation per row
684                                 int annotation_found = 0;
685                                 for(c = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
686                                         if(co[c] & RRDR_RESET) {
687                                                 buffer_strcat(wb, overflow_annotation);
688                                                 annotation_found = 1;
689                                                 break;
690                                         }
691                                 }
692                                 if(!annotation_found)
693                                         buffer_strcat(wb, normal_annotation);
694                         }
695                 }
696                 else {
697                         // print the timestamp of the line
698                         if(likely(i != start)) buffer_strcat(wb, ",\n");
699                         buffer_strcat(wb, pre_date);
700
701                         if( options & RRDR_OPTION_OBJECTSROWS )
702                                 buffer_sprintf(wb, "%stime%s: ", kq, kq);
703
704                         buffer_rrd_value(wb, (calculated_number)r->t[i]);
705                         // in ms
706                         if(options & RRDR_OPTION_MILLISECONDS) buffer_strcat(wb, "000");
707
708                         buffer_strcat(wb, post_date);
709                 }
710
711                 // for each dimension
712                 for(c = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
713                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
714                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
715
716                         calculated_number n = cn[c];
717
718                         buffer_strcat(wb, pre_value);
719
720                         if( options & RRDR_OPTION_OBJECTSROWS )
721                                 buffer_sprintf(wb, "%s%s%s: ", kq, rd->name, kq);
722
723                         if(co[c] & RRDR_EMPTY) {
724                                 if(options & RRDR_OPTION_NULL2ZERO)
725                                         buffer_strcat(wb, "0");
726                                 else
727                                         buffer_strcat(wb, "null");
728                         }
729                         else if((options & RRDR_OPTION_ABSOLUTE))
730                                 buffer_rrd_value(wb, (n<0)?-n:n);
731                         else
732                                 buffer_rrd_value(wb, n);
733
734                         buffer_strcat(wb, post_value);
735                 }
736
737                 buffer_strcat(wb, post_line);
738         }
739
740         buffer_strcat(wb, finish);
741 }
742
743 static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startline, const char *separator, const char *endline)
744 {
745         long c, i;
746         RRDDIM *d;
747
748         // print the csv header
749         for(c = 0, i = 0, d = r->st->dimensions; d ;c++, d = d->next) {
750                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
751                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
752
753                 if(!i) {
754                         buffer_strcat(wb, startline);
755                         buffer_strcat(wb, "time");
756                 }
757                 buffer_strcat(wb, separator);
758                 buffer_strcat(wb, d->name);
759                 i++;
760         }
761         buffer_strcat(wb, endline);
762
763         if(!i) {
764                 // no dimensions present
765                 return;
766         }
767
768         long start = 0, end = rrdr_rows(r), step = 1;
769         if((options & RRDR_OPTION_REVERSED)) {
770                 start = rrdr_rows(r) - 1;
771                 end = -1;
772                 step = -1;
773         }
774
775         // for each line in the array
776         for(i = start; i != end ;i += step) {
777                 calculated_number *cn = &r->v[ i * r->d ];
778                 uint8_t *co = &r->o[ i * r->d ];
779
780                 buffer_strcat(wb, startline);
781
782                 time_t now = r->t[i];
783
784                 if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
785                         // print the timestamp of the line
786                         buffer_rrd_value(wb, (calculated_number)now);
787                         // in ms
788                         if(options & RRDR_OPTION_MILLISECONDS) buffer_strcat(wb, "000");
789                 }
790                 else {
791                         // generate the local date time
792                         struct tm *tm = localtime(&now);
793                         if(!tm) { error("localtime() failed."); continue; }
794                         buffer_date(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
795                 }
796
797                 // for each dimension
798                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
799                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
800                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
801
802                         buffer_strcat(wb, separator);
803
804                         calculated_number n = cn[c];
805
806                         if(co[c] & RRDR_EMPTY) {
807                                 if(options & RRDR_OPTION_NULL2ZERO)
808                                         buffer_strcat(wb, "0");
809                                 else
810                                         buffer_strcat(wb, "null");
811                         }
812                         else if((options & RRDR_OPTION_ABSOLUTE))
813                                 buffer_rrd_value(wb, (n<0)?-n:n);
814                         else
815                                 buffer_rrd_value(wb, n);
816                 }
817
818                 buffer_strcat(wb, endline);
819         }
820 }
821
822 static void rrdr2ssv(RRDR *r, BUFFER *wb, uint32_t options, const char *prefix, const char *separator, const char *suffix)
823 {
824         long c, i;
825         RRDDIM *d;
826
827         buffer_strcat(wb, prefix);
828         long start = 0, end = rrdr_rows(r), step = 1;
829         if((options & RRDR_OPTION_REVERSED)) {
830                 start = rrdr_rows(r) - 1;
831                 end = -1;
832                 step = -1;
833         }
834
835         // for each line in the array
836         for(i = start; i != end ;i += step) {
837
838                 calculated_number *cn = &r->v[ i * r->d ];
839                 uint8_t *co = &r->o[ i * r->d ];
840
841                 calculated_number sum = 0, min = 0, max = 0;
842                 int all_null = 1, init = 1;
843
844                 // for each dimension
845                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
846                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
847                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
848
849                         calculated_number n = cn[c];
850
851                         if(unlikely(init)) {
852                                 if(n > 0) {
853                                         min = 0;
854                                         max = n;
855                                 }
856                                 else {
857                                         min = n;
858                                         max = 0;
859                                 }
860                                 init = 0;
861                         }
862
863                         if(likely(!(co[c] & RRDR_EMPTY))) {
864                                 all_null = 0;
865                                 if((options & RRDR_OPTION_ABSOLUTE) && n < 0) n = -n;
866                                 sum += n;
867                         }
868
869                         if(n < min) min = n;
870                         if(n > max) max = n;
871                 }
872
873                 if(likely(i != start))
874                         buffer_strcat(wb, separator);
875
876                 if(all_null) {
877                         if(options & RRDR_OPTION_NULL2ZERO)
878                                 buffer_strcat(wb, "0");
879                         else
880                                 buffer_strcat(wb, "null");
881                 }
882                 else if(options & RRDR_OPTION_MIN2MAX)
883                         buffer_rrd_value(wb, max - min);
884                 else
885                         buffer_rrd_value(wb, sum);
886         }
887         buffer_strcat(wb, suffix);
888 }
889
890 inline static calculated_number *rrdr_line_values(RRDR *r)
891 {
892         return &r->v[ r->c * r->d ];
893 }
894
895 inline static uint8_t *rrdr_line_options(RRDR *r)
896 {
897         return &r->o[ r->c * r->d ];
898 }
899
900 inline static int rrdr_line_init(RRDR *r, time_t t)
901 {
902         r->c++;
903
904         if(unlikely(r->c >= r->n)) {
905                 error("requested to step above RRDR size for chart %s", r->st->name);
906                 r->c = r->n - 1;
907         }
908
909         // save the time
910         r->t[r->c] = t;
911
912         return 1;
913 }
914
915 inline static void rrdr_lock_rrdset(RRDR *r) {
916         if(unlikely(!r)) {
917                 error("NULL value given!");
918                 return;
919         }
920
921         pthread_rwlock_rdlock(&r->st->rwlock);
922         r->has_st_lock = 1;
923 }
924
925 inline static void rrdr_unlock_rrdset(RRDR *r) {
926         if(unlikely(!r)) {
927                 error("NULL value given!");
928                 return;
929         }
930
931         if(likely(r->has_st_lock)) {
932                 pthread_rwlock_unlock(&r->st->rwlock);
933                 r->has_st_lock = 0;
934         }
935 }
936
937 inline static void rrdr_free(RRDR *r)
938 {
939         if(unlikely(!r)) {
940                 error("NULL value given!");
941                 return;
942         }
943
944         rrdr_unlock_rrdset(r);
945         if(likely(r->t)) free(r->t);
946         if(likely(r->v)) free(r->v);
947         if(likely(r->o)) free(r->o);
948         if(likely(r->od)) free(r->od);
949         free(r);
950 }
951
952 inline void rrdr_done(RRDR *r)
953 {
954         r->rows = r->c + 1;
955         r->c = 0;
956 }
957
958 static RRDR *rrdr_create(RRDSET *st, int n)
959 {
960         if(unlikely(!st)) {
961                 error("NULL value given!");
962                 return NULL;
963         }
964
965         RRDR *r = malloc(sizeof(RRDR));
966         if(unlikely(!r)) goto cleanup;
967
968         r->st = st;
969         r->has_st_lock = 0;
970
971         rrdr_lock_rrdset(r);
972
973         RRDDIM *rd;
974         for(rd = st->dimensions ; rd ; rd = rd->next) r->d++;
975
976         r->n = n;
977
978         r->t = malloc(n * sizeof(time_t));
979         if(unlikely(!r->t)) goto cleanup;
980
981         r->v = malloc(n * r->d * sizeof(calculated_number));
982         if(unlikely(!r->v)) goto cleanup;
983
984         r->o = malloc(n * r->d * sizeof(uint8_t));
985         if(unlikely(!r->o)) goto cleanup;
986
987         r->od = malloc(r->d * sizeof(uint8_t));
988         if(unlikely(!r->od)) goto cleanup;
989
990         r->c = -1;
991         r->rows = 0;
992
993         r->group = 1;
994         r->update_every = 1;
995
996         r->min = 0.0;
997         r->max = 0.0;
998
999         r->before = 0;
1000         r->after = 0;
1001
1002         return r;
1003
1004 cleanup:
1005         error("Cannot allocate RRDR memory for %d entries", n);
1006         if(likely(r)) rrdr_free(r);
1007         return NULL;
1008 }
1009
1010 RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int group_method)
1011 {
1012         int debug = st->debug;
1013
1014         time_t first_entry_t = rrdset_first_entry_t(st);
1015         time_t last_entry_t = rrdset_last_entry_t(st);
1016
1017         if(before == 0 && after == 0) {
1018                 before = last_entry_t;
1019                 after = first_entry_t;
1020         }
1021
1022         // allow relative for before and after
1023         if(before <= st->update_every * st->entries)
1024                 before = last_entry_t + before;
1025
1026         if(after <= st->update_every * st->entries)
1027                 after = last_entry_t + after;
1028
1029         // make sure they are within our timeframe
1030         if(before > last_entry_t) before = last_entry_t;
1031         if(before < first_entry_t) before = first_entry_t;
1032
1033         if(after > last_entry_t) after = last_entry_t;
1034         if(after < first_entry_t) after = first_entry_t;
1035
1036         // check if they are upside down
1037         if(after > before) {
1038                 time_t tmp = before;
1039                 before = after;
1040                 after = tmp;
1041         }
1042
1043         // the duration of the chart
1044         time_t duration = before - after;
1045         if(duration <= 0) return NULL;
1046
1047         // how many points does the chart has?
1048         long available_points = duration / st->update_every;
1049
1050         // check the wanted points
1051         if(points < 0) points = -points;
1052         if(points > available_points) points = available_points;
1053         if(points == 0) points = available_points;
1054
1055         // calculate proper grouping of source data
1056         long group = available_points / points;
1057         if(group <= 0) group = 1;
1058
1059         // round group to the closest integer
1060         if(available_points % points > points / 2) group++;
1061
1062         time_t after_new = after - (after % (group * st->update_every));
1063         time_t before_new = before - (before % (group * st->update_every));
1064         long points_new = (before_new - after_new) / st->update_every / group;
1065
1066         // find the starting and ending slots in our round robin db
1067         long    start_at_slot = rrdset_time2slot(st, before_new),
1068                         stop_at_slot = rrdset_time2slot(st, after_new);
1069
1070         if(after_new < first_entry_t) {
1071                 error("after_new %u is too small, minimum %u", after_new, first_entry_t);
1072         }
1073         if(after_new > last_entry_t) {
1074                 error("after_new %u is too big, maximum %u", after_new, last_entry_t);
1075         }
1076         if(before_new < first_entry_t) {
1077                 error("before_new %u is too small, minimum %u", before_new, first_entry_t);
1078         }
1079         if(before_new > last_entry_t) {
1080                 error("before_new %u is too big, maximum %u", before_new, last_entry_t);
1081         }
1082         if(start_at_slot < 0 || start_at_slot >= st->entries) {
1083                 error("start_at_slot is invalid %ld, expected %ld to %ld", start_at_slot, 0, st->entries - 1);
1084                 start_at_slot = st->current_entry;
1085         }
1086         if(stop_at_slot < 0 || stop_at_slot >= st->entries) {
1087                 error("stop_at_slot is invalid %ld, expected %ld to %ld", stop_at_slot, 0, st->entries - 1);
1088                 stop_at_slot = 0;
1089         }
1090         if(points_new > (before_new - after_new) / group / st->update_every + 1) {
1091                 error("points_new %ld is more than points %ld", points_new, (before_new - after_new) / group / st->update_every + 1);
1092         }
1093
1094         // error("SHIFT: %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);
1095
1096         after = after_new;
1097         before = before_new;
1098         duration = before - after;
1099         points = points_new;
1100
1101         // Now we have:
1102         // before = the end time of the calculation
1103         // after = the start time of the calculation
1104         // duration = the duration of the calculation
1105         // group = the number of source points to aggregate / group together
1106         // method = the method of grouping source points
1107         // points = the number of points to generate
1108
1109
1110         // -------------------------------------------------------------------------
1111         // initialize our result set
1112
1113         RRDR *r = rrdr_create(st, points);
1114         if(!r) return NULL;
1115         if(!r->d) {
1116                 rrdr_free(r);
1117                 return NULL;
1118         }
1119
1120         // find how many dimensions we have
1121         long dimensions = r->d;
1122
1123
1124         // -------------------------------------------------------------------------
1125         // checks for debugging
1126
1127         if(debug) debug(D_RRD_STATS, "INFO %s first_t: %lu, last_t: %lu, all_duration: %lu, after: %lu, before: %lu, duration: %lu, points: %ld, group: %ld"
1128                         , st->id
1129                         , first_entry_t
1130                         , last_entry_t
1131                         , last_entry_t - first_entry_t
1132                         , after
1133                         , before
1134                         , duration
1135                         , points
1136                         , group
1137                         );
1138
1139
1140         // -------------------------------------------------------------------------
1141         // temp arrays for keeping values per dimension
1142
1143         calculated_number       group_values[dimensions]; // keep sums when grouping
1144         long                            group_counts[dimensions]; // keep the number of values added to group_values
1145         uint8_t                         group_options[dimensions];
1146         uint8_t                         found_non_zero[dimensions];
1147
1148
1149         // initialize them
1150         RRDDIM *rd;
1151         long c;
1152         for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1153                 group_values[c] = 0;
1154                 group_counts[c] = 0;
1155                 group_options[c] = 0;
1156                 found_non_zero[c] = 0;
1157         }
1158
1159
1160         // -------------------------------------------------------------------------
1161         // the main loop
1162
1163         time_t  now = rrdset_slot2time(st, start_at_slot),
1164                         dt = st->update_every,
1165                         group_start_t = 0;
1166
1167         if(unlikely(debug)) debug(D_RRD_STATS, "BEGIN %s after_t: %lu (stop_at_t: %ld), before_t: %lu (start_at_t: %ld), start_t(now): %lu, current_entry: %ld, entries: %ld"
1168                         , st->id
1169                         , after
1170                         , stop_at_slot
1171                         , before
1172                         , start_at_slot
1173                         , now
1174                         , st->current_entry
1175                         , st->entries
1176                         );
1177
1178         r->group = group;
1179         r->update_every = group * st->update_every;
1180         r->before = now;
1181         r->after = now;
1182
1183         long slot = start_at_slot, counter = 0, stop_now = 0, added = 0, group_count = 0, add_this = 0;
1184         for(; !stop_now ; now -= dt, slot--, counter++) {
1185                 if(unlikely(slot < 0)) slot = st->entries - 1;
1186                 if(unlikely(slot == stop_at_slot)) stop_now = counter;
1187
1188                 if(unlikely(debug)) debug(D_RRD_STATS, "ROW %s slot: %ld, entries_counter: %ld, group_count: %ld, added: %ld, now: %lu, %s %s"
1189                                 , st->id
1190                                 , slot
1191                                 , counter
1192                                 , group_count + 1
1193                                 , added
1194                                 , now
1195                                 , (group_count + 1 == group)?"PRINT":"  -  "
1196                                 , (now >= after && now <= before)?"RANGE":"  -  "
1197                                 );
1198
1199                 // make sure we return data in the proper time range
1200                 if(unlikely(now > before)) continue;
1201                 if(unlikely(now < after)) break;
1202
1203                 if(unlikely(group_count == 0)) {
1204                         group_start_t = now;
1205                 }
1206                 group_count++;
1207
1208                 if(unlikely(group_count == group)) {
1209                         if(unlikely(added >= points)) break;
1210                         add_this = 1;
1211                 }
1212
1213                 // do the calculations
1214                 for(rd = st->dimensions, c = 0 ; likely(rd && c < dimensions) ; rd = rd->next, c++) {
1215                         storage_number n = rd->values[slot];
1216                         if(unlikely(!does_storage_number_exist(n))) continue;
1217
1218                         group_counts[c]++;
1219
1220                         calculated_number value = unpack_storage_number(n);
1221                         if(likely(value != 0.0)) {
1222                                 group_options[c] |= RRDR_NONZERO;
1223                                 found_non_zero[c] = 1;
1224                         }
1225
1226                         if(unlikely(did_storage_number_reset(n)))
1227                                 group_options[c] |= RRDR_RESET;
1228
1229                         switch(group_method) {
1230                                 case GROUP_MAX:
1231                                         if(unlikely(abs(value) > abs(group_values[c])))
1232                                                 group_values[c] = value;
1233                                         break;
1234
1235                                 default:
1236                                 case GROUP_SUM:
1237                                 case GROUP_AVERAGE:
1238                                         group_values[c] += value;
1239                                         break;
1240                         }
1241                 }
1242
1243                 // added it
1244                 if(unlikely(add_this)) {
1245                         if(unlikely(!rrdr_line_init(r, group_start_t))) break;
1246
1247                         r->after = now;
1248
1249                         calculated_number *cn = rrdr_line_values(r);
1250                         uint8_t *co = rrdr_line_options(r);
1251
1252                         for(rd = st->dimensions, c = 0 ; likely(rd && c < dimensions) ; rd = rd->next, c++) {
1253
1254                                 // update the dimension options
1255                                 if(likely(found_non_zero[c])) r->od[c] |= RRDR_NONZERO;
1256                                 if(unlikely(rd->flags & RRDDIM_FLAG_HIDDEN)) r->od[c] |= RRDR_HIDDEN;
1257
1258                                 // store the specific point options
1259                                 co[c] = group_options[c];
1260
1261                                 // store the value
1262                                 if(unlikely(group_counts[c] == 0)) {
1263                                         cn[c] = 0.0;
1264                                         co[c] |= RRDR_EMPTY;
1265                                 }
1266                                 else if(unlikely(group_method == GROUP_AVERAGE)) {
1267                                         cn[c] = group_values[c] / group_counts[c];
1268                                 }
1269                                 else {
1270                                         cn[c] = group_values[c];
1271                                 }
1272
1273                                 if(cn[c] < r->min) r->min = cn[c];
1274                                 if(cn[c] > r->max) r->max = cn[c];
1275
1276                                 // reset them for the next loop
1277                                 group_values[c] = 0;
1278                                 group_counts[c] = 0;
1279                                 group_options[c] = 0;
1280                         }
1281
1282                         added++;
1283                         group_count = 0;
1284                         add_this = 0;
1285                 }
1286         }
1287
1288         rrdr_done(r);
1289         //error("SHIFT: %s: wanted %ld points, got %ld", st->id, points, rrdr_rows(r));
1290         return r;
1291 }
1292
1293 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)
1294 {
1295         RRDR *r = rrd2rrdr(st, points, after, before, group_method);
1296         if(!r) {
1297                 buffer_strcat(wb, "Cannot generate output with these parameters on this chart.");
1298                 return 500;
1299         }
1300
1301         if(dimensions)
1302                 rrdr_disable_not_selected_dimensions(r, buffer_tostring(dimensions));
1303
1304         if(latest_timestamp && rrdr_rows(r) > 0)
1305                 *latest_timestamp = r->before;
1306
1307         switch(format) {
1308         case DATASOURCE_SSV:
1309                 if(options & RRDR_OPTION_JSON_WRAP) {
1310                         wb->contenttype = CT_APPLICATION_JSON;
1311                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1312                         rrdr2ssv(r, wb, options, "", " ", "");
1313                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1314                 }
1315                 else {
1316                         wb->contenttype = CT_TEXT_PLAIN;
1317                         rrdr2ssv(r, wb, options, "", " ", "");
1318                 }
1319                 break;
1320
1321         case DATASOURCE_SSV_COMMA:
1322                 if(options & RRDR_OPTION_JSON_WRAP) {
1323                         wb->contenttype = CT_APPLICATION_JSON;
1324                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1325                         rrdr2ssv(r, wb, options, "", ",", "");
1326                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1327                 }
1328                 else {
1329                         wb->contenttype = CT_TEXT_PLAIN;
1330                         rrdr2ssv(r, wb, options, "", ",", "");
1331                 }
1332                 break;
1333
1334         case DATASOURCE_JS_ARRAY:
1335                 if(options & RRDR_OPTION_JSON_WRAP) {
1336                         wb->contenttype = CT_APPLICATION_JSON;
1337                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1338                         rrdr2ssv(r, wb, options, "[", ",", "]");
1339                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1340                 }
1341                 else {
1342                         wb->contenttype = CT_APPLICATION_JSON;
1343                         rrdr2ssv(r, wb, options, "[", ",", "]");
1344                 }
1345                 break;
1346
1347         case DATASOURCE_CSV:
1348                 if(options & RRDR_OPTION_JSON_WRAP) {
1349                         wb->contenttype = CT_APPLICATION_JSON;
1350                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1351                         rrdr2csv(r, wb, options, "", ",", "\\n");
1352                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1353                 }
1354                 else {
1355                         wb->contenttype = CT_TEXT_PLAIN;
1356                         rrdr2csv(r, wb, options, "", ",", "\r\n");
1357                 }
1358                 break;
1359
1360         case DATASOURCE_TSV:
1361                 if(options & RRDR_OPTION_JSON_WRAP) {
1362                         wb->contenttype = CT_APPLICATION_JSON;
1363                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1364                         rrdr2csv(r, wb, options, "", "\t", "\\n");
1365                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1366                 }
1367                 else {
1368                         wb->contenttype = CT_TEXT_PLAIN;
1369                         rrdr2csv(r, wb, options, "", "\t", "\r\n");
1370                 }
1371                 break;
1372
1373         case DATASOURCE_HTML:
1374                 if(options & RRDR_OPTION_JSON_WRAP) {
1375                         wb->contenttype = CT_APPLICATION_JSON;
1376                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1377                         buffer_strcat(wb, "<html>\\n<center>\\n<table border=\\\"0\\\" cellpadding=\\\"5\\\" cellspacing=\\\"5\\\">\\n");
1378                         rrdr2csv(r, wb, options, "<tr><td>", "</td><td>", "</td></tr>\\n");
1379                         buffer_strcat(wb, "</table>\\n</center>\\n</html>\\n");
1380                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1381                 }
1382                 else {
1383                         wb->contenttype = CT_TEXT_HTML;
1384                         buffer_strcat(wb, "<html>\n<center>\n<table border=\"0\" cellpadding=\"5\" cellspacing=\"5\">\n");
1385                         rrdr2csv(r, wb, options, "<tr><td>", "</td><td>", "</td></tr>\n");
1386                         buffer_strcat(wb, "</table>\n</center>\n</html>\n");
1387                 }
1388                 break;
1389
1390         case DATASOURCE_DATATABLE_JSONP:
1391                 wb->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1392
1393                 if(options & RRDR_OPTION_JSON_WRAP)
1394                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1395
1396                 rrdr2json(r, wb, options, 1);
1397
1398                 if(options & RRDR_OPTION_JSON_WRAP)
1399                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1400                 break;
1401
1402         case DATASOURCE_DATATABLE_JSON:
1403                 wb->contenttype = CT_APPLICATION_JSON;
1404
1405                 if(options & RRDR_OPTION_JSON_WRAP)
1406                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1407
1408                 rrdr2json(r, wb, options, 1);
1409
1410                 if(options & RRDR_OPTION_JSON_WRAP)
1411                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1412                 break;
1413
1414         case DATASOURCE_JSONP:
1415                 wb->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1416                 if(options & RRDR_OPTION_JSON_WRAP)
1417                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1418
1419                 rrdr2json(r, wb, options, 0);
1420
1421                 if(options & RRDR_OPTION_JSON_WRAP)
1422                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1423                 break;
1424
1425         case DATASOURCE_JSON:
1426         default:
1427                 wb->contenttype = CT_APPLICATION_JSON;
1428
1429                 if(options & RRDR_OPTION_JSON_WRAP)
1430                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1431
1432                 rrdr2json(r, wb, options, 0);
1433
1434                 if(options & RRDR_OPTION_JSON_WRAP)
1435                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1436                 break;
1437         }
1438
1439         rrdr_free(r);
1440         return 200;
1441 }
1442
1443 unsigned long rrd_stats_json(int type, RRDSET *st, BUFFER *wb, int points, int group, int group_method, time_t after, time_t before, int only_non_zero)
1444 {
1445         int c;
1446         pthread_rwlock_rdlock(&st->rwlock);
1447
1448
1449         // -------------------------------------------------------------------------
1450         // switch from JSON to google JSON
1451
1452         char kq[2] = "\"";
1453         char sq[2] = "\"";
1454         switch(type) {
1455                 case DATASOURCE_DATATABLE_JSON:
1456                 case DATASOURCE_DATATABLE_JSONP:
1457                         kq[0] = '\0';
1458                         sq[0] = '\'';
1459                         break;
1460
1461                 case DATASOURCE_JSON:
1462                 default:
1463                         break;
1464         }
1465
1466
1467         // -------------------------------------------------------------------------
1468         // validate the parameters
1469
1470         if(points < 1) points = 1;
1471         if(group < 1) group = 1;
1472
1473         if(before == 0 || before > rrdset_last_entry_t(st)) before = rrdset_last_entry_t(st);
1474         if(after  == 0 || after < rrdset_first_entry_t(st)) after = rrdset_first_entry_t(st);
1475
1476         // ---
1477
1478         // our return value (the last timestamp printed)
1479         // this is required to detect re-transmit in google JSONP
1480         time_t last_timestamp = 0;
1481
1482
1483         // -------------------------------------------------------------------------
1484         // find how many dimensions we have
1485
1486         int dimensions = 0;
1487         RRDDIM *rd;
1488         for( rd = st->dimensions ; rd ; rd = rd->next) dimensions++;
1489         if(!dimensions) {
1490                 pthread_rwlock_unlock(&st->rwlock);
1491                 buffer_strcat(wb, "No dimensions yet.");
1492                 return 0;
1493         }
1494
1495
1496         // -------------------------------------------------------------------------
1497         // prepare various strings, to speed up the loop
1498
1499         char overflow_annotation[201]; snprintf(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);
1500         char normal_annotation[201];   snprintf(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
1501         char pre_date[51];             snprintf(pre_date,             50, "             {%sc%s:[{%sv%s:%s", kq, kq, kq, kq, sq);
1502         char post_date[21];            snprintf(post_date,            20, "%s}", sq);
1503         char pre_value[21];            snprintf(pre_value,            20, ",{%sv%s:", kq, kq);
1504         char post_value[21];           snprintf(post_value,           20, "}");
1505
1506
1507         // -------------------------------------------------------------------------
1508         // checks for debugging
1509
1510         if(st->debug) {
1511                 debug(D_RRD_STATS, "%s first_entry_t = %lu, last_entry_t = %lu, duration = %lu, after = %lu, before = %lu, duration = %lu, entries_to_show = %lu, group = %lu"
1512                         , st->id
1513                         , rrdset_first_entry_t(st)
1514                         , rrdset_last_entry_t(st)
1515                         , rrdset_last_entry_t(st) - rrdset_first_entry_t(st)
1516                         , after
1517                         , before
1518                         , before - after
1519                         , points
1520                         , group
1521                         );
1522
1523                 if(before < after)
1524                         debug(D_RRD_STATS, "WARNING: %s The newest value in the database (%lu) is earlier than the oldest (%lu)", st->name, before, after);
1525
1526                 if((before - after) > st->entries * st->update_every)
1527                         debug(D_RRD_STATS, "WARNING: %s The time difference between the oldest and the newest entries (%lu) is higher than the capacity of the database (%lu)", st->name, before - after, st->entries * st->update_every);
1528         }
1529
1530
1531         // -------------------------------------------------------------------------
1532         // temp arrays for keeping values per dimension
1533
1534         calculated_number group_values[dimensions]; // keep sums when grouping
1535         int               print_hidden[dimensions]; // keep hidden flags
1536         int               found_non_zero[dimensions];
1537         int               found_non_existing[dimensions];
1538
1539         // initialize them
1540         for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1541                 group_values[c] = 0;
1542                 print_hidden[c] = (rd->flags & RRDDIM_FLAG_HIDDEN)?1:0;
1543                 found_non_zero[c] = 0;
1544                 found_non_existing[c] = 0;
1545         }
1546
1547
1548         // 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);
1549         // rrd2array(st, entries_to_show, before - (st->update_every * group * entries_to_show), before, group_method, only_non_zero);
1550         // rrd2rrdr(st, entries_to_show, before - (st->update_every * group * entries_to_show), before, group_method);
1551
1552         // -------------------------------------------------------------------------
1553         // remove dimensions that contain only zeros
1554
1555         int max_loop = 1;
1556         if(only_non_zero) max_loop = 2;
1557
1558         for(; max_loop ; max_loop--) {
1559
1560                 // -------------------------------------------------------------------------
1561                 // print the JSON header
1562
1563                 buffer_sprintf(wb, "{\n %scols%s:\n     [\n", kq, kq);
1564                 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);
1565                 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);
1566                 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);
1567
1568                 // print the header for each dimension
1569                 // and update the print_hidden array for the dimensions that should be hidden
1570                 int pc = 0;
1571                 for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1572                         if(!print_hidden[c]) {
1573                                 pc++;
1574                                 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);
1575                         }
1576                 }
1577                 if(!pc) {
1578                         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);
1579                 }
1580
1581                 // print the begin of row data
1582                 buffer_sprintf(wb, "\n  ],\n    %srows%s:\n     [\n", kq, kq);
1583
1584
1585                 // -------------------------------------------------------------------------
1586                 // the main loop
1587
1588                 int annotate_reset = 0;
1589                 int annotation_count = 0;
1590
1591                 long    t = rrdset_time2slot(st, before),
1592                                 stop_at_t = rrdset_time2slot(st, after),
1593                                 stop_now = 0;
1594
1595                 t -= t % group;
1596
1597                 time_t  now = rrdset_slot2time(st, t),
1598                                 dt = st->update_every;
1599
1600                 long count = 0, printed = 0, group_count = 0;
1601                 last_timestamp = 0;
1602
1603                 if(st->debug) debug(D_RRD_STATS, "%s: REQUEST after:%lu before:%lu, points:%d, group:%d, CHART cur:%ld first: %lu last:%lu, CALC start_t:%ld, stop_t:%ld"
1604                                         , st->id
1605                                         , after
1606                                         , before
1607                                         , points
1608                                         , group
1609                                         , st->current_entry
1610                                         , rrdset_first_entry_t(st)
1611                                         , rrdset_last_entry_t(st)
1612                                         , t
1613                                         , stop_at_t
1614                                         );
1615
1616                 long counter = 0;
1617                 for(; !stop_now ; now -= dt, t--, counter++) {
1618                         if(t < 0) t = st->entries - 1;
1619                         if(t == stop_at_t) stop_now = counter;
1620
1621                         int print_this = 0;
1622
1623                         if(st->debug) debug(D_RRD_STATS, "%s t = %ld, count = %ld, group_count = %ld, printed = %ld, now = %lu, %s %s"
1624                                         , st->id
1625                                         , t
1626                                         , count + 1
1627                                         , group_count + 1
1628                                         , printed
1629                                         , now
1630                                         , (group_count + 1 == group)?"PRINT":"  -  "
1631                                         , (now >= after && now <= before)?"RANGE":"  -  "
1632                                         );
1633
1634
1635                         // make sure we return data in the proper time range
1636                         if(now > before) continue;
1637                         if(now < after) break;
1638
1639                         //if(rrdset_slot2time(st, t) != now)
1640                         //      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));
1641
1642                         count++;
1643                         group_count++;
1644
1645                         // check if we have to print this now
1646                         if(group_count == group) {
1647                                 if(printed >= points) {
1648                                         // debug(D_RRD_STATS, "Already printed all rows. Stopping.");
1649                                         break;
1650                                 }
1651
1652                                 // generate the local date time
1653                                 struct tm *tm = localtime(&now);
1654                                 if(!tm) { error("localtime() failed."); continue; }
1655                                 if(now > last_timestamp) last_timestamp = now;
1656
1657                                 if(printed) buffer_strcat(wb, "]},\n");
1658                                 buffer_strcat(wb, pre_date);
1659                                 buffer_jsdate(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
1660                                 buffer_strcat(wb, post_date);
1661
1662                                 print_this = 1;
1663                         }
1664
1665                         // do the calculations
1666                         for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1667                                 storage_number n = rd->values[t];
1668                                 calculated_number value = unpack_storage_number(n);
1669
1670                                 if(!does_storage_number_exist(n)) {
1671                                         value = 0.0;
1672                                         found_non_existing[c]++;
1673                                 }
1674                                 if(did_storage_number_reset(n)) annotate_reset = 1;
1675
1676                                 switch(group_method) {
1677                                         case GROUP_MAX:
1678                                                 if(abs(value) > abs(group_values[c])) group_values[c] = value;
1679                                                 break;
1680
1681                                         case GROUP_SUM:
1682                                                 group_values[c] += value;
1683                                                 break;
1684
1685                                         default:
1686                                         case GROUP_AVERAGE:
1687                                                 group_values[c] += value;
1688                                                 if(print_this) group_values[c] /= ( group_count - found_non_existing[c] );
1689                                                 break;
1690                                 }
1691                         }
1692
1693                         if(print_this) {
1694                                 if(annotate_reset) {
1695                                         annotation_count++;
1696                                         buffer_strcat(wb, overflow_annotation);
1697                                         annotate_reset = 0;
1698                                 }
1699                                 else
1700                                         buffer_strcat(wb, normal_annotation);
1701
1702                                 pc = 0;
1703                                 for(c = 0 ; c < dimensions ; c++) {
1704                                         if(found_non_existing[c] == group_count) {
1705                                                 // all entries are non-existing
1706                                                 pc++;
1707                                                 buffer_strcat(wb, pre_value);
1708                                                 buffer_strcat(wb, "null");
1709                                                 buffer_strcat(wb, post_value);
1710                                         }
1711                                         else if(!print_hidden[c]) {
1712                                                 pc++;
1713                                                 buffer_strcat(wb, pre_value);
1714                                                 buffer_rrd_value(wb, group_values[c]);
1715                                                 buffer_strcat(wb, post_value);
1716
1717                                                 if(group_values[c]) found_non_zero[c]++;
1718                                         }
1719
1720                                         // reset them for the next loop
1721                                         group_values[c] = 0;
1722                                         found_non_existing[c] = 0;
1723                                 }
1724
1725                                 // if all dimensions are hidden, print a null
1726                                 if(!pc) {
1727                                         buffer_strcat(wb, pre_value);
1728                                         buffer_strcat(wb, "null");
1729                                         buffer_strcat(wb, post_value);
1730                                 }
1731
1732                                 printed++;
1733                                 group_count = 0;
1734                         }
1735                 }
1736
1737                 if(printed) buffer_strcat(wb, "]}");
1738                 buffer_strcat(wb, "\n   ]\n}\n");
1739
1740                 if(only_non_zero && max_loop > 1) {
1741                         int changed = 0;
1742                         for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1743                                 group_values[c] = 0;
1744                                 found_non_existing[c] = 0;
1745
1746                                 if(!print_hidden[c] && !found_non_zero[c]) {
1747                                         changed = 1;
1748                                         print_hidden[c] = 1;
1749                                 }
1750                         }
1751
1752                         if(changed) buffer_flush(wb);
1753                         else break;
1754                 }
1755                 else break;
1756
1757         } // max_loop
1758
1759         debug(D_RRD_STATS, "RRD_STATS_JSON: %s total %ld bytes", st->name, wb->len);
1760
1761         pthread_rwlock_unlock(&st->rwlock);
1762         return last_timestamp;
1763 }