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