]> arthur.barton.de Git - netdata.git/blob - src/rrd2json.c
solved a duplicate memory allocation in the new API
[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 group;                              // how many collected values were grouped for each row
273         int update_every;               // what is the suggested update frequency in seconds
274
275         int d;                                  // the number of dimensions
276         int n;                                  // the number of values in the arrays
277
278         uint8_t *od;                    // the options for the dimensions
279
280         time_t *t;                              // array of n timestamps
281         calculated_number *v;   // array n x d values
282         uint8_t *o;                             // array n x d options
283
284         int c;                                  // current line ( -1 ~ n ), ( -1 = none, use rrdr_rows() to get number of rows )
285
286         int has_st_lock;                // if st is read locked by us
287 } RRDR;
288
289 #define rrdr_rows(r) ((r)->c + 1)
290
291 /*
292 static void rrdr_dump(RRDR *r)
293 {
294         long c, i;
295         RRDDIM *d;
296
297         fprintf(stderr, "\nCHART %s (%s)\n", r->st->id, r->st->name);
298
299         for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
300                 fprintf(stderr, "DIMENSION %s (%s), %s%s%s%s\n"
301                                 , d->id
302                                 , d->name
303                                 , (r->od[c] & RRDR_EMPTY)?"EMPTY ":""
304                                 , (r->od[c] & RRDR_RESET)?"RESET ":""
305                                 , (r->od[c] & RRDR_HIDDEN)?"HIDDEN ":""
306                                 , (r->od[c] & RRDR_NONZERO)?"NONZERO ":""
307                                 );
308         }
309
310         if(r->c < 0) {
311                 fprintf(stderr, "RRDR does not have any values in it.\n");
312                 return;
313         }
314
315         fprintf(stderr, "RRDR includes %d values in it:\n", r->c + 1);
316
317         // for each line in the array
318         for(i = 0; i <= r->c ;i++) {
319                 calculated_number *cn = &r->v[ i * r->d ];
320                 uint8_t *co = &r->o[ i * r->d ];
321
322                 // print the id and the timestamp of the line
323                 fprintf(stderr, "%ld %ld ", i + 1, r->t[i]);
324
325                 // for each dimension
326                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
327                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
328                         if(unlikely(!(r->od[c] & RRDR_NONZERO))) continue;
329
330                         if(co[c] & RRDR_EMPTY)
331                                 fprintf(stderr, "null ");
332                         else
333                                 fprintf(stderr, CALCULATED_NUMBER_FORMAT " %s%s%s%s "
334                                         , cn[c]
335                                         , (co[c] & RRDR_EMPTY)?"E":" "
336                                         , (co[c] & RRDR_RESET)?"R":" "
337                                         , (co[c] & RRDR_HIDDEN)?"H":" "
338                                         , (co[c] & RRDR_NONZERO)?"N":" "
339                                         );
340                 }
341
342                 fprintf(stderr, "\n");
343         }
344 }
345 */
346
347 void rrdr_disable_not_selected_dimensions(RRDR *r, const char *dims)
348 {
349         char b[strlen(dims) + 1];
350         char *o = b, *tok;
351         strcpy(o, dims);
352
353         long c;
354         RRDDIM *d;
355
356         // disable all of them
357         for(c = 0, d = r->st->dimensions; d ;c++, d = d->next)
358                 r->od[c] |= RRDR_HIDDEN;
359
360         while(o && *o && (tok = mystrsep(&o, ", |"))) {
361                 if(!*tok) continue;
362
363                 // find it and enable it
364                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
365                         if(!strcmp(d->name, tok)) {
366                                 r->od[c] &= ~RRDR_HIDDEN;
367                         }
368                 }
369         }
370 }
371
372 #define JSON_DATES_JS 1
373 #define JSON_DATES_TIMESTAMP 2
374
375 static void rrdr2json(RRDR *r, BUFFER *wb, uint32_t options, int datatable)
376 {
377         int annotations = 0, dates = JSON_DATES_JS, dates_with_new = 0;
378         char kq[2] = "",                                        // key quote
379                 sq[2] = "",                                             // string quote
380                 pre_label[101] = "",                    // before each label
381                 post_label[101] = "",                   // after each label
382                 pre_date[101] = "",                             // the beginning of line, to the date
383                 post_date[101] = "",                    // closing the date
384                 pre_value[101] = "",                    // before each value
385                 post_value[101] = "",                   // after each value
386                 post_line[101] = "",                    // at the end of each row
387                 normal_annotation[201] = "",    // default row annotation
388                 overflow_annotation[201] = "",  // overflow row annotation
389                 data_begin[101] = "",                   // between labels and values
390                 finish[101] = "";                               // at the end of everything
391
392         if(datatable) {
393                 dates = JSON_DATES_JS;
394                 if( options & RRDR_OPTION_GOOGLE_JSON ) {
395                         kq[0] = '\0';
396                         sq[0] = '\'';
397                 }
398                 else {
399                         kq[0] = '"';
400                         sq[0] = '"';
401                 }
402                 annotations = 1;
403                 snprintf(pre_date,   100, "             {%sc%s:[{%sv%s:%s", kq, kq, kq, kq, sq);
404                 snprintf(post_date,  100, "%s}", sq);
405                 snprintf(pre_label,  100, ",\n          {%sid%s:%s%s,%slabel%s:%s", kq, kq, sq, sq, kq, kq, sq);
406                 snprintf(post_label, 100, "%s,%spattern%s:%s%s,%stype%s:%snumber%s}", sq, kq, kq, sq, sq, kq, kq, sq, sq);
407                 snprintf(pre_value,  100, ",{%sv%s:", kq, kq);
408                 snprintf(post_value, 100, "}");
409                 snprintf(post_line,  100, "]}");
410                 snprintf(data_begin, 100, "\n   ],\n    %srows%s:\n     [\n", kq, kq);
411                 snprintf(finish,     100, "\n   ]\n}\n");
412
413                 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);
414                 snprintf(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
415
416                 buffer_sprintf(wb, "{\n %supdate_every%s: %d,\n %scols%s:\n     [\n", kq, kq, r->update_every, kq, kq, kq, kq);
417                 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);
418                 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);
419                 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);
420
421                 // remove the valueobjects flag
422                 // google wants its own keys
423                 if(options & RRDR_OPTION_OBJECTSROWS)
424                         options &= ~RRDR_OPTION_OBJECTSROWS;
425         }
426         else {
427                 kq[0] = '"';
428                 sq[0] = '"';
429                 if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
430                         dates = JSON_DATES_TIMESTAMP;
431                         dates_with_new = 0;
432                 }
433                 else {
434                         dates = JSON_DATES_JS;
435                         dates_with_new = 1;
436                 }
437                 if( options & RRDR_OPTION_OBJECTSROWS )
438                         snprintf(pre_date,   100, "             { ");
439                 else
440                         snprintf(pre_date,   100, "             [ ");
441                 snprintf(pre_label,  100, ", \"");
442                 snprintf(post_label, 100, "\"");
443                 snprintf(pre_value,  100, ", ");
444                 if( options & RRDR_OPTION_OBJECTSROWS )
445                         snprintf(post_line,  100, "}");
446                 else
447                         snprintf(post_line,  100, "]");
448                 snprintf(data_begin, 100, "],\n %sdata%s:\n     [\n", kq, kq);
449                 snprintf(finish,     100, "\n   ]\n}\n");
450
451                 buffer_sprintf(wb, "{\n %supdate_every%s: %d,\n %slabels%s: [", kq, kq, r->update_every, kq, kq);
452                 buffer_sprintf(wb, "%stime%s", sq, sq);
453         }
454
455         // -------------------------------------------------------------------------
456         // print the JSON header
457
458         long c, i;
459         RRDDIM *rd;
460
461         // print the csv header
462         for(c = 0, i = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
463                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
464                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
465
466                 buffer_strcat(wb, pre_label);
467                 buffer_strcat(wb, rd->name);
468                 buffer_strcat(wb, post_label);
469                 i++;
470         }
471         if(!i) {
472                 buffer_strcat(wb, pre_label);
473                 buffer_strcat(wb, "no data");
474                 buffer_strcat(wb, post_label);
475         }
476
477         // print the begin of row data
478         buffer_strcat(wb, data_begin);
479
480         // if all dimensions are hidden, print a null
481         if(!i) {
482                 buffer_strcat(wb, pre_value);
483                 if(options & RRDR_OPTION_NULL2ZERO)
484                         buffer_strcat(wb, "0");
485                 else
486                         buffer_strcat(wb, "null");
487                 buffer_strcat(wb, post_value);
488         }
489
490         long start = 0, end = rrdr_rows(r), step = 1;
491         if((options & RRDR_OPTION_REVERSED)) {
492                 start = rrdr_rows(r) - 1;
493                 end = -1;
494                 step = -1;
495         }
496
497         // for each line in the array
498         for(i = start; i != end ;i += step) {
499                 calculated_number *cn = &r->v[ i * r->d ];
500                 uint8_t *co = &r->o[ i * r->d ];
501
502                 time_t now = r->t[i];
503
504                 if(dates == JSON_DATES_JS) {
505                         // generate the local date time
506                         struct tm *tm = localtime(&now);
507                         if(!tm) { error("localtime() failed."); continue; }
508
509                         if(likely(i != start)) buffer_strcat(wb, ",\n");
510                         buffer_strcat(wb, pre_date);
511
512                         if( options & RRDR_OPTION_OBJECTSROWS )
513                                 buffer_sprintf(wb, "%stime%s: ", kq, kq);
514
515                         if(dates_with_new)
516                                 buffer_strcat(wb, "new ");
517
518                         buffer_jsdate(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
519
520                         buffer_strcat(wb, post_date);
521
522                         if(annotations) {
523                                 if(co[c] & RRDR_RESET)
524                                         buffer_strcat(wb, overflow_annotation);
525                                 else
526                                         buffer_strcat(wb, normal_annotation);
527                         }
528                 }
529                 else {
530                         // print the timestamp of the line
531                         if(likely(i != start)) buffer_strcat(wb, ",\n");
532                         buffer_strcat(wb, pre_date);
533
534                         if( options & RRDR_OPTION_OBJECTSROWS )
535                                 buffer_sprintf(wb, "%stime%s: ", kq, kq);
536
537                         buffer_rrd_value(wb, (calculated_number)r->t[i]);
538                         // in ms
539                         if(options & RRDR_OPTION_MILLISECONDS) buffer_strcat(wb, "000");
540
541                         buffer_strcat(wb, post_date);
542                 }
543
544                 // for each dimension
545                 for(c = 0, rd = r->st->dimensions; rd ;c++, rd = rd->next) {
546                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
547                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
548
549                         calculated_number n = cn[c];
550
551                         buffer_strcat(wb, pre_value);
552
553                         if( options & RRDR_OPTION_OBJECTSROWS )
554                                 buffer_sprintf(wb, "%s%s%s: ", kq, rd->name, kq);
555
556                         if(co[c] & RRDR_EMPTY) {
557                                 if(options & RRDR_OPTION_NULL2ZERO)
558                                         buffer_strcat(wb, "0");
559                                 else
560                                         buffer_strcat(wb, "null");
561                         }
562                         else if((options & RRDR_OPTION_ABSOLUTE))
563                                 buffer_rrd_value(wb, (n<0)?-n:n);
564                         else
565                                 buffer_rrd_value(wb, n);
566
567                         buffer_strcat(wb, post_value);
568                 }
569
570                 buffer_strcat(wb, post_line);
571         }
572
573         buffer_strcat(wb, finish);
574 }
575
576 static void rrdr2csv(RRDR *r, BUFFER *wb, uint32_t options, const char *startline, const char *separator, const char *endline)
577 {
578         long c, i;
579         RRDDIM *d;
580
581         // print the csv header
582         for(c = 0, i = 0, d = r->st->dimensions; d ;c++, d = d->next) {
583                 if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
584                 if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
585
586                 if(!i) {
587                         buffer_strcat(wb, startline);
588                         buffer_strcat(wb, "time");
589                 }
590                 buffer_strcat(wb, separator);
591                 buffer_strcat(wb, d->name);
592                 i++;
593         }
594         buffer_strcat(wb, endline);
595
596         if(!i) {
597                 // no dimensions present
598                 return;
599         }
600
601         long start = 0, end = rrdr_rows(r), step = 1;
602         if((options & RRDR_OPTION_REVERSED)) {
603                 start = rrdr_rows(r) - 1;
604                 end = -1;
605                 step = -1;
606         }
607
608         // for each line in the array
609         for(i = start; i != end ;i += step) {
610                 calculated_number *cn = &r->v[ i * r->d ];
611                 uint8_t *co = &r->o[ i * r->d ];
612
613                 buffer_strcat(wb, startline);
614
615                 time_t now = r->t[i];
616
617                 if((options & RRDR_OPTION_SECONDS) || (options & RRDR_OPTION_MILLISECONDS)) {
618                         // print the timestamp of the line
619                         buffer_rrd_value(wb, (calculated_number)now);
620                         // in ms
621                         if(options & RRDR_OPTION_MILLISECONDS) buffer_strcat(wb, "000");
622                 }
623                 else {
624                         // generate the local date time
625                         struct tm *tm = localtime(&now);
626                         if(!tm) { error("localtime() failed."); continue; }
627                         buffer_date(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
628                 }
629
630                 // for each dimension
631                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
632                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
633                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
634
635                         buffer_strcat(wb, separator);
636
637                         calculated_number n = cn[c];
638
639                         if(co[c] & RRDR_EMPTY) {
640                                 if(options & RRDR_OPTION_NULL2ZERO)
641                                         buffer_strcat(wb, "0");
642                                 else
643                                         buffer_strcat(wb, "null");
644                         }
645                         else if((options & RRDR_OPTION_ABSOLUTE))
646                                 buffer_rrd_value(wb, (n<0)?-n:n);
647                         else
648                                 buffer_rrd_value(wb, n);
649                 }
650
651                 buffer_strcat(wb, endline);
652         }
653 }
654
655 static void rrdr2ssv(RRDR *r, BUFFER *out, uint32_t options, const char *prefix, const char *separator, const char *suffix)
656 {
657         long c, i;
658         RRDDIM *d;
659
660         buffer_strcat(out, prefix);
661         long start = 0, end = rrdr_rows(r), step = 1;
662         if((options & RRDR_OPTION_REVERSED)) {
663                 start = rrdr_rows(r) - 1;
664                 end = -1;
665                 step = -1;
666         }
667
668         // for each line in the array
669         for(i = start; i != end ;i += step) {
670
671                 calculated_number *cn = &r->v[ i * r->d ];
672                 uint8_t *co = &r->o[ i * r->d ];
673
674                 calculated_number sum = 0, min = 0, max = 0;
675                 int all_null = 1, init = 1;
676
677                 // for each dimension
678                 for(c = 0, d = r->st->dimensions; d ;c++, d = d->next) {
679                         if(unlikely(r->od[c] & RRDR_HIDDEN)) continue;
680                         if(unlikely((options & RRDR_OPTION_NONZERO) && !(r->od[c] & RRDR_NONZERO))) continue;
681
682                         calculated_number n = cn[c];
683
684                         if(unlikely(init)) {
685                                 if(n > 0) {
686                                         min = 0;
687                                         max = n;
688                                 }
689                                 else {
690                                         min = n;
691                                         max = 0;
692                                 }
693                                 init = 0;
694                         }
695
696                         if(likely(!(co[c] & RRDR_EMPTY))) {
697                                 all_null = 0;
698                                 if((options & RRDR_OPTION_ABSOLUTE) && n < 0) n = -n;
699                                 sum += n;
700                         }
701
702                         if(n < min) min = n;
703                         if(n > max) max = n;
704                 }
705
706                 if(likely(i != start))
707                         buffer_strcat(out, separator);
708
709                 if(all_null) {
710                         if(options & RRDR_OPTION_NULL2ZERO)
711                                 buffer_strcat(out, "0");
712                         else
713                                 buffer_strcat(out, "null");
714                 }
715                 else if(options & RRDR_OPTION_MIN2MAX)
716                         buffer_rrd_value(out, max - min);
717                 else
718                         buffer_rrd_value(out, sum);
719         }
720         buffer_strcat(out, suffix);
721 }
722
723 inline static calculated_number *rrdr_line_values(RRDR *r)
724 {
725         return &r->v[ r->c * r->d ];
726 }
727
728 inline static uint8_t *rrdr_line_options(RRDR *r)
729 {
730         return &r->o[ r->c * r->d ];
731 }
732
733 inline static int rrdr_line_init(RRDR *r, time_t t)
734 {
735         r->c++;
736         if(unlikely(r->c >= r->n)) {
737                 r->c = r->n - 1;
738                 return 0;
739         }
740
741         // save the time
742         r->t[r->c] = t;
743
744         return 1;
745 }
746
747 inline static void rrdr_lock_rrdset(RRDR *r) {
748         if(unlikely(!r)) {
749                 error("NULL value given!");
750                 return;
751         }
752
753         pthread_rwlock_rdlock(&r->st->rwlock);
754         r->has_st_lock = 1;
755 }
756
757 inline static void rrdr_unlock_rrdset(RRDR *r) {
758         if(unlikely(!r)) {
759                 error("NULL value given!");
760                 return;
761         }
762
763         if(likely(r->has_st_lock)) {
764                 pthread_rwlock_unlock(&r->st->rwlock);
765                 r->has_st_lock = 0;
766         }
767 }
768
769 inline static void rrdr_free(RRDR *r)
770 {
771         if(unlikely(!r)) {
772                 error("NULL value given!");
773                 return;
774         }
775
776         rrdr_unlock_rrdset(r);
777         if(likely(r->t)) free(r->t);
778         if(likely(r->v)) free(r->v);
779         if(likely(r->o)) free(r->o);
780         if(likely(r->od)) free(r->od);
781         free(r);
782 }
783
784 static RRDR *rrdr_create(RRDSET *st, int n)
785 {
786         if(unlikely(!st)) {
787                 error("NULL value given!");
788                 return NULL;
789         }
790
791         RRDR *r = calloc(1, sizeof(RRDR));
792         if(unlikely(!r)) goto cleanup;
793
794         r->st = st;
795
796         rrdr_lock_rrdset(r);
797
798         RRDDIM *rd;
799         for(rd = st->dimensions ; rd ; rd = rd->next) r->d++;
800
801         r->n = n;
802         r->t = malloc(n * sizeof(time_t));
803         if(unlikely(!r->t)) goto cleanup;
804
805         r->v = malloc(n * r->d * sizeof(calculated_number));
806         if(unlikely(!r->v)) goto cleanup;
807
808         r->o = malloc(n * r->d * sizeof(uint8_t));
809         if(unlikely(!r->o)) goto cleanup;
810
811         r->od = calloc(r->d, sizeof(uint8_t));
812         if(unlikely(!r->od)) goto cleanup;
813
814         r->c = -1;
815
816         return r;
817
818 cleanup:
819         error("Cannot allocate memory");
820         if(likely(r)) rrdr_free(r);
821         return NULL;
822 }
823
824 RRDR *rrd2rrdr(RRDSET *st, long points, long long after, long long before, int group_method)
825 {
826         int debug = st->debug;
827
828         time_t first_entry_t = rrdset_first_entry_t(st);
829         time_t last_entry_t = rrdset_last_entry_t(st);
830
831         if(before == 0 && after == 0) {
832                 before = last_entry_t;
833                 after = first_entry_t;
834         }
835
836         // allow relative for before and after
837         if(before <= st->update_every * st->entries) before = last_entry_t + before;
838         if(after <= st->update_every * st->entries) after = last_entry_t + after;
839
840         // make sure they are within our timeframe
841         if(before > last_entry_t) before = last_entry_t;
842         if(before < first_entry_t) before = first_entry_t;
843
844         if(after > last_entry_t) after = last_entry_t;
845         if(after < first_entry_t) after = first_entry_t;
846
847         // check if they are upside down
848         if(after > before) {
849                 time_t tmp = before;
850                 before = after;
851                 after = tmp;
852         }
853
854         // the duration of the chart
855         time_t duration = before - after;
856         if(duration <= 0) return NULL;
857
858         // check the required points
859         if(points > duration / st->update_every) points = 0;
860         if(points <= 0) points = duration / st->update_every;
861
862         // calculate proper grouping of source data
863         long group = duration / points;
864         if(group <= 0) group = 1;
865         if(duration / group > points) group++;
866
867         // error("NEW: points=%d after=%d before=%d group=%d, duration=%d", points, after, before, group, duration);
868
869         // Now we have:
870         // before = the end time of the calculation
871         // after = the start time of the calculation
872         // duration = the duration of the calculation
873         // group = the number of source points to aggregate / group together
874         // method = the method of grouping source points
875         // points = the number of points to generate
876
877
878         // -------------------------------------------------------------------------
879         // initialize our result set
880
881         RRDR *r = rrdr_create(st, points);
882         if(!r) return NULL;
883         if(!r->d) {
884                 rrdr_free(r);
885                 return NULL;
886         }
887
888         // find how many dimensions we have
889         long dimensions = r->d;
890
891
892         // -------------------------------------------------------------------------
893         // checks for debugging
894
895         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"
896                         , st->id
897                         , first_entry_t
898                         , last_entry_t
899                         , last_entry_t - first_entry_t
900                         , after
901                         , before
902                         , duration
903                         , points
904                         , group
905                         );
906
907
908         // -------------------------------------------------------------------------
909         // temp arrays for keeping values per dimension
910
911         calculated_number       group_values[dimensions]; // keep sums when grouping
912         long                            group_counts[dimensions]; // keep the number of values added to group_values
913         uint8_t                         group_options[dimensions];
914         uint8_t                         found_non_zero[dimensions];
915
916
917         // initialize them
918         RRDDIM *rd;
919         long c;
920         for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
921                 group_values[c] = 0;
922                 group_counts[c] = 0;
923                 group_options[c] = 0;
924                 found_non_zero[c] = 0;
925         }
926
927
928         // -------------------------------------------------------------------------
929         // the main loop
930
931         long    start_at_slot = rrdset_time2slot(st, before), // rrdset_last_slot(st),
932                         stop_at_slot = rrdset_time2slot(st, after);
933
934         time_t  now = rrdset_slot2time(st, start_at_slot),
935                         dt = st->update_every,
936                         group_start_t = 0;
937
938         if(unlikely(debug)) debug(D_RRD_STATS, "INFO  %s after_t: %lu (stop_at_t: %ld), before_t: %lu (start_at_t: %ld), start_t(now): %lu, current_entry: %ld, entries: %ld"
939                         , st->id
940                         , after
941                         , stop_at_slot
942                         , before
943                         , start_at_slot
944                         , now
945                         , st->current_entry
946                         , st->entries
947                         );
948
949         // align to group for proper panning of data
950         start_at_slot -= start_at_slot % group;
951         stop_at_slot -= stop_at_slot % group;
952         now = rrdset_slot2time(st, start_at_slot);
953
954         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"
955                         , st->id
956                         , after
957                         , stop_at_slot
958                         , before
959                         , start_at_slot
960                         , now
961                         , st->current_entry
962                         , st->entries
963                         );
964
965         r->group = group;
966         r->update_every = group * st->update_every;
967
968         long slot = start_at_slot, counter = 0, stop_now = 0, added = 0, group_count = 0, add_this = 0;
969         for(; !stop_now ; now -= dt, slot--, counter++) {
970                 if(unlikely(slot < 0)) slot = st->entries - 1;
971                 if(unlikely(slot == stop_at_slot)) stop_now = counter;
972
973                 if(unlikely(debug)) debug(D_RRD_STATS, "ROW %s slot: %ld, entries_counter: %ld, group_count: %ld, added: %ld, now: %lu, %s %s"
974                                 , st->id
975                                 , slot
976                                 , counter
977                                 , group_count + 1
978                                 , added
979                                 , now
980                                 , (group_count + 1 == group)?"PRINT":"  -  "
981                                 , (now >= after && now <= before)?"RANGE":"  -  "
982                                 );
983
984                 // make sure we return data in the proper time range
985                 if(unlikely(now > before)) continue;
986                 if(unlikely(now < after)) break;
987
988                 if(unlikely(group_count == 0)) group_start_t = now;
989                 group_count++;
990
991                 if(unlikely(group_count == group)) {
992                         if(unlikely(added >= points)) break;
993                         add_this = 1;
994                 }
995
996                 // do the calculations
997                 for(rd = st->dimensions, c = 0 ; likely(rd && c < dimensions) ; rd = rd->next, c++) {
998                         storage_number n = rd->values[slot];
999                         if(unlikely(!does_storage_number_exist(n))) continue;
1000
1001                         group_counts[c]++;
1002
1003                         calculated_number value = unpack_storage_number(n);
1004                         if(likely(value != 0.0)) {
1005                                 group_options[c] |= RRDR_NONZERO;
1006                                 found_non_zero[c] = 1;
1007                         }
1008
1009                         if(unlikely(did_storage_number_reset(n)))
1010                                 group_options[c] |= RRDR_RESET;
1011
1012                         switch(group_method) {
1013                                 case GROUP_MAX:
1014                                         if(unlikely(abs(value) > abs(group_values[c])))
1015                                                 group_values[c] = value;
1016                                         break;
1017
1018                                 default:
1019                                 case GROUP_SUM:
1020                                 case GROUP_AVERAGE:
1021                                         group_values[c] += value;
1022                                         break;
1023                         }
1024                 }
1025
1026                 // added it
1027                 if(unlikely(add_this)) {
1028                         if(unlikely(!rrdr_line_init(r, group_start_t))) break;
1029
1030                         calculated_number *cn = rrdr_line_values(r);
1031                         uint8_t *co = rrdr_line_options(r);
1032
1033                         for(rd = st->dimensions, c = 0 ; likely(rd && c < dimensions) ; rd = rd->next, c++) {
1034
1035                                 // update the dimension options
1036                                 if(likely(found_non_zero[c])) r->od[c] |= RRDR_NONZERO;
1037                                 if(unlikely(rd->flags & RRDDIM_FLAG_HIDDEN)) r->od[c] |= RRDR_HIDDEN;
1038
1039                                 // store the specific point options
1040                                 co[c] = group_options[c];
1041
1042                                 // store the value
1043                                 if(unlikely(group_counts[c] == 0)) {
1044                                         cn[c] = 0.0;
1045                                         co[c] |= RRDR_EMPTY;
1046                                 }
1047                                 else if(unlikely(group_method == GROUP_AVERAGE)) {
1048                                         cn[c] = group_values[c] / group_counts[c];
1049                                 }
1050                                 else {
1051                                         cn[c] = group_values[c];
1052                                 }
1053
1054                                 // reset them for the next loop
1055                                 group_values[c] = 0;
1056                                 group_counts[c] = 0;
1057                                 group_options[c] = 0;
1058                         }
1059
1060                         added++;
1061                         group_count = 0;
1062                         add_this = 0;
1063                 }
1064         }
1065
1066         return r;
1067 }
1068
1069 int rrd2format(RRDSET *st, BUFFER *out, BUFFER *dimensions, uint32_t format, long points, long long after, long long before, int group_method, uint32_t options, time_t *latest_timestamp)
1070 {
1071         RRDR *rrdr = rrd2rrdr(st, points, after, before, group_method);
1072         if(!rrdr) {
1073                 buffer_strcat(out, "Cannot generate output with these parameters on this chart.");
1074                 return 500;
1075         }
1076
1077         if(dimensions)
1078                 rrdr_disable_not_selected_dimensions(rrdr, buffer_tostring(dimensions));
1079
1080         if(latest_timestamp && rrdr_rows(rrdr) > 0)
1081                 *latest_timestamp = rrdr->t[rrdr_rows(rrdr) - 1];
1082
1083         switch(format) {
1084         case DATASOURCE_SSV:
1085                 out->contenttype = CT_TEXT_PLAIN;
1086                 rrdr2ssv(rrdr, out, options, "", " ", "");
1087                 break;
1088
1089         case DATASOURCE_SSV_COMMA:
1090                 out->contenttype = CT_TEXT_PLAIN;
1091                 rrdr2ssv(rrdr, out, options, "", ",", "");
1092                 break;
1093
1094         case DATASOURCE_JS_ARRAY:
1095                 out->contenttype = CT_APPLICATION_JSON;
1096                 rrdr2ssv(rrdr, out, options, "[", ",", "]");
1097                 break;
1098
1099         case DATASOURCE_CSV:
1100                 out->contenttype = CT_TEXT_PLAIN;
1101                 rrdr2csv(rrdr, out, options, "", ",", "\r\n");
1102                 break;
1103
1104         case DATASOURCE_TSV:
1105                 out->contenttype = CT_TEXT_PLAIN;
1106                 rrdr2csv(rrdr, out, options, "", "\t", "\r\n");
1107                 break;
1108
1109         case DATASOURCE_HTML:
1110                 out->contenttype = CT_TEXT_HTML;
1111                 buffer_strcat(out, "<html>\n<center><table border=\"0\" cellpadding=\"5\" cellspacing=\"5\">");
1112                 rrdr2csv(rrdr, out, options, "<tr><td>", "</td><td>", "</td></tr>\n");
1113                 buffer_strcat(out, "</table>\n</center>\n</html>\n");
1114                 break;
1115
1116         case DATASOURCE_DATATABLE_JSONP:
1117                 out->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1118                 rrdr2json(rrdr, out, options, 1);
1119                 break;
1120
1121         case DATASOURCE_DATATABLE_JSON:
1122                 out->contenttype = CT_APPLICATION_JSON;
1123                 rrdr2json(rrdr, out, options, 1);
1124                 break;
1125
1126         case DATASOURCE_JSONP:
1127                 out->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1128                 rrdr2json(rrdr, out, options, 0);
1129                 break;
1130
1131         case DATASOURCE_JSON:
1132         default:
1133                 out->contenttype = CT_APPLICATION_JSON;
1134                 rrdr2json(rrdr, out, options, 0);
1135                 break;
1136         }
1137
1138         rrdr_free(rrdr);
1139         return 200;
1140 }
1141
1142 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)
1143 {
1144         int c;
1145         pthread_rwlock_rdlock(&st->rwlock);
1146
1147
1148         // -------------------------------------------------------------------------
1149         // switch from JSON to google JSON
1150
1151         char kq[2] = "\"";
1152         char sq[2] = "\"";
1153         switch(type) {
1154                 case DATASOURCE_DATATABLE_JSON:
1155                 case DATASOURCE_DATATABLE_JSONP:
1156                         kq[0] = '\0';
1157                         sq[0] = '\'';
1158                         break;
1159
1160                 case DATASOURCE_JSON:
1161                 default:
1162                         break;
1163         }
1164
1165
1166         // -------------------------------------------------------------------------
1167         // validate the parameters
1168
1169         if(points < 1) points = 1;
1170         if(group < 1) group = 1;
1171
1172         if(before == 0 || before > rrdset_last_entry_t(st)) before = rrdset_last_entry_t(st);
1173         if(after  == 0 || after < rrdset_first_entry_t(st)) after = rrdset_first_entry_t(st);
1174
1175         // ---
1176
1177         // our return value (the last timestamp printed)
1178         // this is required to detect re-transmit in google JSONP
1179         time_t last_timestamp = 0;
1180
1181
1182         // -------------------------------------------------------------------------
1183         // find how many dimensions we have
1184
1185         int dimensions = 0;
1186         RRDDIM *rd;
1187         for( rd = st->dimensions ; rd ; rd = rd->next) dimensions++;
1188         if(!dimensions) {
1189                 pthread_rwlock_unlock(&st->rwlock);
1190                 buffer_strcat(wb, "No dimensions yet.");
1191                 return 0;
1192         }
1193
1194
1195         // -------------------------------------------------------------------------
1196         // prepare various strings, to speed up the loop
1197
1198         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);
1199         char normal_annotation[201];   snprintf(normal_annotation,   200, ",{%sv%s:null},{%sv%s:null}", kq, kq, kq, kq);
1200         char pre_date[51];             snprintf(pre_date,             50, "             {%sc%s:[{%sv%s:%s", kq, kq, kq, kq, sq);
1201         char post_date[21];            snprintf(post_date,            20, "%s}", sq);
1202         char pre_value[21];            snprintf(pre_value,            20, ",{%sv%s:", kq, kq);
1203         char post_value[21];           snprintf(post_value,           20, "}");
1204
1205
1206         // -------------------------------------------------------------------------
1207         // checks for debugging
1208
1209         if(st->debug) {
1210                 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"
1211                         , st->id
1212                         , rrdset_first_entry_t(st)
1213                         , rrdset_last_entry_t(st)
1214                         , rrdset_last_entry_t(st) - rrdset_first_entry_t(st)
1215                         , after
1216                         , before
1217                         , before - after
1218                         , points
1219                         , group
1220                         );
1221
1222                 if(before < after)
1223                         debug(D_RRD_STATS, "WARNING: %s The newest value in the database (%lu) is earlier than the oldest (%lu)", st->name, before, after);
1224
1225                 if((before - after) > st->entries * st->update_every)
1226                         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);
1227         }
1228
1229
1230         // -------------------------------------------------------------------------
1231         // temp arrays for keeping values per dimension
1232
1233         calculated_number group_values[dimensions]; // keep sums when grouping
1234         int               print_hidden[dimensions]; // keep hidden flags
1235         int               found_non_zero[dimensions];
1236         int               found_non_existing[dimensions];
1237
1238         // initialize them
1239         for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1240                 group_values[c] = 0;
1241                 print_hidden[c] = (rd->flags & RRDDIM_FLAG_HIDDEN)?1:0;
1242                 found_non_zero[c] = 0;
1243                 found_non_existing[c] = 0;
1244         }
1245
1246
1247         // 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);
1248         // rrd2array(st, entries_to_show, before - (st->update_every * group * entries_to_show), before, group_method, only_non_zero);
1249         // rrd2rrdr(st, entries_to_show, before - (st->update_every * group * entries_to_show), before, group_method);
1250
1251         // -------------------------------------------------------------------------
1252         // remove dimensions that contain only zeros
1253
1254         int max_loop = 1;
1255         if(only_non_zero) max_loop = 2;
1256
1257         for(; max_loop ; max_loop--) {
1258
1259                 // -------------------------------------------------------------------------
1260                 // print the JSON header
1261
1262                 buffer_sprintf(wb, "{\n %scols%s:\n     [\n", kq, kq);
1263                 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);
1264                 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);
1265                 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);
1266
1267                 // print the header for each dimension
1268                 // and update the print_hidden array for the dimensions that should be hidden
1269                 int pc = 0;
1270                 for( rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1271                         if(!print_hidden[c]) {
1272                                 pc++;
1273                                 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);
1274                         }
1275                 }
1276                 if(!pc) {
1277                         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);
1278                 }
1279
1280                 // print the begin of row data
1281                 buffer_sprintf(wb, "\n  ],\n    %srows%s:\n     [\n", kq, kq);
1282
1283
1284                 // -------------------------------------------------------------------------
1285                 // the main loop
1286
1287                 int annotate_reset = 0;
1288                 int annotation_count = 0;
1289
1290                 long    t = rrdset_time2slot(st, before),
1291                                 stop_at_t = rrdset_time2slot(st, after),
1292                                 stop_now = 0;
1293
1294                 t -= t % group;
1295
1296                 time_t  now = rrdset_slot2time(st, t),
1297                                 dt = st->update_every;
1298
1299                 long count = 0, printed = 0, group_count = 0;
1300                 last_timestamp = 0;
1301
1302                 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"
1303                                         , st->id
1304                                         , after
1305                                         , before
1306                                         , points
1307                                         , group
1308                                         , st->current_entry
1309                                         , rrdset_first_entry_t(st)
1310                                         , rrdset_last_entry_t(st)
1311                                         , t
1312                                         , stop_at_t
1313                                         );
1314
1315                 for(; !stop_now ; now -= dt, t--) {
1316                         if(t < 0) t = st->entries - 1;
1317                         if(t == stop_at_t) stop_now = 1;
1318
1319                         int print_this = 0;
1320
1321                         if(st->debug) debug(D_RRD_STATS, "%s t = %ld, count = %ld, group_count = %ld, printed = %ld, now = %lu, %s %s"
1322                                         , st->id
1323                                         , t
1324                                         , count + 1
1325                                         , group_count + 1
1326                                         , printed
1327                                         , now
1328                                         , (group_count + 1 == group)?"PRINT":"  -  "
1329                                         , (now >= after && now <= before)?"RANGE":"  -  "
1330                                         );
1331
1332
1333                         // make sure we return data in the proper time range
1334                         if(now > before) continue;
1335                         if(now < after) break;
1336
1337                         //if(rrdset_slot2time(st, t) != now)
1338                         //      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));
1339
1340                         count++;
1341                         group_count++;
1342
1343                         // check if we have to print this now
1344                         if(group_count == group) {
1345                                 if(printed >= points) {
1346                                         // debug(D_RRD_STATS, "Already printed all rows. Stopping.");
1347                                         break;
1348                                 }
1349
1350                                 // generate the local date time
1351                                 struct tm *tm = localtime(&now);
1352                                 if(!tm) { error("localtime() failed."); continue; }
1353                                 if(now > last_timestamp) last_timestamp = now;
1354
1355                                 if(printed) buffer_strcat(wb, "]},\n");
1356                                 buffer_strcat(wb, pre_date);
1357                                 buffer_jsdate(wb, tm->tm_year + 1900, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
1358                                 buffer_strcat(wb, post_date);
1359
1360                                 print_this = 1;
1361                         }
1362
1363                         // do the calculations
1364                         for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1365                                 storage_number n = rd->values[t];
1366                                 calculated_number value = unpack_storage_number(n);
1367
1368                                 if(!does_storage_number_exist(n)) {
1369                                         value = 0.0;
1370                                         found_non_existing[c]++;
1371                                 }
1372                                 if(did_storage_number_reset(n)) annotate_reset = 1;
1373
1374                                 switch(group_method) {
1375                                         case GROUP_MAX:
1376                                                 if(abs(value) > abs(group_values[c])) group_values[c] = value;
1377                                                 break;
1378
1379                                         case GROUP_SUM:
1380                                                 group_values[c] += value;
1381                                                 break;
1382
1383                                         default:
1384                                         case GROUP_AVERAGE:
1385                                                 group_values[c] += value;
1386                                                 if(print_this) group_values[c] /= ( group_count - found_non_existing[c] );
1387                                                 break;
1388                                 }
1389                         }
1390
1391                         if(print_this) {
1392                                 if(annotate_reset) {
1393                                         annotation_count++;
1394                                         buffer_strcat(wb, overflow_annotation);
1395                                         annotate_reset = 0;
1396                                 }
1397                                 else
1398                                         buffer_strcat(wb, normal_annotation);
1399
1400                                 pc = 0;
1401                                 for(c = 0 ; c < dimensions ; c++) {
1402                                         if(found_non_existing[c] == group_count) {
1403                                                 // all entries are non-existing
1404                                                 pc++;
1405                                                 buffer_strcat(wb, pre_value);
1406                                                 buffer_strcat(wb, "null");
1407                                                 buffer_strcat(wb, post_value);
1408                                         }
1409                                         else if(!print_hidden[c]) {
1410                                                 pc++;
1411                                                 buffer_strcat(wb, pre_value);
1412                                                 buffer_rrd_value(wb, group_values[c]);
1413                                                 buffer_strcat(wb, post_value);
1414
1415                                                 if(group_values[c]) found_non_zero[c]++;
1416                                         }
1417
1418                                         // reset them for the next loop
1419                                         group_values[c] = 0;
1420                                         found_non_existing[c] = 0;
1421                                 }
1422
1423                                 // if all dimensions are hidden, print a null
1424                                 if(!pc) {
1425                                         buffer_strcat(wb, pre_value);
1426                                         buffer_strcat(wb, "null");
1427                                         buffer_strcat(wb, post_value);
1428                                 }
1429
1430                                 printed++;
1431                                 group_count = 0;
1432                         }
1433                 }
1434
1435                 if(printed) buffer_strcat(wb, "]}");
1436                 buffer_strcat(wb, "\n   ]\n}\n");
1437
1438                 if(only_non_zero && max_loop > 1) {
1439                         int changed = 0;
1440                         for(rd = st->dimensions, c = 0 ; rd && c < dimensions ; rd = rd->next, c++) {
1441                                 group_values[c] = 0;
1442                                 found_non_existing[c] = 0;
1443
1444                                 if(!print_hidden[c] && !found_non_zero[c]) {
1445                                         changed = 1;
1446                                         print_hidden[c] = 1;
1447                                 }
1448                         }
1449
1450                         if(changed) buffer_flush(wb);
1451                         else break;
1452                 }
1453                 else break;
1454
1455         } // max_loop
1456
1457         debug(D_RRD_STATS, "RRD_STATS_JSON: %s total %ld bytes", st->name, wb->len);
1458
1459         pthread_rwlock_unlock(&st->rwlock);
1460         return last_timestamp;
1461 }