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