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