moved output generation for xport out of rrd_tool.c -- martin sperl
[rrdtool.git] / src / rrd_xport.c
1 /****************************************************************************
2  * RRDtool 1.4.3  Copyright by Tobi Oetiker, 1997-2010
3  ****************************************************************************
4  * rrd_xport.c  export RRD data 
5  ****************************************************************************/
6
7 #include <sys/stat.h>
8 #include <locale.h>
9
10 #include "rrd_tool.h"
11 #include "rrd_graph.h"
12 #include "rrd_xport.h"
13 #include "unused.h"
14 #include "rrd_client.h"
15
16 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
17 #include <io.h>
18 #include <fcntl.h>
19 #endif
20
21 int       rrd_xport(
22     int,
23     char **,
24     int *,
25     time_t *,
26     time_t *,
27     unsigned long *,
28     unsigned long *,
29     char ***,
30     rrd_value_t **);
31
32 int       rrd_xport_fn(
33     image_desc_t *,
34     time_t *,
35     time_t *,
36     unsigned long *,
37     unsigned long *,
38     char ***,
39     rrd_value_t **,
40     int);
41
42 /* helper function for buffer handling */
43 typedef struct stringbuffer_t {
44   size_t allocated;
45   size_t len;
46   unsigned char* data;
47   FILE *file;
48 } stringbuffer_t;
49 int addToBuffer(stringbuffer_t *,char*,size_t);
50 void escapeJSON(char*,size_t);
51
52 int rrd_graph_xport(image_desc_t *);
53 int rrd_xport_format_xmljson(int,stringbuffer_t *,image_desc_t*,time_t, time_t, unsigned long, unsigned long, char**, rrd_value_t*);
54 int rrd_xport_format_sv(char,stringbuffer_t *,image_desc_t*,time_t, time_t, unsigned long, unsigned long, char**, rrd_value_t*);
55 int rrd_xport_format_addprints(int,stringbuffer_t *,image_desc_t *);
56
57 int rrd_xport(
58     int argc,
59     char **argv,
60     int UNUSED(*xsize),
61     time_t *start,
62     time_t *end,        /* which time frame do you want ?
63                          * will be changed to represent reality */
64     unsigned long *step,    /* which stepsize do you want? 
65                              * will be changed to represent reality */
66     unsigned long *col_cnt, /* number of data columns in the result */
67     char ***legend_v,   /* legend entries */
68     rrd_value_t **data)
69 {                       /* two dimensional array containing the data */
70     image_desc_t im;
71     time_t    start_tmp = 0, end_tmp = 0;
72     rrd_time_value_t start_tv, end_tv;
73     char     *parsetime_error = NULL;
74
75     struct option long_options[] = {
76         {"start", required_argument, 0, 's'},
77         {"end", required_argument, 0, 'e'},
78         {"maxrows", required_argument, 0, 'm'},
79         {"step", required_argument, 0, 261},
80         {"enumds", no_argument, 0, 262},    /* these are handled in the frontend ... */
81         {"json", no_argument, 0, 263},    /* these are handled in the frontend ... */
82         {"daemon", required_argument, 0, 'd'},
83         {0, 0, 0, 0}
84     };
85
86     optind = 0;
87     opterr = 0;         /* initialize getopt */
88
89     rrd_graph_init(&im);
90
91     rrd_parsetime("end-24h", &start_tv);
92     rrd_parsetime("now", &end_tv);
93
94     int enumds=0;
95     int json=0;
96
97     while (1) {
98         int       option_index = 0;
99         int       opt;
100
101         opt = getopt_long(argc, argv, "s:e:m:d:", long_options, &option_index);
102
103         if (opt == EOF)
104             break;
105
106         switch (opt) {
107         case 261:
108             im.step = atoi(optarg);
109             break;
110         case 262:
111             enumds=1;
112             break;
113         case 263:
114             json=1;
115             break;
116         case 's':
117             if ((parsetime_error = rrd_parsetime(optarg, &start_tv))) {
118                 rrd_set_error("start time: %s", parsetime_error);
119                 return -1;
120             }
121             break;
122         case 'e':
123             if ((parsetime_error = rrd_parsetime(optarg, &end_tv))) {
124                 rrd_set_error("end time: %s", parsetime_error);
125                 return -1;
126             }
127             break;
128         case 'm':
129             im.xsize = atol(optarg);
130             if (im.xsize < 10) {
131                 rrd_set_error("maxrows below 10 rows");
132                 return -1;
133             }
134             break;
135         case 'd':
136         {
137             if (im.daemon_addr != NULL)
138             {
139                 rrd_set_error ("You cannot specify --daemon "
140                         "more than once.");
141                 return (-1);
142             }
143
144             im.daemon_addr = strdup(optarg);
145             if (im.daemon_addr == NULL)
146             {
147                 rrd_set_error("strdup error");
148                 return -1;
149             }
150             break;
151         }
152
153         case '?':
154             rrd_set_error("unknown option '%s'", argv[optind - 1]);
155             return -1;
156         }
157     }
158
159     if (rrd_proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
160         return -1;
161     }
162
163     if (start_tmp < 3600 * 24 * 365 * 10) {
164         rrd_set_error("the first entry to fetch should be after 1980 (%ld)",
165                       start_tmp);
166         return -1;
167     }
168
169     if (end_tmp < start_tmp) {
170         rrd_set_error("start (%ld) should be less than end (%ld)",
171                       start_tmp, end_tmp);
172         return -1;
173     }
174
175     im.start = start_tmp;
176     im.end = end_tmp;
177     im.step = max((long) im.step, (im.end - im.start) / im.xsize);
178
179     rrd_graph_script(argc, argv, &im, 0);
180     if (rrd_test_error()) {
181         im_free(&im);
182         return -1;
183     }
184
185     if (im.gdes_c == 0) {
186         rrd_set_error("can't make an xport without contents");
187         im_free(&im);
188         return (-1);
189     }
190
191     {   /* try to connect to rrdcached */
192         int status = rrdc_connect(im.daemon_addr);
193         if (status != 0) return status;
194     }
195
196     if (rrd_xport_fn(&im, start, end, step, col_cnt, legend_v, data,0) == -1) {
197         im_free(&im);
198         return -1;
199     }
200
201     /* and create the export */
202     if (!xsize) {
203       int flags=0;
204       if (json) { flags|=1; }
205       if (enumds) { flags|=4; }
206       stringbuffer_t buffer={0,0,NULL,stdout};
207       rrd_xport_format_xmljson(flags,&buffer,&im, 
208                                *start, *end, *step,
209                                *col_cnt, *legend_v,
210                                *data);
211     }
212
213     im_free(&im);
214     return 0;
215 }
216
217
218
219 int rrd_xport_fn(
220     image_desc_t *im,
221     time_t *start,
222     time_t *end,        /* which time frame do you want ?
223                          * will be changed to represent reality */
224     unsigned long *step,    /* which stepsize do you want? 
225                              * will be changed to represent reality */
226     unsigned long *col_cnt, /* number of data columns in the result */
227     char ***legend_v,   /* legend entries */
228     rrd_value_t **data,
229     int dolines)
230 {                       /* two dimensional array containing the data */
231
232     int       i = 0, j = 0;
233     unsigned long dst_row, row_cnt;
234     rrd_value_t  *dstptr;
235
236     unsigned long xport_counter = 0;
237     int      *ref_list;
238     long     *step_list;
239     long     *step_list_ptr;    
240     char    **legend_list;
241
242
243     /* pull the data from the rrd files ... */
244     if (data_fetch(im) == -1)
245         return -1;
246
247     /* evaluate CDEF  operations ... */
248     if (data_calc(im) == -1)
249         return -1;
250
251     /* how many xports or lines/AREA/STACK ? */
252     *col_cnt = 0;
253     for (i = 0; i < im->gdes_c; i++) {
254         switch (im->gdes[i].gf) {
255         case GF_LINE:
256         case GF_AREA:
257         case GF_STACK:
258           (*col_cnt)+=dolines;
259           break;
260         case GF_XPORT:
261           (*col_cnt)++;
262             break;
263         default:
264             break;
265         }
266     }
267     if ((*col_cnt) == 0) {
268         rrd_set_error("no XPORT found, nothing to do");
269         return -1;
270     }
271
272     /* a list of referenced gdes */
273     ref_list = (int*)malloc(sizeof(int) * (*col_cnt));
274     if (ref_list == NULL)
275         return -1;
276
277     /* a list to save pointers to the column's legend entry */
278     /* this is a return value! */
279     legend_list = (char**)malloc(sizeof(char *) * (*col_cnt));
280     if (legend_list == NULL) {
281         free(ref_list);
282         return -1;
283     }
284
285     /* lets find the step size we have to use for xport */
286     step_list = (long*)malloc(sizeof(long)*((*col_cnt)+1));
287     step_list_ptr = step_list;
288     j = 0;
289     for (i = 0; i < im->gdes_c; i++) {
290       /* decide if we need to handle the output */
291         int handle=0;
292         switch (im->gdes[i].gf) {
293         case GF_LINE:
294         case GF_AREA:
295         case GF_STACK:
296           handle=dolines;
297           break;
298         case GF_XPORT:
299           handle=1;
300           break;
301         default:
302           handle=0;
303           break;
304         }
305         /* and now do the real work */
306         if (handle) {
307             ref_list[xport_counter++] = i;
308             *step_list_ptr = im->gdes[im->gdes[i].vidx].step;
309             /* printf("%s:%lu\n",im->gdes[i].legend,*step_list_ptr); */
310             step_list_ptr++;
311             /* reserve room for one legend entry */
312             /* is FMT_LEG_LEN + 5 the correct size? */
313             if ((legend_list[j] =
314                 (char*)malloc(sizeof(char) * (FMT_LEG_LEN + 5))) == NULL) {
315                 free(ref_list);
316                 *data = NULL;
317                 while (--j > -1)
318                     free(legend_list[j]);
319                 free(legend_list);
320                 free(step_list);
321                 rrd_set_error("malloc xport legend entry");
322                 return (-1);
323             }
324
325             if (im->gdes[i].legend)
326                 /* omit bounds check, should have the same size */
327                 strcpy(legend_list[j++], im->gdes[i].legend);
328             else
329                 legend_list[j++][0] = '\0';
330         }
331     }
332     *step_list_ptr=0;    
333     /* find a common step */
334     *step = lcd(step_list);
335     /* printf("step: %lu\n",*step); */
336     free(step_list);
337     
338     *start =  im->start - im->start % (*step);
339     *end = im->end - im->end % (*step) + (*step);
340     
341
342     /* room for rearranged data */
343     /* this is a return value! */
344     row_cnt = ((*end) - (*start)) / (*step);
345     if (((*data) =
346         (rrd_value_t*)malloc((*col_cnt) * row_cnt * sizeof(rrd_value_t))) == NULL) {
347         free(ref_list);
348         free(legend_list);
349         rrd_set_error("malloc xport data area");
350         return (-1);
351     }
352     dstptr = (*data);
353
354     /* fill data structure */
355     for (dst_row = 0; (int) dst_row < (int) row_cnt; dst_row++) {
356         for (i = 0; i < (int) (*col_cnt); i++) {
357             long vidx = im->gdes[ref_list[i]].vidx;
358             time_t now = *start + dst_row * *step;
359             (*dstptr++) = im->gdes[vidx].data[(unsigned long)
360                                               floor((double)
361                                                     (now - im->gdes[vidx].start)
362                                                     /im->gdes[vidx].step)
363                                               * im->gdes[vidx].ds_cnt +
364                                               im->gdes[vidx].ds];
365
366         }
367     }
368
369     *legend_v = legend_list;
370     free(ref_list);
371     return 0;
372
373 }
374
375 int rrd_graph_xport(image_desc_t *im) {
376   /* prepare the data for processing */
377   unsigned long col_cnt=0;
378   time_t start=im->start;
379   time_t end=im->end;
380   unsigned long step=im->step;
381   char **legend_v=NULL;
382   rrd_value_t *data=NULL;
383   /* initialize buffer */
384   stringbuffer_t buffer={0,0,NULL,NULL}; 
385   /* if we write a file, then open it */
386   if (strlen(im->graphfile)) {
387     buffer.file=fopen(im->graphfile,"w");
388   }
389
390   /* do the data processing */
391   if (rrd_xport_fn(im,&start,&end,&step,&col_cnt,&legend_v,&data,1)) { return -1;}
392
393   /* fill in some data */
394   rrd_infoval_t info;
395   info.u_cnt = start;
396   grinfo_push(im, sprintf_alloc("graph_start"), RD_I_CNT, info);
397   info.u_cnt = end;
398   grinfo_push(im, sprintf_alloc("graph_end"), RD_I_CNT, info);
399   info.u_cnt = step;
400   grinfo_push(im, sprintf_alloc("graph_step"), RD_I_CNT, info);
401
402   /* set locale */
403   char *old_locale = setlocale(LC_NUMERIC,NULL);
404   setlocale(LC_NUMERIC, "C");
405
406   /* format it for output */
407   int r=0;
408   switch(im->imgformat) {
409   case IF_XML:
410     r=rrd_xport_format_xmljson(2,&buffer,im, start, end, step, col_cnt, legend_v, data);
411     break;
412   case IF_XMLENUM:
413     r=rrd_xport_format_xmljson(6,&buffer,im, start, end, step, col_cnt, legend_v, data);
414     break;
415   case IF_JSON:
416     r=rrd_xport_format_xmljson(1,&buffer,im, start, end, step, col_cnt, legend_v, data);
417     break;
418   case IF_JSONTIME:
419     r=rrd_xport_format_xmljson(3,&buffer,im, start, end, step, col_cnt, legend_v, data);
420     break;
421   case IF_CSV:
422     r=rrd_xport_format_sv(',',&buffer,im, start, end, step, col_cnt, legend_v, data);
423     break;
424   case IF_TSV:
425     r=rrd_xport_format_sv('\t',&buffer,im, start, end, step, col_cnt, legend_v, data);
426     break;
427   case IF_SSV:
428     r=rrd_xport_format_sv(';',&buffer,im, start, end, step, col_cnt, legend_v, data);
429     break;
430   default:
431     break;
432   }
433   /* restore locale */
434   setlocale(LC_NUMERIC, old_locale);
435   /* handle errors */
436   if (r) {
437     /* free legend */
438     for (unsigned long j = 0; j < col_cnt; j++) {
439       free(legend_v[j]);
440     }
441     free(legend_v);
442     /* free data */
443     free(data);
444     /* free the bufer */
445     if (buffer.data) {free(buffer.data);}
446     /* close the file */
447     if (buffer.file) {fclose(buffer.file);}
448     /* and return with error */
449     return r;
450   }
451
452   /* now do the cleanup */
453   if (buffer.file) {
454     fclose(buffer.file); buffer.file=NULL; 
455     im->rendered_image_size=0;
456     im->rendered_image=NULL;
457   } else {
458     im->rendered_image_size=buffer.len;
459     im->rendered_image=buffer.data;    
460   }
461
462   /* and print stuff */
463   return print_calc(im);
464 }
465
466 int addToBuffer(stringbuffer_t * sb,char* data,size_t len) {
467   /* if len <= 0  we assume a string and calculate the length ourself */
468   if (len<=0) { len=strlen(data); }
469   /* if we have got a file, then take the shortcut */
470   if (sb->file) { 
471     sb->len+=len;
472     fwrite(data,len,1,sb->file); 
473     return 0; 
474   }
475   /* if buffer is 0, then initialize */
476   if (! sb->data) { 
477     /* make buffer a multiple of 8192 */
478     sb->allocated+=8192;
479     sb->allocated-=(sb->allocated%8192);    
480     /* and allocate it */
481     sb->data=malloc(sb->allocated); 
482     if (! sb->data) { 
483       rrd_set_error("malloc issue");
484       return 1;
485     }
486     /* and initialize the buffer */
487     sb->len=0;
488     sb->data[0]=0;
489   }
490   /* and figure out if we need to extend the buffer */
491   if (sb->len+len+1>=sb->allocated) {
492     /* add so many pages until we have a buffer big enough */
493     while(sb->len+len+1>=sb->allocated) {
494       sb->allocated+=8192;
495     }
496     /* try to resize it */
497     unsigned char* resized=(unsigned char*)realloc(sb->data,sb->allocated);
498     if (resized) {
499       sb->data=resized;
500     } else {
501       free(sb->data);
502       sb->data=NULL;
503       sb->allocated=0;
504       rrd_set_error("realloc issue");
505       return -1;
506     }
507   }
508   /* and finally add to the buffer */
509   memcpy(sb->data+sb->len,data,len);
510   sb->len+=len;
511   /* and 0 terminate it */
512   sb->data[sb->len]=0;
513   /* and return */
514   return 0;
515 }
516
517 int rrd_xport_format_sv(char sep, stringbuffer_t *buffer,image_desc_t *im,time_t start, time_t end, unsigned long step, unsigned long col_cnt, char **legend_v, rrd_value_t* data) {
518   /* define the time format */
519   char* timefmt=NULL;
520   if (im->xlab_user.minsec!=-1) { timefmt=im->xlab_user.stst; }
521
522   /* row count */
523   unsigned long row_cnt=(end-start)/step;
524
525   /* estimate buffer size (to avoid multiple allocations) */
526   buffer->allocated=
527     1024 /* bytes of overhead /header/footer */
528     +(12+19*col_cnt) /* 12 bytes overhead/line plus 19 bytes per column*/
529     *(1+row_cnt) /* number of columns + 1 (for header) */
530     ;
531
532   char buf[256];
533
534   /* now start writing the header*/
535   if (addToBuffer(buffer,"\"time\"",6)) { return 1; }
536   for(unsigned long i=0;i<col_cnt;i++) {
537     /* strip leading spaces */
538     char *t=legend_v[i]; while (isspace(*t)) { t++;}
539     /* and print it */
540     snprintf(buf,255,"%c\"%s\"",sep,t);
541     if (addToBuffer(buffer,buf,0)) { return 1;}
542   }
543   if (addToBuffer(buffer,"\r\n",2)) { return 1; }
544   /* and now write the data */
545   rrd_value_t *ptr=data;
546   for(time_t ti=start+step;ti<end;ti+=step) {
547     /* write time */
548     if (timefmt) {
549       struct tm loc;
550       localtime_r(&ti,&loc);
551       strftime(buf,254,timefmt,&loc);
552     } else {
553       snprintf(buf,254,"%lld",(long long int)ti);
554     }
555     if (addToBuffer(buffer,buf,0)) { return 1; }
556     /* write the columns */
557     for(unsigned long i=0;i<col_cnt;i++) {
558       /* get the value */
559       rrd_value_t v=*ptr;ptr++;
560       /* and print it */
561       if (isnan(v)) {
562         snprintf(buf,255,"%c\"NaN\"",sep);
563       } else {
564         snprintf(buf,255,"%c\"%0.10e\"",sep,v);
565       }
566       if (addToBuffer(buffer,buf,0)) { return 1;}
567     }
568     /* and add a newline */
569     if (addToBuffer(buffer,"\r\n",2)) { return 1; }
570   }
571
572   /* and return OK */
573   return 0;
574 }
575
576 int rrd_xport_format_xmljson(int flags,stringbuffer_t *buffer,image_desc_t *im,time_t start, time_t end, unsigned long step, unsigned long col_cnt, char **legend_v, rrd_value_t* data) {
577
578   /* define some other stuff based on flags */
579   int json=0;
580   if (flags &1) { json=1; }
581   int showtime=0;
582   if (flags &2) { showtime=1;}
583   int enumds=0;
584   if (flags &4) { enumds=1;}
585
586   /* define the time format */
587   char* timefmt=NULL;
588   /* unfortunatley we have to do it this way, 
589      as when no --x-graph argument is given,
590      then the xlab_user is not in a clean state (e.g. zero-filled) */
591   if (im->xlab_user.minsec!=-1) { timefmt=im->xlab_user.stst; }
592
593   /* row count */
594   unsigned long row_cnt=(end-start)/step;
595
596   /* estimate buffer size (to avoid multiple allocations) */
597   /* better estimates are needed here */
598   buffer->allocated=
599     1024 /* bytes of overhead /header/footer */
600     +(12+19*col_cnt) /* 12 bytes overhead/line plus 19 bytes per column*/
601     *(1+row_cnt) /* number of columns + 1 (for header) */
602     ;
603   char buf[256];
604   char dbuf[1024];
605
606   rrd_value_t *ptr = data;
607   if (json == 0){
608     snprintf(buf,sizeof(buf),
609              "<?xml version=\"1.0\" encoding=\"%s\"?>\n\n<%s>\n  <%s>\n",
610              XML_ENCODING,ROOT_TAG,META_TAG);
611     addToBuffer(buffer,buf,0);
612   }
613   else {
614     addToBuffer(buffer,"{ \"about\": \"RRDtool graph JSON output\",\n  \"meta\": {\n",0);
615   }
616   
617   /* calculate start time */
618   if (timefmt) {
619     struct tm loc;
620     time_t ti=start+step;
621     localtime_r(&ti,&loc);
622     strftime(dbuf,sizeof(dbuf),timefmt,&loc);
623     if (json) {
624       snprintf(buf,sizeof(buf),"    \"%s\": \"%s\",\n",META_START_TAG,dbuf);
625     } else {
626       snprintf(buf,sizeof(buf),"    <%s>%s</%s>\n",META_START_TAG,dbuf,META_START_TAG);
627     }
628   } else {
629     if (json) {
630       snprintf(buf,sizeof(buf),"    \"%s\": %lld,\n",META_START_TAG,(long long int)start+step);
631     } else {
632       snprintf(buf,sizeof(buf),"    <%s>%lld</%s>\n",META_START_TAG,(long long int)start+step,META_START_TAG);
633     }
634   }
635   addToBuffer(buffer,buf,0);
636
637   /* calculate end time */
638   if (timefmt) {
639     struct tm loc;
640     time_t ti=end;
641     localtime_r(&ti,&loc);
642     strftime(dbuf,sizeof(dbuf),timefmt,&loc);
643     if (json) {
644       snprintf(buf,sizeof(buf),"    \"%s\": \"%s\",\n",META_END_TAG,dbuf);
645     } else {
646       snprintf(buf,sizeof(buf),"    <%s>%s</%s>\n",META_END_TAG,dbuf,META_END_TAG);
647     }
648   } else {
649     if (json) {
650       snprintf(buf,sizeof(buf),"    \"%s\": %lld,\n",META_END_TAG,(long long int)end);
651     } else {
652       snprintf(buf,sizeof(buf),"    <%s>%lld</%s>\n",META_END_TAG,(long long int)end,META_END_TAG);
653     }
654   }
655   addToBuffer(buffer,buf,0);
656   /* print other info */
657   if (json) {
658     snprintf(buf,sizeof(buf),"    \"%s\": %lld,\n",META_STEP_TAG,(long long int)step);
659     addToBuffer(buffer,buf,0);
660   } else {
661     snprintf(buf,sizeof(buf),"    <%s>%lld</%s>\n",META_STEP_TAG,(long long int)step,META_STEP_TAG); 
662     addToBuffer(buffer,buf,0);
663     snprintf(buf,sizeof(buf),"    <%s>%lu</%s>\n",META_ROWS_TAG,row_cnt,META_ROWS_TAG); 
664     addToBuffer(buffer,buf,0);
665     snprintf(buf,sizeof(buf),"    <%s>%lu</%s>\n",META_COLS_TAG,col_cnt,META_COLS_TAG); 
666     addToBuffer(buffer,buf,0);
667   }
668   
669   /* start legend */
670   if (json){
671     snprintf(buf,sizeof(buf),"    \"%s\": [\n", LEGEND_TAG);
672   }
673   else {
674     snprintf(buf,sizeof(buf),"    <%s>\n", LEGEND_TAG);
675   }
676   addToBuffer(buffer,buf,0);
677   /* add legend entries */
678   for (unsigned long j = 0; j < col_cnt; j++) {
679     char *entry = legend_v[j];
680     /* I do not know why the legend is "spaced", but let us skip it */
681     while(isspace(*entry)){entry++;}
682     /* now output it */
683     if (json){
684       snprintf(buf,sizeof(buf),"      \"%s\"", entry);
685       addToBuffer(buffer,buf,0);
686       if (j < col_cnt -1){
687         addToBuffer(buffer,",",1);
688       }
689       addToBuffer(buffer,"\n",1);
690     }
691     else {
692       snprintf(buf,sizeof(buf),"      <%s>%s</%s>\n", LEGEND_ENTRY_TAG, entry,LEGEND_ENTRY_TAG);
693       addToBuffer(buffer,buf,0);
694     }
695   }
696   /* end legend */
697   if (json){
698     snprintf(buf,sizeof(buf),"          ],\n");
699   }
700   else {
701     snprintf(buf,sizeof(buf),"    </%s>\n", LEGEND_TAG);
702   }
703   addToBuffer(buffer,buf,0);
704   
705   /* add graphs and prints */
706   if (rrd_xport_format_addprints(json,buffer,im)) {return -1;}
707
708   /* if we have got a trailing , then kill it */
709   if (buffer->data) {
710     if (buffer->data[buffer->len-2]==',') { 
711       buffer->data[buffer->len-2]=buffer->data[buffer->len-1];
712       buffer->len--;
713     }
714   }
715
716   /* end meta */
717   if (json){
718     snprintf(buf,sizeof(buf),"     },\n");
719   } else {
720     snprintf(buf,sizeof(buf),"  </%s>\n", META_TAG);
721   }
722   addToBuffer(buffer,buf,0);
723
724   
725   /* start data */
726   if (json){
727     snprintf(buf,sizeof(buf),"  \"%s\": [\n",DATA_TAG);
728   } else {
729     snprintf(buf,sizeof(buf),"  <%s>\n", DATA_TAG);
730   }
731   addToBuffer(buffer,buf,0);
732   /* iterate over data */
733   for (time_t ti = start + step; ti <= end; ti += step) {
734     if (timefmt) {
735       struct tm loc;
736       localtime_r(&ti,&loc);
737       strftime(dbuf,sizeof(dbuf),timefmt,&loc);
738     } else {
739       snprintf(dbuf,sizeof(dbuf),"%lld",(long long int)ti);
740     }
741     if (json){
742       addToBuffer(buffer,"    [ ",0);
743       if(showtime){
744         addToBuffer(buffer,"\"",1);
745         addToBuffer(buffer,dbuf,0);
746         addToBuffer(buffer,"\",",2);
747       }
748     }
749     else {
750       if (showtime) {
751         snprintf(buf,sizeof(buf),
752                  "    <%s><%s>%s</%s>", DATA_ROW_TAG,COL_TIME_TAG, dbuf, COL_TIME_TAG);
753       } else {
754         snprintf(buf,sizeof(buf),
755                  "    <%s>", DATA_ROW_TAG);
756       }
757       addToBuffer(buffer,buf,0);
758     }
759     for (unsigned long j = 0; j < col_cnt; j++) {
760       rrd_value_t newval = DNAN;
761       newval = *ptr;
762       if (json){
763         if (isnan(newval)){
764           addToBuffer(buffer,"null",0);                        
765         } else {
766           snprintf(buf,sizeof(buf),"%0.10e",newval);
767           addToBuffer(buffer,buf,0);
768         }
769         if (j < col_cnt -1){
770           addToBuffer(buffer,", ",0);
771         }
772       }
773       else {
774         if (isnan(newval)) {
775           if (enumds) {
776             snprintf(buf,sizeof(buf),"<%s%lu>NaN</%s%lu>", COL_DATA_TAG,j,COL_DATA_TAG,j);
777           } else {
778             snprintf(buf,sizeof(buf),"<%s>NaN</%s>", COL_DATA_TAG,COL_DATA_TAG);
779           }
780         } else {
781           if (enumds) {
782             snprintf(buf,sizeof(buf),"<%s%lu>%0.10e</%s%lu>", COL_DATA_TAG,j,newval,COL_DATA_TAG,j);
783           } else {
784             snprintf(buf,sizeof(buf),"<%s>%0.10e</%s>", COL_DATA_TAG,newval,COL_DATA_TAG);
785           }
786         }
787         addToBuffer(buffer,buf,0);
788       }
789       ptr++;
790     }                
791     if (json){
792       addToBuffer(buffer,(ti < end ? " ],\n" : " ]\n"),0);
793     }
794     else {                
795       snprintf(buf,sizeof(buf),"</%s>\n", DATA_ROW_TAG);
796       addToBuffer(buffer,buf,0);
797     }
798   }
799   /* end data */
800   if (json){
801     addToBuffer(buffer,"  ]\n",0);
802   }
803   else {
804     snprintf(buf,sizeof(buf),"  </%s>\n",DATA_TAG);
805     addToBuffer(buffer,buf,0);
806   }
807
808   /* end all */
809   if (json){
810     addToBuffer(buffer,"}\n",0);
811   } else {
812     snprintf(buf,sizeof(buf),"</%s>\n", ROOT_TAG);
813     addToBuffer(buffer,buf,0);
814   }
815   return 0;
816 }
817
818 void escapeJSON(char* txt,size_t len) {
819   char *tmp=(char*)malloc(len+2);
820   size_t l=strlen(txt);
821   size_t pos=0;
822   /* now iterate over the chars */
823   for(size_t i=0;(i<l)&&(pos<len);i++,pos++) {
824     switch (txt[i]) {
825       case '"':
826       case '\\':
827         tmp[pos]='\\';pos++;
828         tmp[pos]=txt[i];
829         break;
830     default:
831       tmp[pos]=txt[i];
832       break;
833     }
834   }
835   /* 0 terminate it */
836   tmp[pos]=0;
837   /* and copy back over txt */
838   strncpy(txt,tmp,len);
839   /* and release tmp */
840   free(tmp);
841 }
842
843 int rrd_xport_format_addprints(int flags,stringbuffer_t *buffer,image_desc_t *im) {
844   /* initialize buffer */
845   stringbuffer_t prints={1024,0,NULL,NULL}; 
846   stringbuffer_t rules={1024,0,NULL,NULL}; 
847   stringbuffer_t gprints={4096,0,NULL,NULL}; 
848   char buf[256];
849   char dbuf[1024];
850   char* val;
851   char* timefmt=NULL;
852   if (im->xlab_user.minsec!=-1) { timefmt=im->xlab_user.stst; }
853
854   /* define some other stuff based on flags */
855   int json=0;
856   if (flags &1) { json=1; }
857   int showtime=0;
858   if (flags &2) { showtime=1;}
859   int enumds=0;
860   if (flags &4) { enumds=1;}
861
862   /* define some values */
863   time_t    now = time(NULL);
864   struct tm tmvdef;
865   localtime_r(&now, &tmvdef);
866   double printval=DNAN;
867
868   /* iterate over all fields and start the work writing to the correct buffers */
869   for (long i = 0; i < im->gdes_c; i++) {
870     long vidx = im->gdes[i].vidx;
871     char* entry;
872     switch (im->gdes[i].gf) {
873     case GF_PRINT:
874     case GF_GPRINT:
875       /* PRINT and GPRINT can now print VDEF generated values.
876        * There's no need to do any calculations on them as these
877        * calculations were already made.
878        * we do not support the depreciated version here
879        */
880       printval=DNAN;
881       /* decide to which buffer we print to*/
882       stringbuffer_t *usebuffer=&gprints;
883       char* usetag="gprint";
884       if (im->gdes[i].gf==GF_PRINT) { 
885         usebuffer=&prints;
886         usetag="print";
887       }
888       /* get the value */
889       if (im->gdes[vidx].gf == GF_VDEF) { /* simply use vals */
890         printval = im->gdes[vidx].vf.val;
891         localtime_r(&im->gdes[vidx].vf.when, &tmvdef);
892       } else {
893         int max_ii = ((im->gdes[vidx].end - im->gdes[vidx].start)
894                       / im->gdes[vidx].step * im->gdes[vidx].ds_cnt);
895         printval = DNAN;
896         long validsteps = 0;
897         for (long ii = im->gdes[vidx].ds;
898              ii < max_ii; ii += im->gdes[vidx].ds_cnt) {
899           if (!finite(im->gdes[vidx].data[ii]))
900             continue;
901           if (isnan(printval)) {
902             printval = im->gdes[vidx].data[ii];
903             validsteps++;
904             continue;
905           }
906           
907           switch (im->gdes[i].cf) {
908           case CF_HWPREDICT:
909           case CF_MHWPREDICT:
910           case CF_DEVPREDICT:
911           case CF_DEVSEASONAL:
912           case CF_SEASONAL:
913           case CF_AVERAGE:
914             validsteps++;
915             printval += im->gdes[vidx].data[ii];
916             break;
917           case CF_MINIMUM:
918             printval = min(printval, im->gdes[vidx].data[ii]);
919             break;
920           case CF_FAILURES:
921           case CF_MAXIMUM:
922             printval = max(printval, im->gdes[vidx].data[ii]);
923             break;
924           case CF_LAST:
925             printval = im->gdes[vidx].data[ii];
926           }
927         }
928         if (im->gdes[i].cf == CF_AVERAGE || im->gdes[i].cf > CF_LAST) {
929           if (validsteps > 1) {
930             printval = (printval / validsteps);
931           }
932         }
933       }
934       /* we handle PRINT and GPRINT the same - format now*/
935       if (im->gdes[i].strftm) {
936         if (im->gdes[vidx].vf.never == 1) {
937           time_clean(buf, im->gdes[i].format);
938         } else {
939           strftime(dbuf,sizeof(dbuf), im->gdes[i].format, &tmvdef);
940         }
941       } else if (bad_format(im->gdes[i].format)) {
942         rrd_set_error
943           ("bad format for PRINT in \"%s'", im->gdes[i].format);
944         return -1;
945       } else {
946         snprintf(dbuf,sizeof(dbuf), im->gdes[i].format, printval,"");
947       }
948       /* print */
949       if (json) {
950         escapeJSON(dbuf,sizeof(dbuf));
951         snprintf(buf,sizeof(buf),",\n        { \"%s\": \"%s\" }",usetag,dbuf);
952       } else {
953         snprintf(buf,sizeof(buf),"        <%s>%s</%s>\n",usetag,dbuf,usetag);
954       }
955       addToBuffer(usebuffer,buf,0);
956       break;
957     case GF_COMMENT:
958       if (json) {
959         strncpy(dbuf,im->gdes[i].legend,sizeof(dbuf));
960         escapeJSON(dbuf,sizeof(dbuf));
961         snprintf(buf,sizeof(buf),",\n        { \"comment\": \"%s\" }",dbuf);
962       } else {
963         snprintf(buf,sizeof(buf),"        <comment>%s</comment>\n",im->gdes[i].legend);
964       }
965       addToBuffer(&gprints,buf,0);
966       break;
967     case GF_LINE:
968       entry = im->gdes[i].legend;
969       /* I do not know why the legend is "spaced", but let us skip it */
970       while(isspace(*entry)){entry++;}
971       if (json) {
972         snprintf(buf,sizeof(buf),",\n        { \"line\": \"%s\" }",entry);
973       } else {
974         snprintf(buf,sizeof(buf),"        <line>%s</line>\n",entry);
975       }
976       addToBuffer(&gprints,buf,0);
977       break;
978     case GF_AREA:
979       if (json) {
980         snprintf(buf,sizeof(buf),",\n        { \"area\": \"%s\" }",im->gdes[i].legend);
981       } else {
982         snprintf(buf,sizeof(buf),"        <area>%s</area>\n",im->gdes[i].legend);
983       }
984       addToBuffer(&gprints,buf,0);
985       break;
986     case GF_STACK:
987       if (json) {
988         snprintf(buf,sizeof(buf),",\n        { \"stack\": \"%s\" }",im->gdes[i].legend);
989       } else {
990         snprintf(buf,sizeof(buf),"        <stack>%s</stack>\n",im->gdes[i].legend);
991       }
992       addToBuffer(&gprints,buf,0);
993       break;
994     case GF_TEXTALIGN:
995       val="";
996       switch (im->gdes[i].txtalign) {
997       case TXA_LEFT: val="left"; break;
998       case TXA_RIGHT: val="right"; break;
999       case TXA_CENTER: val="center"; break;
1000       case TXA_JUSTIFIED: val="justified"; break;
1001       }
1002       if (json) {
1003         snprintf(buf,sizeof(buf),",\n        { \"align\": \"%s\" }",val);
1004       } else {
1005         snprintf(buf,sizeof(buf),"        <align>%s</align>\n",val);
1006       }
1007       addToBuffer(&gprints,buf,0);
1008       break;
1009     case GF_HRULE:
1010       /* This does not work as expected - Tobi please help!!! */
1011       snprintf(dbuf,sizeof(dbuf),"%0.10e",im->gdes[i].vf.val);
1012       /* and output it */
1013       if (json) {
1014         snprintf(buf,sizeof(buf),",\n        { \"hrule\": \"%s\" }",dbuf);
1015       } else {
1016         snprintf(buf,sizeof(buf),"        <hrule>%s</hrule>\n",dbuf);
1017       }
1018       addToBuffer(&rules,buf,0);
1019       break;
1020     case GF_VRULE:
1021       if (timefmt) {
1022         struct tm loc;
1023         localtime_r(&im->gdes[i].xrule,&loc);
1024         strftime(dbuf,254,timefmt,&loc);
1025       } else {
1026         snprintf(dbuf,254,"%lld",(long long int)im->gdes[i].vf.when);
1027       }
1028       /* and output it */
1029       if (json) {
1030         snprintf(buf,sizeof(buf),",\n        { \"vrule\": \"%s\" }",dbuf);
1031       } else {
1032         snprintf(buf,sizeof(buf),"        <vrule>%s</vrule>\n",dbuf);
1033       }
1034       addToBuffer(&rules,buf,0);
1035       break;
1036     default: 
1037       break;
1038     }
1039   }
1040   /* now add prints */
1041   if (prints.len) {
1042     if (json){
1043       snprintf(buf,sizeof(buf),"    \"%s\": [\n","prints");
1044       addToBuffer(buffer,buf,0);
1045       addToBuffer(buffer,(char*)prints.data+2,prints.len-2);
1046       addToBuffer(buffer,"\n        ],\n",0);
1047     } else {
1048       snprintf(buf,sizeof(buf),"    <%s>\n", "prints");
1049       addToBuffer(buffer,buf,0);
1050       addToBuffer(buffer,(char*)prints.data,prints.len);
1051       snprintf(buf,sizeof(buf),"    </%s>\n", "prints");
1052       addToBuffer(buffer,buf,0);
1053     }
1054     free(prints.data);
1055   }
1056   /* now add gprints */
1057   if (gprints.len) {
1058     if (json){
1059       snprintf(buf,sizeof(buf),"    \"%s\": [\n","gprints");
1060       addToBuffer(buffer,buf,0);
1061       addToBuffer(buffer,(char*)gprints.data+2,gprints.len-2);
1062       addToBuffer(buffer,"\n        ],\n",0);
1063     } else {
1064       snprintf(buf,sizeof(buf),"    <%s>\n", "gprints");
1065       addToBuffer(buffer,buf,0);
1066       addToBuffer(buffer,(char*)gprints.data,gprints.len);
1067       snprintf(buf,sizeof(buf),"    </%s>\n", "gprints");
1068       addToBuffer(buffer,buf,0);
1069     }
1070     free(gprints.data);
1071   }
1072   /* now add rules */
1073   if (rules.len) {
1074     if (json){
1075       snprintf(buf,sizeof(buf),"    \"%s\": [\n","rules");
1076       addToBuffer(buffer,buf,0);
1077       addToBuffer(buffer,(char*)rules.data+2,rules.len-2);
1078       addToBuffer(buffer,"\n        ],\n",0);
1079     } else {
1080       snprintf(buf,sizeof(buf),"    <%s>\n", "rules");
1081       addToBuffer(buffer,buf,0);
1082       addToBuffer(buffer,(char*)rules.data,rules.len);
1083       snprintf(buf,sizeof(buf),"    </%s>\n", "rules");
1084       addToBuffer(buffer,buf,0);
1085     }
1086     free(rules.data);
1087   }
1088   /* and return */
1089   return 0;
1090 }