prepare for the release of rrdtool-1.2.20
[rrdtool.git] / src / rrd_fetch.c
1 /*****************************************************************************
2  * RRDtool 1.2.20  Copyright by Tobi Oetiker, 1997-2007
3  *****************************************************************************
4  * rrd_fetch.c  read date from an rrd to use for further processing
5  *****************************************************************************
6  * $Id$
7  * $Log$
8  * Revision 1.8  2004/05/18 18:53:03  oetiker
9  * big spell checking patch -- slif@bellsouth.net
10  *
11  * Revision 1.7  2003/11/11 19:46:21  oetiker
12  * replaced time_value with rrd_time_value as MacOS X introduced a struct of that name in their standard headers
13  *
14  * Revision 1.6  2003/01/16 23:27:54  oetiker
15  * fix border condition in rra selection of rrd_fetch
16  * -- Stanislav Sinyagin <ssinyagin@yahoo.com>
17  *
18  * Revision 1.5  2002/06/23 22:29:40  alex
19  * Added "step=1800" and such to "DEF"
20  * Cleaned some of the signed vs. unsigned problems
21  *
22  * Revision 1.4  2002/02/01 20:34:49  oetiker
23  * fixed version number and date/time
24  *
25  * Revision 1.3  2001/12/24 06:51:49  alex
26  * A patch of size 44Kbytes... in short:
27  *
28  * Found and repaired the off-by-one error in rrd_fetch_fn().
29  * As a result I had to remove the hacks in rrd_fetch_fn(),
30  * rrd_tool.c, vdef_calc(), data_calc(), data_proc() and
31  * reduce_data().  There may be other places which I didn't
32  * find so be careful.
33  *
34  * Enhanced debugging in rrd_fetch_fn(), it shows the RRA selection
35  * process.
36  *
37  * Added the ability to print VDEF timestamps.  At the moment it
38  * is a hack, I needed it now to fix the off-by-one error.
39  * If the format string is "%c" (and nothing else!), the time
40  * will be printed by both ctime() and as a long int.
41  *
42  * Moved some code around (slightly altering it) from rrd_graph()
43  *   initializing     now in rrd_graph_init()
44  *   options parsing  now in rrd_graph_options()
45  *   script parsing   now in rrd_graph_script()
46  *
47  * Revision 1.2  2001/12/17 12:48:43  oetiker
48  * fix overflow error ...
49  *
50  * Revision 1.1.1.1  2001/02/25 22:25:05  oetiker
51  * checkin
52  *
53  *****************************************************************************/
54
55 #include "rrd_tool.h"
56
57 #include "rrd_is_thread_safe.h"
58 /*#define DEBUG*/
59
60 int
61 rrd_fetch(int argc, 
62           char **argv,
63           time_t         *start,
64           time_t         *end,       /* which time frame do you want ?
65                                       * will be changed to represent reality */
66           unsigned long  *step,      /* which stepsize do you want? 
67                                       * will be changed to represent reality */
68           unsigned long  *ds_cnt,    /* number of data sources in file */
69           char           ***ds_namv,   /* names of data sources */
70           rrd_value_t    **data)     /* two dimensional array containing the data */
71 {
72
73
74     long     step_tmp =1;
75     time_t   start_tmp=0, end_tmp=0;
76     const char *cf;
77
78     struct rrd_time_value start_tv, end_tv;
79     char     *parsetime_error = NULL;
80     optind = 0; opterr = 0;  /* initialize getopt */
81
82     /* init start and end time */
83     parsetime("end-24h", &start_tv);
84     parsetime("now", &end_tv);
85
86     while (1){
87         static struct option long_options[] =
88         {
89             {"resolution",      required_argument, 0, 'r'},
90             {"start",      required_argument, 0, 's'},
91             {"end",      required_argument, 0, 'e'},
92             {0,0,0,0}
93         };
94         int option_index = 0;
95         int opt;
96         opt = getopt_long(argc, argv, "r:s:e:", 
97                           long_options, &option_index);
98
99         if (opt == EOF)
100             break;
101
102         switch(opt) {
103         case 's':
104             if ((parsetime_error = parsetime(optarg, &start_tv))) {
105                 rrd_set_error( "start time: %s", parsetime_error );
106                 return -1;
107             }
108             break;
109         case 'e':
110             if ((parsetime_error = parsetime(optarg, &end_tv))) {
111                 rrd_set_error( "end time: %s", parsetime_error );
112                 return -1;
113             }
114             break;
115         case 'r':
116             step_tmp = atol(optarg);
117             break;
118         case '?':
119             rrd_set_error("unknown option '-%c'",optopt);
120             return(-1);
121         }
122     }
123
124     
125     if (proc_start_end(&start_tv,&end_tv,&start_tmp,&end_tmp) == -1){
126         return -1;
127     }  
128
129     
130     if (start_tmp < 3600*24*365*10){
131         rrd_set_error("the first entry to fetch should be after 1980");
132         return(-1);
133     }
134     
135     if (end_tmp < start_tmp) {
136         rrd_set_error("start (%ld) should be less than end (%ld)", start_tmp, end_tmp);
137         return(-1);
138     }
139     
140     *start = start_tmp;
141     *end = end_tmp;
142
143     if (step_tmp < 1) {
144         rrd_set_error("step must be >= 1 second");
145         return -1;
146     }
147     *step = step_tmp;
148     
149     if (optind + 1 >= argc){
150         rrd_set_error("not enough arguments");
151         return -1;
152     }
153
154     cf = argv[optind+1];
155
156     if (rrd_fetch_r(argv[optind],cf,start,end,step,ds_cnt,ds_namv,data) == -1)
157         return(-1);
158     return (0);
159 }
160
161 int
162 rrd_fetch_r(
163     const char           *filename,  /* name of the rrd */
164     const char           *cf,        /* which consolidation function ?*/
165     time_t         *start,
166     time_t         *end,       /* which time frame do you want ?
167                                 * will be changed to represent reality */
168     unsigned long  *step,      /* which stepsize do you want? 
169                                 * will be changed to represent reality */
170     unsigned long  *ds_cnt,    /* number of data sources in file */
171     char           ***ds_namv, /* names of data_sources */
172     rrd_value_t    **data)     /* two dimensional array containing the data */
173 {
174     enum     cf_en cf_idx;
175
176     if ((int)(cf_idx=cf_conv(cf)) == -1 ){
177         return -1;
178     }
179
180     return (rrd_fetch_fn(filename,cf_idx,start,end,step,ds_cnt,ds_namv,data));
181 }
182
183 int
184 rrd_fetch_fn(
185     const char     *filename,  /* name of the rrd */
186     enum cf_en     cf_idx,         /* which consolidation function ?*/
187     time_t         *start,
188     time_t         *end,       /* which time frame do you want ?
189                                 * will be changed to represent reality */
190     unsigned long  *step,      /* which stepsize do you want? 
191                                 * will be changed to represent reality */
192     unsigned long  *ds_cnt,    /* number of data sources in file */
193     char           ***ds_namv,   /* names of data_sources */
194     rrd_value_t    **data)     /* two dimensional array containing the data */
195 {
196     long           i,ii;
197     FILE           *in_file;
198     time_t         cal_start,cal_end, rra_start_time,rra_end_time;
199     long  best_full_rra=0, best_part_rra=0, chosen_rra=0, rra_pointer=0;
200     long  best_full_step_diff=0, best_part_step_diff=0, tmp_step_diff=0, tmp_match=0, best_match=0;
201     long  full_match, rra_base;
202     long           start_offset, end_offset;
203     int            first_full = 1;
204     int            first_part = 1;
205     rrd_t     rrd;
206     rrd_value_t    *data_ptr;
207     unsigned long  rows;
208
209 #ifdef DEBUG
210 fprintf(stderr,"Entered rrd_fetch_fn() searching for the best match\n");
211 fprintf(stderr,"Looking for: start %10lu end %10lu step %5lu\n",
212                                                 *start,*end,*step);
213 #endif
214
215     if(rrd_open(filename,&in_file,&rrd, RRD_READONLY)==-1)
216         return(-1);
217     
218     /* when was the really last update of this file ? */
219
220     if (((*ds_namv) = (char **) malloc(rrd.stat_head->ds_cnt * sizeof(char*)))==NULL){
221         rrd_set_error("malloc fetch ds_namv array");
222         rrd_free(&rrd);
223         fclose(in_file);
224         return(-1);
225     }
226     
227     for(i=0;(unsigned long)i<rrd.stat_head->ds_cnt;i++){
228         if ((((*ds_namv)[i]) = malloc(sizeof(char) * DS_NAM_SIZE))==NULL){
229             rrd_set_error("malloc fetch ds_namv entry");
230             rrd_free(&rrd);
231             free(*ds_namv);
232             fclose(in_file);
233             return(-1);
234         }
235         strncpy((*ds_namv)[i],rrd.ds_def[i].ds_nam,DS_NAM_SIZE-1);
236         (*ds_namv)[i][DS_NAM_SIZE-1]='\0';
237
238     }
239     
240     /* find the rra which best matches the requirements */
241     for(i=0;(unsigned)i<rrd.stat_head->rra_cnt;i++){
242         if(cf_conv(rrd.rra_def[i].cf_nam) == cf_idx){
243             
244             cal_end = (rrd.live_head->last_up - (rrd.live_head->last_up 
245                           % (rrd.rra_def[i].pdp_cnt 
246                              * rrd.stat_head->pdp_step)));
247             cal_start = (cal_end 
248                          - (rrd.rra_def[i].pdp_cnt 
249                             * rrd.rra_def[i].row_cnt
250                             * rrd.stat_head->pdp_step));
251
252             full_match = *end -*start;
253 #ifdef DEBUG
254 fprintf(stderr,"Considering: start %10lu end %10lu step %5lu ",
255                                                         cal_start,cal_end,
256                         rrd.stat_head->pdp_step * rrd.rra_def[i].pdp_cnt);
257 #endif
258             /* we need step difference in either full or partial case */
259             tmp_step_diff = labs(*step - (rrd.stat_head->pdp_step
260                                            * rrd.rra_def[i].pdp_cnt));
261             /* best full match */
262             if(cal_end >= *end 
263                && cal_start <= *start){
264                 if (first_full || (tmp_step_diff < best_full_step_diff)){
265                     first_full=0;
266                     best_full_step_diff = tmp_step_diff;
267                     best_full_rra=i;
268 #ifdef DEBUG
269 fprintf(stderr,"best full match so far\n");
270 #endif
271                 } else {
272 #ifdef DEBUG
273 fprintf(stderr,"full match, not best\n");
274 #endif
275                 }
276                 
277             } else {
278                 /* best partial match */
279                 tmp_match = full_match;
280                 if (cal_start>*start)
281                     tmp_match -= (cal_start-*start);
282                 if (cal_end<*end)
283                     tmp_match -= (*end-cal_end);                
284                 if (first_part ||
285                     (best_match < tmp_match) ||
286                     (best_match == tmp_match && 
287                      tmp_step_diff < best_part_step_diff)){ 
288 #ifdef DEBUG
289 fprintf(stderr,"best partial so far\n");
290 #endif
291                     first_part=0;
292                     best_match = tmp_match;
293                     best_part_step_diff = tmp_step_diff;
294                     best_part_rra =i;
295                 } else {
296 #ifdef DEBUG
297 fprintf(stderr,"partial match, not best\n");
298 #endif
299                 }
300             }
301         }
302     }
303
304     /* lets see how the matching went. */
305     if (first_full==0)
306         chosen_rra = best_full_rra;
307     else if (first_part==0)
308         chosen_rra = best_part_rra;
309     else {
310         rrd_set_error("the RRD does not contain an RRA matching the chosen CF");
311         rrd_free(&rrd);
312         fclose(in_file);
313         return(-1);
314     }
315         
316     /* set the wish parameters to their real values */
317     *step = rrd.stat_head->pdp_step * rrd.rra_def[chosen_rra].pdp_cnt;
318     *start -= (*start % *step);
319     *end += (*step - *end % *step);
320     rows = (*end - *start) / *step + 1;
321
322 #ifdef DEBUG
323     fprintf(stderr,"We found:    start %10lu end %10lu step %5lu rows  %lu\n",
324                                                 *start,*end,*step,rows);
325 #endif
326
327 /* Start and end are now multiples of the step size.  The amount of
328 ** steps we want is (end-start)/step and *not* an extra one.
329 ** Reasoning:  if step is s and we want to graph from t to t+s,
330 ** we need exactly ((t+s)-t)/s rows.  The row to collect from the
331 ** database is the one with time stamp (t+s) which means t to t+s.
332 */
333     *ds_cnt =   rrd.stat_head->ds_cnt; 
334     if (((*data) = malloc(*ds_cnt * rows * sizeof(rrd_value_t)))==NULL){
335         rrd_set_error("malloc fetch data area");
336         for (i=0;(unsigned long)i<*ds_cnt;i++)
337               free((*ds_namv)[i]);
338         free(*ds_namv);
339         rrd_free(&rrd);
340         fclose(in_file);
341         return(-1);
342     }
343     
344     data_ptr=(*data);
345     
346     /* find base address of rra */
347     rra_base=ftell(in_file);
348     for(i=0;i<chosen_rra;i++)
349         rra_base += ( *ds_cnt
350                       * rrd.rra_def[i].row_cnt
351                       * sizeof(rrd_value_t));
352
353     /* find start and end offset */
354     rra_end_time = (rrd.live_head->last_up 
355                     - (rrd.live_head->last_up % *step));
356     rra_start_time = (rra_end_time
357                  - ( *step * (rrd.rra_def[chosen_rra].row_cnt-1)));
358     /* here's an error by one if we don't be careful */
359     start_offset =(long)(*start + *step - rra_start_time) / (long)*step;
360     end_offset = (long)(rra_end_time - *end ) / (long)*step; 
361 #ifdef DEBUG
362     fprintf(stderr,"rra_start %lu, rra_end %lu, start_off %li, end_off %li\n",
363             rra_start_time,rra_end_time,start_offset,end_offset);
364 #endif
365
366     /* fill the gap at the start if needs be */
367
368     if (start_offset <= 0)
369         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row+1;
370     else 
371         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row+1+start_offset;
372     
373     if(fseek(in_file,(rra_base 
374                    + (rra_pointer
375                       * *ds_cnt
376                       * sizeof(rrd_value_t))),SEEK_SET) != 0){
377         rrd_set_error("seek error in RRA");
378         for (i=0;(unsigned)i<*ds_cnt;i++)
379               free((*ds_namv)[i]);
380         free(*ds_namv);
381         rrd_free(&rrd);
382         free(*data);
383         *data = NULL;
384         fclose(in_file);
385         return(-1);
386
387     }
388 #ifdef DEBUG
389     fprintf(stderr,"First Seek: rra_base %lu rra_pointer %lu\n",
390             rra_base, rra_pointer);
391 #endif
392     /* step trough the array */
393
394     for (i=start_offset;
395          i< (signed)rrd.rra_def[chosen_rra].row_cnt - end_offset;
396          i++){
397         /* no valid data yet */
398         if (i<0) {
399 #ifdef DEBUG
400             fprintf(stderr,"pre fetch %li -- ",i);
401 #endif
402             for(ii=0;(unsigned)ii<*ds_cnt;ii++){
403                 *(data_ptr++) = DNAN;
404 #ifdef DEBUG
405                 fprintf(stderr,"%10.2f ",*(data_ptr-1));
406 #endif
407             }
408         } 
409         /* past the valid data area */
410         else if (i >= (signed)rrd.rra_def[chosen_rra].row_cnt) {
411 #ifdef DEBUG
412             fprintf(stderr,"post fetch %li -- ",i);
413 #endif
414             for(ii=0;(unsigned)ii<*ds_cnt;ii++){
415                 *(data_ptr++) = DNAN;
416 #ifdef DEBUG
417                 fprintf(stderr,"%10.2f ",*(data_ptr-1));
418 #endif
419             }
420         } else {
421             /* OK we are inside the valid area but the pointer has to 
422              * be wrapped*/
423             if (rra_pointer >= (signed)rrd.rra_def[chosen_rra].row_cnt) {
424                 rra_pointer -= rrd.rra_def[chosen_rra].row_cnt;
425                 if(fseek(in_file,(rra_base+rra_pointer
426                                * *ds_cnt
427                                * sizeof(rrd_value_t)),SEEK_SET) != 0){
428                     rrd_set_error("wrap seek in RRA did fail");
429                     for (ii=0;(unsigned)ii<*ds_cnt;ii++)
430                         free((*ds_namv)[ii]);
431                     free(*ds_namv);
432                     rrd_free(&rrd);
433                     free(*data);
434                     *data = NULL;
435                     fclose(in_file);
436                     return(-1);
437                 }
438 #ifdef DEBUG
439                 fprintf(stderr,"wrap seek ...\n");
440 #endif      
441             }
442             
443             if(fread(data_ptr,
444                      sizeof(rrd_value_t),
445                      *ds_cnt,in_file) != rrd.stat_head->ds_cnt){
446                 rrd_set_error("fetching cdp from rra");
447                 for (ii=0;(unsigned)ii<*ds_cnt;ii++)
448                     free((*ds_namv)[ii]);
449                 free(*ds_namv);
450                 rrd_free(&rrd);
451                 free(*data);
452                 *data = NULL;
453                 fclose(in_file);
454                 return(-1);
455             }
456 #ifdef DEBUG
457             fprintf(stderr,"post fetch %li -- ",i);
458             for(ii=0;ii<*ds_cnt;ii++)
459                 fprintf(stderr,"%10.2f ",*(data_ptr+ii));
460 #endif
461             data_ptr += *ds_cnt;
462             rra_pointer ++;
463         }
464 #ifdef DEBUG
465             fprintf(stderr,"\n");
466 #endif      
467         
468     }
469     rrd_free(&rrd);
470     fclose(in_file);
471     return(0);
472 }