]> arthur.barton.de Git - netdata.git/blob - src/rrd2json.c
fixed all crashes; empty responses are now formatted properly; fixed exit procedure...
[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         //info("JSONWRAPPER(): %s: BEGIN", r->st->id);
431         char kq[2] = "",                                        // key quote
432                 sq[2] = "";                                             // string quote
433
434         if( options & RRDR_OPTION_GOOGLE_JSON ) {
435                 kq[0] = '\0';
436                 sq[0] = '\'';
437         }
438         else {
439                 kq[0] = '"';
440                 sq[0] = '"';
441         }
442
443         buffer_sprintf(wb, "{\n"
444                         "       %sid%s: %s%s%s,\n"
445                         "       %sname%s: %s%s%s,\n"
446                         "       %sview_update_every%s: %d,\n"
447                         "       %supdate_every%s: %d,\n"
448                         "       %sfirst_entry_t%s: %u, \n"
449                         "       %slast_entry_t%s: %u, \n"
450                         "       %smin%s: "
451                         , kq, kq, sq, r->st->id, sq
452                         , kq, kq, sq, r->st->name, sq
453                         , kq, kq, r->update_every
454                         , kq, kq, r->st->update_every
455                         , kq, kq, rrdset_first_entry_t(r->st)
456                         , kq, kq, rrdset_last_entry_t(r->st)
457                         , kq, kq);
458
459         buffer_rrd_value(wb, r->min);
460         buffer_sprintf(wb, ",\n %smax%s: ", kq, kq);
461         buffer_rrd_value(wb, r->max);
462         buffer_sprintf(wb, ",\n"
463                         "       %sbefore%s: %u,\n"
464                         "       %safter%s: %u,\n"
465                         "       %sdimension_names%s: ["
466                         , kq, kq, r->before
467                         , kq, kq, r->after
468                         , kq, kq);
469
470
471         long c, i;
472         RRDDIM *rd;
473         for(c = 0, i = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
474                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
475                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
476
477                 if(i) buffer_strcat(wb, ", ");
478                 buffer_strcat(wb, sq);
479                 buffer_strcat(wb, rd->name);
480                 buffer_strcat(wb, sq);
481                 i++;
482         }
483         buffer_sprintf(wb, "],\n"
484                         "       %sdimension_ids%s: ["
485                         , kq, kq);
486
487         for(c = 0, i = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
488                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
489                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
490
491                 if(i) buffer_strcat(wb, ", ");
492                 buffer_strcat(wb, sq);
493                 buffer_strcat(wb, rd->id);
494                 buffer_strcat(wb, sq);
495                 i++;
496         }
497         buffer_sprintf(wb, "],\n"
498                         "       %sdimensions%s: %d,\n"
499                         "       %spoints%s: %d,\n"
500                         "       %sformat%s: %s"
501                         , kq, kq, i
502                         , kq, kq, rrdr_rows(r)
503                         , kq, kq, sq
504                         );
505
506         rrdr_buffer_print_format(wb, format);
507
508         buffer_sprintf(wb, "%s,\n"
509                         "       %sresult%s: "
510                         , sq
511                         , kq, kq
512                         );
513
514         if(string_value) buffer_strcat(wb, sq);
515         //info("JSONWRAPPER(): %s: END", r->st->id);
516 }
517
518 void rrdr_json_wrapper_end(RRDR *r, BUFFER *wb, uint32_t format, uint32_t options, int string_value)
519 {
520         if(r) {;}
521         if(format) {;}
522
523         char sq[2] = "";                                                // string quote
524
525         if( options & RRDR_OPTION_GOOGLE_JSON )
526                 sq[0] = '\'';
527         else
528                 sq[0] = '"';
529
530         if(string_value) buffer_strcat(wb, sq);
531         buffer_strcat(wb, "\n}\n");
532 }
533
534 #define JSON_DATES_JS 1
535 #define JSON_DATES_TIMESTAMP 2
536
537 static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
538 {
539         //info("RRD2JSON(): %s: BEGIN", r->st->id);
540         int row_annotations = 0, dates = JSON_DATES_JS, dates_with_new = 0;
541         char kq[2] = "",                                        // key quote
542                 sq[2] = "",                                             // string quote
543                 pre_label[101] = "",                    // before each label
544                 post_label[101] = "",                   // after each label
545                 pre_date[101] = "",                             // the beginning of line, to the date
546                 post_date[101] = "",                    // closing the date
547                 pre_value[101] = "",                    // before each value
548                 post_value[101] = "",                   // after each value
549                 post_line[101] = "",                    // at the end of each row
550                 normal_annotation[201] = "",    // default row annotation
551                 overflow_annotation[201] = "",  // overflow row annotation
552                 data_begin[101] = "",                   // between labels and values
553                 finish[101] = "";                               // at the end of everything
554
555         if(datatable) {
556                 dates = JSON_DATES_JS;
557                 if( options & RRDR_OPTION_GOOGLE_JSON ) {
558                         kq[0] = '\0';
559                         sq[0] = '\'';
560                 }
561                 else {
562                         kq[0] = '"';
563                         sq[0] = '"';
564                 }
565                 row_annotations = 1;
566                 snprintf(pre_date,   100, "             {%sc%s:[{%sv%s:%s", kq, kq, kq, kq, sq);
567                 snprintf(post_date,  100, "%s}", sq);
568                 snprintf(pre_label,  100, ",\n          {%sid%s:%s%s,%slabel%s:%s", kq, kq, sq, sq, kq, kq, sq);
569                 snprintf(post_label, 100, "%s,%spattern%s:%s%s,%stype%s:%snumber%s}", sq, kq, kq, sq, sq, kq, kq, sq, sq);
570                 snprintf(pre_value,  100, ",{%sv%s:", kq, kq);
571                 snprintf(post_value, 100, "}");
572                 snprintf(post_line,  100, "]}");
573                 snprintf(data_begin, 100, "\n   ],\n    %srows%s:\n     [\n", kq, kq);
574                 snprintf(finish,     100, "\n   ]\n}\n");
575
576                 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);
577                 snprintf(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
578
579                 buffer_sprintf(wb, "{\n %scols%s:\n     [\n", kq, kq, kq, kq);
580                 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);
581                 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);
582                 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);
583
584                 // remove the valueobjects flag
585                 // google wants its own keys
586                 if(options & RRDR_OPTION_OBJECTSROWS)
587                         options &= ~RRDR_OPTION_OBJECTSROWS;
588         }
589         else {
590                 kq[0] = '"';
591                 sq[0] = '"';
592                 if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
593                         dates = JSON_DATES_TIMESTAMP;
594                         dates_with_new = 0;
595                 }
596                 else {
597                         dates = JSON_DATES_JS;
598                         dates_with_new = 1;
599                 }
600                 if( options & RRDR_OPTION_OBJECTSROWS )
601                         snprintf(pre_date,   100, "             { ");
602                 else
603                         snprintf(pre_date,   100, "             [ ");
604                 snprintf(pre_label,  100, ", \"");
605                 snprintf(post_label, 100, "\"");
606                 snprintf(pre_value,  100, ", ");
607                 if( options & RRDR_OPTION_OBJECTSROWS )
608                         snprintf(post_line,  100, "}");
609                 else
610                         snprintf(post_line,  100, "]");
611                 snprintf(data_begin, 100, "],\n %sdata%s:\n     [\n", kq, kq);
612                 snprintf(finish,     100, "\n   ]\n}\n");
613
614                 buffer_sprintf(wb, "{\n %slabels%s: [", kq, kq);
615                 buffer_sprintf(wb, "%stime%s", sq, sq);
616         }
617
618         // -------------------------------------------------------------------------
619         // print the JSON header
620
621         long c, i;
622         RRDDIM *rd;
623
624         // print the header lines
625         for(c = 0, i = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
626                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
627                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
628
629                 buffer_strcat(wb, pre_label);
630                 buffer_strcat(wb, rd->name);
631                 buffer_strcat(wb, post_label);
632                 i++;
633         }
634         if(!i) {
635                 buffer_strcat(wb, pre_label);
636                 buffer_strcat(wb, "no data");
637                 buffer_strcat(wb, post_label);
638         }
639
640         // print the begin of row data
641         buffer_strcat(wb, data_begin);
642
643         // if all dimensions are hidden, print a null
644         if(!i) {
645                 buffer_strcat(wb, finish);
646                 return;
647         }
648
649         long start = 0, end = rrdr_rows(r), step = 1;
650         if((options & RRDR_OPTION_REVERSED)) {
651                 start = rrdr_rows(r) - 1;
652                 end = -1;
653                 step = -1;
654         }
655
656         // for each line in the array
657         for(i = start; i != end ;i += step) {
658                 calculated_number *cn = &r->v[ i * r->d ];
659                 uint8_t *co = &r->o[ i * r->d ];
660
661                 time_t now = r->t[i];
662
663                 if(dates == JSON_DATES_JS) {
664                         // generate the local date time
665                         struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
666                         if(!tm) { error("localtime_r() failed."); continue; }
667
668                         if(likely(i != start)) buffer_strcat(wb, ",\n");
669                         buffer_strcat(wb, pre_date);
670
671                         if( options & RRDR_OPTION_OBJECTSROWS )
672                                 buffer_sprintf(wb, "%stime%s: ", kq, kq);
673
674                         if(dates_with_new)
675                                 buffer_strcat(wb, "new ");
676
677                         buffer_jsdate(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
678
679                         buffer_strcat(wb, post_date);
680
681                         if(row_annotations) {
682                                 // google supports one annotation per row
683                                 int annotation_found = 0;
684                                 for(c = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
685                                         if(co[c] & RRDR_RESET) {
686                                                 buffer_strcat(wb, overflow_annotation);
687                                                 annotation_found = 1;
688                                                 break;
689                                         }
690                                 }
691                                 if(!annotation_found)
692                                         buffer_strcat(wb, normal_annotation);
693                         }
694                 }
695                 else {
696                         // print the timestamp of the line
697                         if(likely(i != start)) buffer_strcat(wb, ",\n");
698                         buffer_strcat(wb, pre_date);
699
700                         if( options & RRDR_OPTION_OBJECTSROWS )
701                                 buffer_sprintf(wb, "%stime%s: ", kq, kq);
702
703                         buffer_rrd_value(wb, (calculated_number)r->t[i]);
704                         // in ms
705                         if(options & RRDR_OPTION_MILLISECONDS) buffer_strcat(wb, "000");
706
707                         buffer_strcat(wb, post_date);
708                 }
709
710                 // for each dimension
711                 for(c = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
712                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
713                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
714
715                         calculated_number n = cn[c];
716
717                         buffer_strcat(wb, pre_value);
718
719                         if( options & RRDR_OPTION_OBJECTSROWS )
720                                 buffer_sprintf(wb, "%s%s%s: ", kq, rd->name, kq);
721
722                         if(co[c] & RRDR_EMPTY) {
723                                 if(options & RRDR_OPTION_NULL2ZERO)
724                                         buffer_strcat(wb, "0");
725                                 else
726                                         buffer_strcat(wb, "null");
727                         }
728                         else if((options & RRDR_OPTION_ABSOLUTE))
729                                 buffer_rrd_value(wb, (n<0)?-n:n);
730                         else
731                                 buffer_rrd_value(wb, n);
732
733                         buffer_strcat(wb, post_value);
734                 }
735
736                 buffer_strcat(wb, post_line);
737         }
738
739         buffer_strcat(wb, finish);
740         //info("RRD2JSON(): %s: END", r->st->id);
741 }
742
743 static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startline, const char *separator, const char *endline)
744 {
745         //info("RRD2CSV(): %s: BEGIN", r->st->id);
746         long c, i;
747         RRDDIM *d;
748
749         // print the csv header
750         for(c = 0, i = 0, d = r->st->dimensions; d ;c++, d = d->next) {
751                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
752                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
753
754                 if(!i) {
755                         buffer_strcat(wb, startline);
756                         buffer_strcat(wb, "time");
757                 }
758                 buffer_strcat(wb, separator);
759                 buffer_strcat(wb, d->name);
760                 i++;
761         }
762         buffer_strcat(wb, endline);
763
764         if(!i) {
765                 // no dimensions present
766                 return;
767         }
768
769         long start = 0, end = rrdr_rows(r), step = 1;
770         if((options & RRDR_OPTION_REVERSED)) {
771                 start = rrdr_rows(r) - 1;
772                 end = -1;
773                 step = -1;
774         }
775
776         // for each line in the array
777         for(i = start; i != end ;i += step) {
778                 calculated_number *cn = &r->v[ i * r->d ];
779                 uint8_t *co = &r->o[ i * r->d ];
780
781                 buffer_strcat(wb, startline);
782
783                 time_t now = r->t[i];
784
785                 if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
786                         // print the timestamp of the line
787                         buffer_rrd_value(wb, (calculated_number)now);
788                         // in ms
789                         if(options & RRDR_OPTION_MILLISECONDS) buffer_strcat(wb, "000");
790                 }
791                 else {
792                         // generate the local date time
793                         struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
794                         if(!tm) { error("localtime() failed."); continue; }
795                         buffer_date(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
796                 }
797
798                 // for each dimension
799                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
800                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
801                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
802
803                         buffer_strcat(wb, separator);
804
805                         calculated_number n = cn[c];
806
807                         if(co[c] & RRDR_EMPTY) {
808                                 if(options & RRDR_OPTION_NULL2ZERO)
809                                         buffer_strcat(wb, "0");
810                                 else
811                                         buffer_strcat(wb, "null");
812                         }
813                         else if((options & RRDR_OPTION_ABSOLUTE))
814                                 buffer_rrd_value(wb, (n<0)?-n:n);
815                         else
816                                 buffer_rrd_value(wb, n);
817                 }
818
819                 buffer_strcat(wb, endline);
820         }
821         //info("RRD2CSV(): %s: END", r->st->id);
822 }
823
824 static void rrdr2ssv(RRDR *r, BUFFER *wb, uint32_t options, const char *prefix, const char *separator, const char *suffix)
825 {
826         //info("RRD2SSV(): %s: BEGIN", r->st->id);
827         long c, i;
828         RRDDIM *d;
829
830         buffer_strcat(wb, prefix);
831         long start = 0, end = rrdr_rows(r), step = 1;
832         if((options & RRDR_OPTION_REVERSED)) {
833                 start = rrdr_rows(r) - 1;
834                 end = -1;
835                 step = -1;
836         }
837
838         // for each line in the array
839         for(i = start; i != end ;i += step) {
840
841                 calculated_number *cn = &r->v[ i * r->d ];
842                 uint8_t *co = &r->o[ i * r->d ];
843
844                 calculated_number sum = 0, min = 0, max = 0;
845                 int all_null = 1, init = 1;
846
847                 // for each dimension
848                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
849                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
850                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
851
852                         calculated_number n = cn[c];
853
854                         if(unlikely(init)) {
855                                 if(n > 0) {
856                                         min = 0;
857                                         max = n;
858                                 }
859                                 else {
860                                         min = n;
861                                         max = 0;
862                                 }
863                                 init = 0;
864                         }
865
866                         if(likely(!(co[c] & RRDR_EMPTY))) {
867                                 all_null = 0;
868                                 if((options & RRDR_OPTION_ABSOLUTE) && n < 0) n = -n;
869                                 sum += n;
870                         }
871
872                         if(n < min) min = n;
873                         if(n > max) max = n;
874                 }
875
876                 if(likely(i != start))
877                         buffer_strcat(wb, separator);
878
879                 if(all_null) {
880                         if(options & RRDR_OPTION_NULL2ZERO)
881                                 buffer_strcat(wb, "0");
882                         else
883                                 buffer_strcat(wb, "null");
884                 }
885                 else if(options & RRDR_OPTION_MIN2MAX)
886                         buffer_rrd_value(wb, max - min);
887                 else
888                         buffer_rrd_value(wb, sum);
889         }
890         buffer_strcat(wb, suffix);
891         //info("RRD2SSV(): %s: END", r->st->id);
892 }
893
894 inline static calculated_number *rrdr_line_values(RRDR *r)
895 {
896         return &r->v[ r->c * r->d ];
897 }
898
899 inline static uint8_t *rrdr_line_options(RRDR *r)
900 {
901         return &r->o[ r->c * r->d ];
902 }
903
904 inline static int rrdr_line_init(RRDR *r, time_t t)
905 {
906         r->c++;
907
908         if(unlikely(r->c >= r->n)) {
909                 error("requested to step above RRDR size for chart %s", r->st->name);
910                 r->c = r->n - 1;
911         }
912
913         // save the time
914         r->t[r->c] = t;
915
916         return 1;
917 }
918
919 inline static void rrdr_lock_rrdset(RRDR *r) {
920         if(unlikely(!r)) {
921                 error("NULL value given!");
922                 return;
923         }
924
925         pthread_rwlock_rdlock(&r->st->rwlock);
926         r->has_st_lock = 1;
927 }
928
929 inline static void rrdr_unlock_rrdset(RRDR *r) {
930         if(unlikely(!r)) {
931                 error("NULL value given!");
932                 return;
933         }
934
935         if(likely(r->has_st_lock)) {
936                 pthread_rwlock_unlock(&r->st->rwlock);
937                 r->has_st_lock = 0;
938         }
939 }
940
941 inline static void rrdr_free(RRDR *r)
942 {
943         if(unlikely(!r)) {
944                 error("NULL value given!");
945                 return;
946         }
947
948         rrdr_unlock_rrdset(r);
949         if(likely(r->t)) free(r->t);
950         if(likely(r->v)) free(r->v);
951         if(likely(r->o)) free(r->o);
952         if(likely(r->od)) free(r->od);
953         free(r);
954 }
955
956 inline void rrdr_done(RRDR *r)
957 {
958         r->rows = r->c + 1;
959         r->c = 0;
960 }
961
962 static RRDR *rrdr_create(RRDSET *st, int n)
963 {
964         if(unlikely(!st)) {
965                 error("NULL value given!");
966                 return NULL;
967         }
968
969         RRDR *r = calloc(1, sizeof(RRDR));
970         if(unlikely(!r)) goto cleanup;
971
972         r->st = st;
973
974         rrdr_lock_rrdset(r);
975
976         RRDDIM *rd;
977         for(rd = st->dimensions ; rd ; rd = rd->next) r->d++;
978
979         r->n = n;
980
981         r->t = malloc(n * sizeof(time_t));
982         if(unlikely(!r->t)) goto cleanup;
983
984         r->v = malloc(n * r->d * sizeof(calculated_number));
985         if(unlikely(!r->v)) goto cleanup;
986
987         r->o = malloc(n * r->d * sizeof(uint8_t));
988         if(unlikely(!r->o)) goto cleanup;
989
990         r->od = malloc(r->d * sizeof(uint8_t));
991         if(unlikely(!r->od)) goto cleanup;
992
993         r->c = -1;
994
995         r->group = 1;
996         r->update_every = 1;
997
998         return r;
999
1000 cleanup:
1001         error("Cannot allocate RRDR memory for %d entries", n);
1002         if(likely(r)) rrdr_free(r);
1003         return NULL;
1004 }
1005
1006 RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int group_method)
1007 {
1008         int debug = st->debug;
1009
1010         time_t first_entry_t = rrdset_first_entry_t(st);
1011         time_t last_entry_t = rrdset_last_entry_t(st);
1012
1013         if(before == 0 && after == 0) {
1014                 before = last_entry_t;
1015                 after = first_entry_t;
1016         }
1017
1018         // allow relative for before and after
1019         if(before <= st->update_every * st->entries)
1020                 before = last_entry_t + before;
1021
1022         if(after <= st->update_every * st->entries)
1023                 after = last_entry_t + after;
1024
1025         // make sure they are within our timeframe
1026         if(before > last_entry_t) before = last_entry_t;
1027         if(before < first_entry_t) before = first_entry_t;
1028
1029         if(after > last_entry_t) after = last_entry_t;
1030         if(after < first_entry_t) after = first_entry_t;
1031
1032         // check if they are upside down
1033         if(after > before) {
1034                 time_t tmp = before;
1035                 before = after;
1036                 after = tmp;
1037         }
1038
1039         // the duration of the chart
1040         time_t duration = before - after;
1041         long available_points = duration / st->update_every;
1042
1043         if(duration <= 0 || available_points <= 0)
1044                 return rrdr_create(st, 1);
1045
1046         // check the wanted points
1047         if(points < 0) points = -points;
1048         if(points > available_points) points = available_points;
1049         if(points == 0) points = available_points;
1050
1051         // calculate proper grouping of source data
1052         long group = available_points / points;
1053         if(group <= 0) group = 1;
1054
1055         // round group to the closest integer
1056         if(available_points % points > points / 2) group++;
1057
1058         time_t after_new = after - (after % (group * st->update_every));
1059         time_t before_new = before - (before % (group * st->update_every));
1060         long points_new = (before_new - after_new) / st->update_every / group;
1061
1062         // find the starting and ending slots in our round robin db
1063         long    start_at_slot = rrdset_time2slot(st, before_new),
1064                         stop_at_slot = rrdset_time2slot(st, after_new);
1065
1066 #ifdef NETDATA_INTERNAL_CHECKS
1067         if(after_new < first_entry_t) {
1068                 error("after_new %u is too small, minimum %u", after_new, first_entry_t);
1069         }
1070         if(after_new > last_entry_t) {
1071                 error("after_new %u is too big, maximum %u", after_new, last_entry_t);
1072         }
1073         if(before_new < first_entry_t) {
1074                 error("before_new %u is too small, minimum %u", before_new, first_entry_t);
1075         }
1076         if(before_new > last_entry_t) {
1077                 error("before_new %u is too big, maximum %u", before_new, last_entry_t);
1078         }
1079         if(start_at_slot < 0 || start_at_slot >= st->entries) {
1080                 error("start_at_slot is invalid %ld, expected %ld to %ld", start_at_slot, 0, st->entries - 1);
1081         }
1082         if(stop_at_slot < 0 || stop_at_slot >= st->entries) {
1083                 error("stop_at_slot is invalid %ld, expected %ld to %ld", stop_at_slot, 0, st->entries - 1);
1084         }
1085         if(points_new > (before_new - after_new) / group / st->update_every + 1) {
1086                 error("points_new %ld is more than points %ld", points_new, (before_new - after_new) / group / st->update_every + 1);
1087         }
1088 #endif
1089
1090         //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);
1091
1092         after = after_new;
1093         before = before_new;
1094         duration = before - after;
1095         points = points_new;
1096
1097         // Now we have:
1098         // before = the end time of the calculation
1099         // after = the start time of the calculation
1100         // duration = the duration of the calculation
1101         // group = the number of source points to aggregate / group together
1102         // method = the method of grouping source points
1103         // points = the number of points to generate
1104
1105
1106         // -------------------------------------------------------------------------
1107         // initialize our result set
1108
1109         RRDR *r = rrdr_create(st, points);
1110         if(!r) return NULL;
1111         if(!r->d) return r;
1112
1113         // find how many dimensions we have
1114         long dimensions = r->d;
1115
1116
1117         // -------------------------------------------------------------------------
1118         // checks for debugging
1119
1120         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"
1121                         , st->id
1122                         , first_entry_t
1123                         , last_entry_t
1124                         , last_entry_t - first_entry_t
1125                         , after
1126                         , before
1127                         , duration
1128                         , points
1129                         , group
1130                         );
1131
1132
1133         // -------------------------------------------------------------------------
1134         // temp arrays for keeping values per dimension
1135
1136         calculated_number       group_values[dimensions]; // keep sums when grouping
1137         long                            group_counts[dimensions]; // keep the number of values added to group_values
1138         uint8_t                         group_options[dimensions];
1139         uint8_t                         found_non_zero[dimensions];
1140
1141
1142         // initialize them
1143         RRDDIM *rd;
1144         long c;
1145         for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1146                 group_values[c] = 0;
1147                 group_counts[c] = 0;
1148                 group_options[c] = 0;
1149                 found_non_zero[c] = 0;
1150         }
1151
1152
1153         // -------------------------------------------------------------------------
1154         // the main loop
1155
1156         time_t  now = rrdset_slot2time(st, start_at_slot),
1157                         dt = st->update_every,
1158                         group_start_t = 0;
1159
1160         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"
1161                         , st->id
1162                         , after
1163                         , stop_at_slot
1164                         , before
1165                         , start_at_slot
1166                         , now
1167                         , st->current_entry
1168                         , st->entries
1169                         );
1170
1171         r->group = group;
1172         r->update_every = group * st->update_every;
1173         r->before = now;
1174         r->after = now;
1175
1176         //info("RRD2RRDR(): %s: STARTING", st->id);
1177
1178         long slot = start_at_slot, counter = 0, stop_now = 0, added = 0, group_count = 0, add_this = 0;
1179         for(; !stop_now ; now -= dt, slot--, counter++) {
1180                 if(unlikely(slot < 0)) slot = st->entries - 1;
1181                 if(unlikely(slot == stop_at_slot)) stop_now = counter;
1182
1183                 if(unlikely(debug)) debug(D_RRD_STATS, "ROW %s slot: %ld, entries_counter: %ld, group_count: %ld, added: %ld, now: %lu, %s %s"
1184                                 , st->id
1185                                 , slot
1186                                 , counter
1187                                 , group_count + 1
1188                                 , added
1189                                 , now
1190                                 , (group_count + 1 == group)?"PRINT":"  -  "
1191                                 , (now >= after && now <= before)?"RANGE":"  -  "
1192                                 );
1193
1194                 // make sure we return data in the proper time range
1195                 if(unlikely(now > before)) continue;
1196                 if(unlikely(now < after)) break;
1197
1198                 if(unlikely(group_count == 0)) {
1199                         group_start_t = now;
1200                 }
1201                 group_count++;
1202
1203                 if(unlikely(group_count == group)) {
1204                         if(unlikely(added >= points)) break;
1205                         add_this = 1;
1206                 }
1207
1208                 // do the calculations
1209                 for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1210                         storage_number n = rd->values[slot];
1211                         if(unlikely(!does_storage_number_exist(n))) continue;
1212
1213                         group_counts[c]++;
1214
1215                         calculated_number value = unpack_storage_number(n);
1216                         if(likely(value != 0.0)) {
1217                                 group_options[c] |= RRDR_NONZERO;
1218                                 found_non_zero[c] = 1;
1219                         }
1220
1221                         if(unlikely(did_storage_number_reset(n)))
1222                                 group_options[c] |= RRDR_RESET;
1223
1224                         switch(group_method) {
1225                                 case GROUP_MAX:
1226                                         if(unlikely(abs(value) > abs(group_values[c])))
1227                                                 group_values[c] = value;
1228                                         break;
1229
1230                                 default:
1231                                 case GROUP_SUM:
1232                                 case GROUP_AVERAGE:
1233                                         group_values[c] += value;
1234                                         break;
1235                         }
1236                 }
1237
1238                 // added it
1239                 if(unlikely(add_this)) {
1240                         if(unlikely(!rrdr_line_init(r, group_start_t))) break;
1241
1242                         r->after = now;
1243
1244                         calculated_number *cn = rrdr_line_values(r);
1245                         uint8_t *co = rrdr_line_options(r);
1246
1247                         for(rd = st->dimensions, c = 0 ; likely(rd && c < dimensions) ; rd = rd->next, c++) {
1248
1249                                 // update the dimension options
1250                                 if(likely(found_non_zero[c])) r->od[c] |= RRDR_NONZERO;
1251                                 if(unlikely(rd->flags & RRDDIM_FLAG_HIDDEN)) r->od[c] |= RRDR_HIDDEN;
1252
1253                                 // store the specific point options
1254                                 co[c] = group_options[c];
1255
1256                                 // store the value
1257                                 if(unlikely(group_counts[c] == 0)) {
1258                                         cn[c] = 0.0;
1259                                         co[c] |= RRDR_EMPTY;
1260                                 }
1261                                 else if(unlikely(group_method == GROUP_AVERAGE)) {
1262                                         cn[c] = group_values[c] / group_counts[c];
1263                                 }
1264                                 else {
1265                                         cn[c] = group_values[c];
1266                                 }
1267
1268                                 if(cn[c] < r->min) r->min = cn[c];
1269                                 if(cn[c] > r->max) r->max = cn[c];
1270
1271                                 // reset them for the next loop
1272                                 group_values[c] = 0;
1273                                 group_counts[c] = 0;
1274                                 group_options[c] = 0;
1275                         }
1276
1277                         added++;
1278                         group_count = 0;
1279                         add_this = 0;
1280                 }
1281         }
1282
1283         rrdr_done(r);
1284         //info("RRD2RRDR(): %s: END %ld loops made, %ld points generated", st->id, counter, rrdr_rows(r));
1285         //error("SHIFT: %s: wanted %ld points, got %ld", st->id, points, rrdr_rows(r));
1286         return r;
1287 }
1288
1289 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)
1290 {
1291         RRDR *r = rrd2rrdr(st, points, after, before, group_method);
1292         if(!r) {
1293                 buffer_strcat(wb, "Cannot generate output with these parameters on this chart.");
1294                 return 500;
1295         }
1296
1297         if(dimensions)
1298                 rrdr_disable_not_selected_dimensions(r, buffer_tostring(dimensions));
1299
1300         if(latest_timestamp && rrdr_rows(r) > 0)
1301                 *latest_timestamp = r->before;
1302
1303         switch(format) {
1304         case DATASOURCE_SSV:
1305                 if(options & RRDR_OPTION_JSON_WRAP) {
1306                         wb->contenttype = CT_APPLICATION_JSON;
1307                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1308                         rrdr2ssv(r, wb, options, "", " ", "");
1309                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1310                 }
1311                 else {
1312                         wb->contenttype = CT_TEXT_PLAIN;
1313                         rrdr2ssv(r, wb, options, "", " ", "");
1314                 }
1315                 break;
1316
1317         case DATASOURCE_SSV_COMMA:
1318                 if(options & RRDR_OPTION_JSON_WRAP) {
1319                         wb->contenttype = CT_APPLICATION_JSON;
1320                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1321                         rrdr2ssv(r, wb, options, "", ",", "");
1322                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1323                 }
1324                 else {
1325                         wb->contenttype = CT_TEXT_PLAIN;
1326                         rrdr2ssv(r, wb, options, "", ",", "");
1327                 }
1328                 break;
1329
1330         case DATASOURCE_JS_ARRAY:
1331                 if(options & RRDR_OPTION_JSON_WRAP) {
1332                         wb->contenttype = CT_APPLICATION_JSON;
1333                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1334                         rrdr2ssv(r, wb, options, "[", ",", "]");
1335                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1336                 }
1337                 else {
1338                         wb->contenttype = CT_APPLICATION_JSON;
1339                         rrdr2ssv(r, wb, options, "[", ",", "]");
1340                 }
1341                 break;
1342
1343         case DATASOURCE_CSV:
1344                 if(options & RRDR_OPTION_JSON_WRAP) {
1345                         wb->contenttype = CT_APPLICATION_JSON;
1346                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1347                         rrdr2csv(r, wb, options, "", ",", "\\n");
1348                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1349                 }
1350                 else {
1351                         wb->contenttype = CT_TEXT_PLAIN;
1352                         rrdr2csv(r, wb, options, "", ",", "\r\n");
1353                 }
1354                 break;
1355
1356         case DATASOURCE_TSV:
1357                 if(options & RRDR_OPTION_JSON_WRAP) {
1358                         wb->contenttype = CT_APPLICATION_JSON;
1359                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1360                         rrdr2csv(r, wb, options, "", "\t", "\\n");
1361                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1362                 }
1363                 else {
1364                         wb->contenttype = CT_TEXT_PLAIN;
1365                         rrdr2csv(r, wb, options, "", "\t", "\r\n");
1366                 }
1367                 break;
1368
1369         case DATASOURCE_HTML:
1370                 if(options & RRDR_OPTION_JSON_WRAP) {
1371                         wb->contenttype = CT_APPLICATION_JSON;
1372                         rrdr_json_wrapper_begin(r, wb, format, options, 1);
1373                         buffer_strcat(wb, "<html>\\n<center>\\n<table border=\\\"0\\\" cellpadding=\\\"5\\\" cellspacing=\\\"5\\\">\\n");
1374                         rrdr2csv(r, wb, options, "<tr><td>", "</td><td>", "</td></tr>\\n");
1375                         buffer_strcat(wb, "</table>\\n</center>\\n</html>\\n");
1376                         rrdr_json_wrapper_end(r, wb, format, options, 1);
1377                 }
1378                 else {
1379                         wb->contenttype = CT_TEXT_HTML;
1380                         buffer_strcat(wb, "<html>\n<center>\n<table border=\"0\" cellpadding=\"5\" cellspacing=\"5\">\n");
1381                         rrdr2csv(r, wb, options, "<tr><td>", "</td><td>", "</td></tr>\n");
1382                         buffer_strcat(wb, "</table>\n</center>\n</html>\n");
1383                 }
1384                 break;
1385
1386         case DATASOURCE_DATATABLE_JSONP:
1387                 wb->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1388
1389                 if(options & RRDR_OPTION_JSON_WRAP)
1390                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1391
1392                 rrdr2json(r, wb, options, 1);
1393
1394                 if(options & RRDR_OPTION_JSON_WRAP)
1395                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1396                 break;
1397
1398         case DATASOURCE_DATATABLE_JSON:
1399                 wb->contenttype = CT_APPLICATION_JSON;
1400
1401                 if(options & RRDR_OPTION_JSON_WRAP)
1402                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1403
1404                 rrdr2json(r, wb, options, 1);
1405
1406                 if(options & RRDR_OPTION_JSON_WRAP)
1407                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1408                 break;
1409
1410         case DATASOURCE_JSONP:
1411                 wb->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1412                 if(options & RRDR_OPTION_JSON_WRAP)
1413                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1414
1415                 rrdr2json(r, wb, options, 0);
1416
1417                 if(options & RRDR_OPTION_JSON_WRAP)
1418                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1419                 break;
1420
1421         case DATASOURCE_JSON:
1422         default:
1423                 wb->contenttype = CT_APPLICATION_JSON;
1424
1425                 if(options & RRDR_OPTION_JSON_WRAP)
1426                         rrdr_json_wrapper_begin(r, wb, format, options, 0);
1427
1428                 rrdr2json(r, wb, options, 0);
1429
1430                 if(options & RRDR_OPTION_JSON_WRAP)
1431                         rrdr_json_wrapper_end(r, wb, format, options, 0);
1432                 break;
1433         }
1434
1435         rrdr_free(r);
1436         return 200;
1437 }
1438
1439 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)
1440 {
1441         int c;
1442         pthread_rwlock_rdlock(&st->rwlock);
1443
1444
1445         // -------------------------------------------------------------------------
1446         // switch from JSON to google JSON
1447
1448         char kq[2] = "\"";
1449         char sq[2] = "\"";
1450         switch(type) {
1451                 case DATASOURCE_DATATABLE_JSON:
1452                 case DATASOURCE_DATATABLE_JSONP:
1453                         kq[0] = '\0';
1454                         sq[0] = '\'';
1455                         break;
1456
1457                 case DATASOURCE_JSON:
1458                 default:
1459                         break;
1460         }
1461
1462
1463         // -------------------------------------------------------------------------
1464         // validate the parameters
1465
1466         if(points < 1) points = 1;
1467         if(group < 1) group = 1;
1468
1469         if(before == 0 || before > rrdset_last_entry_t(st)) before = rrdset_last_entry_t(st);
1470         if(after  == 0 || after < rrdset_first_entry_t(st)) after = rrdset_first_entry_t(st);
1471
1472         // ---
1473
1474         // our return value (the last timestamp printed)
1475         // this is required to detect re-transmit in google JSONP
1476         time_t last_timestamp = 0;
1477
1478
1479         // -------------------------------------------------------------------------
1480         // find how many dimensions we have
1481
1482         int dimensions = 0;
1483         RRDDIM *rd;
1484         for( rd = st->dimensions ; rd ; rd = rd->next) dimensions++;
1485         if(!dimensions) {
1486                 pthread_rwlock_unlock(&st->rwlock);
1487                 buffer_strcat(wb, "No dimensions yet.");
1488                 return 0;
1489         }
1490
1491
1492         // -------------------------------------------------------------------------
1493         // prepare various strings, to speed up the loop
1494
1495         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);
1496         char normal_annotation[201];   snprintf(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
1497         char pre_date[51];             snprintf(pre_date,             50, "             {%sc%s:[{%sv%s:%s", kq, kq, kq, kq, sq);
1498         char post_date[21];            snprintf(post_date,            20, "%s}", sq);
1499         char pre_value[21];            snprintf(pre_value,            20, ",{%sv%s:", kq, kq);
1500         char post_value[21];           snprintf(post_value,           20, "}");
1501
1502
1503         // -------------------------------------------------------------------------
1504         // checks for debugging
1505
1506         if(st->debug) {
1507                 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"
1508                         , st->id
1509                         , rrdset_first_entry_t(st)
1510                         , rrdset_last_entry_t(st)
1511                         , rrdset_last_entry_t(st) - rrdset_first_entry_t(st)
1512                         , after
1513                         , before
1514                         , before - after
1515                         , points
1516                         , group
1517                         );
1518
1519                 if(before < after)
1520                         debug(D_RRD_STATS, "WARNING: %s The newest value in the database (%lu) is earlier than the oldest (%lu)", st->name, before, after);
1521
1522                 if((before - after) > st->entries * st->update_every)
1523                         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);
1524         }
1525
1526
1527         // -------------------------------------------------------------------------
1528         // temp arrays for keeping values per dimension
1529
1530         calculated_number group_values[dimensions]; // keep sums when grouping
1531         int               print_hidden[dimensions]; // keep hidden flags
1532         int               found_non_zero[dimensions];
1533         int               found_non_existing[dimensions];
1534
1535         // initialize them
1536         for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1537                 group_values[c] = 0;
1538                 print_hidden[c] = (rd->flags & RRDDIM_FLAG_HIDDEN)?1:0;
1539                 found_non_zero[c] = 0;
1540                 found_non_existing[c] = 0;
1541         }
1542
1543
1544         // 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);
1545         // rrd2array(st, entries_to_show, before - (st->update_every * group * entries_to_show), before, group_method, only_non_zero);
1546         // rrd2rrdr(st, entries_to_show, before - (st->update_every * group * entries_to_show), before, group_method);
1547
1548         // -------------------------------------------------------------------------
1549         // remove dimensions that contain only zeros
1550
1551         int max_loop = 1;
1552         if(only_non_zero) max_loop = 2;
1553
1554         for(; max_loop ; max_loop--) {
1555
1556                 // -------------------------------------------------------------------------
1557                 // print the JSON header
1558
1559                 buffer_sprintf(wb, "{\n %scols%s:\n     [\n", kq, kq);
1560                 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);
1561                 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);
1562                 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);
1563
1564                 // print the header for each dimension
1565                 // and update the print_hidden array for the dimensions that should be hidden
1566                 int pc = 0;
1567                 for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1568                         if(!print_hidden[c]) {
1569                                 pc++;
1570                                 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);
1571                         }
1572                 }
1573                 if(!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, "no data", sq, kq, kq, sq, sq, kq, kq, sq, sq);
1575                 }
1576
1577                 // print the begin of row data
1578                 buffer_sprintf(wb, "\n  ],\n    %srows%s:\n     [\n", kq, kq);
1579
1580
1581                 // -------------------------------------------------------------------------
1582                 // the main loop
1583
1584                 int annotate_reset = 0;
1585                 int annotation_count = 0;
1586
1587                 long    t = rrdset_time2slot(st, before),
1588                                 stop_at_t = rrdset_time2slot(st, after),
1589                                 stop_now = 0;
1590
1591                 t -= t % group;
1592
1593                 time_t  now = rrdset_slot2time(st, t),
1594                                 dt = st->update_every;
1595
1596                 long count = 0, printed = 0, group_count = 0;
1597                 last_timestamp = 0;
1598
1599                 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"
1600                                         , st->id
1601                                         , after
1602                                         , before
1603                                         , points
1604                                         , group
1605                                         , st->current_entry
1606                                         , rrdset_first_entry_t(st)
1607                                         , rrdset_last_entry_t(st)
1608                                         , t
1609                                         , stop_at_t
1610                                         );
1611
1612                 long counter = 0;
1613                 for(; !stop_now ; now -= dt, t--, counter++) {
1614                         if(t < 0) t = st->entries - 1;
1615                         if(t == stop_at_t) stop_now = counter;
1616
1617                         int print_this = 0;
1618
1619                         if(st->debug) debug(D_RRD_STATS, "%s t = %ld, count = %ld, group_count = %ld, printed = %ld, now = %lu, %s %s"
1620                                         , st->id
1621                                         , t
1622                                         , count + 1
1623                                         , group_count + 1
1624                                         , printed
1625                                         , now
1626                                         , (group_count + 1 == group)?"PRINT":"  -  "
1627                                         , (now >= after && now <= before)?"RANGE":"  -  "
1628                                         );
1629
1630
1631                         // make sure we return data in the proper time range
1632                         if(now > before) continue;
1633                         if(now < after) break;
1634
1635                         //if(rrdset_slot2time(st, t) != now)
1636                         //      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));
1637
1638                         count++;
1639                         group_count++;
1640
1641                         // check if we have to print this now
1642                         if(group_count == group) {
1643                                 if(printed >= points) {
1644                                         // debug(D_RRD_STATS, "Already printed all rows. Stopping.");
1645                                         break;
1646                                 }
1647
1648                                 // generate the local date time
1649                                 struct tm tmbuf, *tm = localtime_r(&now, &tmbuf);
1650                                 if(!tm) { error("localtime() failed."); continue; }
1651                                 if(now > last_timestamp) last_timestamp = now;
1652
1653                                 if(printed) buffer_strcat(wb, "]},\n");
1654                                 buffer_strcat(wb, pre_date);
1655                                 buffer_jsdate(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
1656                                 buffer_strcat(wb, post_date);
1657
1658                                 print_this = 1;
1659                         }
1660
1661                         // do the calculations
1662                         for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1663                                 storage_number n = rd->values[t];
1664                                 calculated_number value = unpack_storage_number(n);
1665
1666                                 if(!does_storage_number_exist(n)) {
1667                                         value = 0.0;
1668                                         found_non_existing[c]++;
1669                                 }
1670                                 if(did_storage_number_reset(n)) annotate_reset = 1;
1671
1672                                 switch(group_method) {
1673                                         case GROUP_MAX:
1674                                                 if(abs(value) > abs(group_values[c])) group_values[c] = value;
1675                                                 break;
1676
1677                                         case GROUP_SUM:
1678                                                 group_values[c] += value;
1679                                                 break;
1680
1681                                         default:
1682                                         case GROUP_AVERAGE:
1683                                                 group_values[c] += value;
1684                                                 if(print_this) group_values[c] /= ( group_count - found_non_existing[c] );
1685                                                 break;
1686                                 }
1687                         }
1688
1689                         if(print_this) {
1690                                 if(annotate_reset) {
1691                                         annotation_count++;
1692                                         buffer_strcat(wb, overflow_annotation);
1693                                         annotate_reset = 0;
1694                                 }
1695                                 else
1696                                         buffer_strcat(wb, normal_annotation);
1697
1698                                 pc = 0;
1699                                 for(c = 0 ; c < dimensions ; c++) {
1700                                         if(found_non_existing[c] == group_count) {
1701                                                 // all entries are non-existing
1702                                                 pc++;
1703                                                 buffer_strcat(wb, pre_value);
1704                                                 buffer_strcat(wb, "null");
1705                                                 buffer_strcat(wb, post_value);
1706                                         }
1707                                         else if(!print_hidden[c]) {
1708                                                 pc++;
1709                                                 buffer_strcat(wb, pre_value);
1710                                                 buffer_rrd_value(wb, group_values[c]);
1711                                                 buffer_strcat(wb, post_value);
1712
1713                                                 if(group_values[c]) found_non_zero[c]++;
1714                                         }
1715
1716                                         // reset them for the next loop
1717                                         group_values[c] = 0;
1718                                         found_non_existing[c] = 0;
1719                                 }
1720
1721                                 // if all dimensions are hidden, print a null
1722                                 if(!pc) {
1723                                         buffer_strcat(wb, pre_value);
1724                                         buffer_strcat(wb, "null");
1725                                         buffer_strcat(wb, post_value);
1726                                 }
1727
1728                                 printed++;
1729                                 group_count = 0;
1730                         }
1731                 }
1732
1733                 if(printed) buffer_strcat(wb, "]}");
1734                 buffer_strcat(wb, "\n   ]\n}\n");
1735
1736                 if(only_non_zero && max_loop > 1) {
1737                         int changed = 0;
1738                         for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1739                                 group_values[c] = 0;
1740                                 found_non_existing[c] = 0;
1741
1742                                 if(!print_hidden[c] && !found_non_zero[c]) {
1743                                         changed = 1;
1744                                         print_hidden[c] = 1;
1745                                 }
1746                         }
1747
1748                         if(changed) buffer_flush(wb);
1749                         else break;
1750                 }
1751                 else break;
1752
1753         } // max_loop
1754
1755         debug(D_RRD_STATS, "RRD_STATS_JSON: %s total %ld bytes", st->name, wb->len);
1756
1757         pthread_rwlock_unlock(&st->rwlock);
1758         return last_timestamp;
1759 }