prep for 1.2rc9 release
[rrdtool.git] / src / rrd_fetch.c
1 /*****************************************************************************
2  * RRDtool 1.2rc9  Copyright by Tobi Oetiker, 1997-2005
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 /*#define DEBUG*/
57
58 int
59 rrd_fetch(int argc, 
60           char **argv,
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  *ds_cnt,    /* number of data sources in file */
67           char           ***ds_namv,   /* names of data sources */
68           rrd_value_t    **data)     /* two dimensional array containing the data */
69 {
70
71
72     long     step_tmp =1;
73     time_t   start_tmp=0, end_tmp=0;
74     enum     cf_en cf_idx;
75
76     struct rrd_time_value start_tv, end_tv;
77     char     *parsetime_error = NULL;
78
79     /* init start and end time */
80     parsetime("end-24h", &start_tv);
81     parsetime("now", &end_tv);
82
83     while (1){
84         static struct option long_options[] =
85         {
86             {"resolution",      required_argument, 0, 'r'},
87             {"start",      required_argument, 0, 's'},
88             {"end",      required_argument, 0, 'e'},
89             {0,0,0,0}
90         };
91         int option_index = 0;
92         int opt;
93         opt = getopt_long(argc, argv, "r:s:e:", 
94                           long_options, &option_index);
95
96         if (opt == EOF)
97             break;
98
99         switch(opt) {
100         case 's':
101             if ((parsetime_error = parsetime(optarg, &start_tv))) {
102                 rrd_set_error( "start time: %s", parsetime_error );
103                 return -1;
104             }
105             break;
106         case 'e':
107             if ((parsetime_error = parsetime(optarg, &end_tv))) {
108                 rrd_set_error( "end time: %s", parsetime_error );
109                 return -1;
110             }
111             break;
112         case 'r':
113             step_tmp = atol(optarg);
114             break;
115         case '?':
116             rrd_set_error("unknown option '-%c'",optopt);
117             return(-1);
118         }
119     }
120
121     
122     if (proc_start_end(&start_tv,&end_tv,&start_tmp,&end_tmp) == -1){
123         return -1;
124     }  
125
126     
127     if (start_tmp < 3600*24*365*10){
128         rrd_set_error("the first entry to fetch should be after 1980");
129         return(-1);
130     }
131     
132     if (end_tmp < start_tmp) {
133         rrd_set_error("start (%ld) should be less than end (%ld)", start_tmp, end_tmp);
134         return(-1);
135     }
136     
137     *start = start_tmp;
138     *end = end_tmp;
139
140     if (step_tmp < 1) {
141         rrd_set_error("step must be >= 1 second");
142         return -1;
143     }
144     *step = step_tmp;
145     
146     if (optind + 1 >= argc){
147         rrd_set_error("not enough arguments");
148         return -1;
149     }
150     
151     if ((int)(cf_idx=cf_conv(argv[optind+1])) == -1 ){
152         return -1;
153     }
154
155     if (rrd_fetch_fn(argv[optind],cf_idx,start,end,step,ds_cnt,ds_namv,data) == -1)
156         return(-1);
157     return (0);
158 }
159
160 int
161 rrd_fetch_fn(
162     char           *filename,  /* name of the rrd */
163     enum cf_en     cf_idx,         /* which consolidation function ?*/
164     time_t         *start,
165     time_t         *end,       /* which time frame do you want ?
166                                 * will be changed to represent reality */
167     unsigned long  *step,      /* which stepsize do you want? 
168                                 * will be changed to represent reality */
169     unsigned long  *ds_cnt,    /* number of data sources in file */
170     char           ***ds_namv,   /* names of data_sources */
171     rrd_value_t    **data)     /* two dimensional array containing the data */
172 {
173     long           i,ii;
174     FILE           *in_file;
175     time_t         cal_start,cal_end, rra_start_time,rra_end_time;
176     long  best_full_rra=0, best_part_rra=0, chosen_rra=0, rra_pointer=0;
177     long  best_step_diff=0, tmp_step_diff=0, tmp_match=0, best_match=0;
178     long  full_match, rra_base;
179     long           start_offset, end_offset;
180     int            first_full = 1;
181     int            first_part = 1;
182     rrd_t     rrd;
183     rrd_value_t    *data_ptr;
184     unsigned long  rows = (*end - *start) / *step;
185
186 #ifdef DEBUG
187 fprintf(stderr,"Entered rrd_fetch_fn() searching for the best match\n");
188 fprintf(stderr,"Looking for: start %10lu end %10lu step %5lu rows  %lu\n",
189                                                 *start,*end,*step,rows);
190 #endif
191
192     if(rrd_open(filename,&in_file,&rrd, RRD_READONLY)==-1)
193         return(-1);
194     
195     /* when was the really last update of this file ? */
196
197     if (((*ds_namv) = (char **) malloc(rrd.stat_head->ds_cnt * sizeof(char*)))==NULL){
198         rrd_set_error("malloc fetch ds_namv array");
199         rrd_free(&rrd);
200         fclose(in_file);
201         return(-1);
202     }
203     
204     for(i=0;(unsigned long)i<rrd.stat_head->ds_cnt;i++){
205         if ((((*ds_namv)[i]) = malloc(sizeof(char) * DS_NAM_SIZE))==NULL){
206             rrd_set_error("malloc fetch ds_namv entry");
207             rrd_free(&rrd);
208             free(*ds_namv);
209             fclose(in_file);
210             return(-1);
211         }
212         strncpy((*ds_namv)[i],rrd.ds_def[i].ds_nam,DS_NAM_SIZE-1);
213         (*ds_namv)[i][DS_NAM_SIZE-1]='\0';
214
215     }
216     
217     /* find the rra which best matches the requirements */
218     for(i=0;(unsigned)i<rrd.stat_head->rra_cnt;i++){
219         if(cf_conv(rrd.rra_def[i].cf_nam) == cf_idx){
220             
221             cal_end = (rrd.live_head->last_up - (rrd.live_head->last_up 
222                           % (rrd.rra_def[i].pdp_cnt 
223                              * rrd.stat_head->pdp_step)));
224             cal_start = (cal_end 
225                          - (rrd.rra_def[i].pdp_cnt 
226                             * rrd.rra_def[i].row_cnt
227                             * rrd.stat_head->pdp_step));
228
229             full_match = *end -*start;
230 #ifdef DEBUG
231 fprintf(stderr,"Considering: start %10lu end %10lu step %5lu ",
232                                                         cal_start,cal_end,
233                         rrd.stat_head->pdp_step * rrd.rra_def[i].pdp_cnt);
234 #endif
235             /* we need step difference in either full or partial case */
236             tmp_step_diff = labs(*step - (rrd.stat_head->pdp_step
237                                            * rrd.rra_def[i].pdp_cnt));
238             /* best full match */
239             if(cal_end >= *end 
240                && cal_start <= *start){
241                 if (first_full || (tmp_step_diff < best_step_diff)){
242                     first_full=0;
243                     best_step_diff = tmp_step_diff;
244                     best_full_rra=i;
245 #ifdef DEBUG
246 fprintf(stderr,"best full match so far\n");
247 #endif
248                 } else {
249 #ifdef DEBUG
250 fprintf(stderr,"full match, not best\n");
251 #endif
252                 }
253                 
254             } else {
255                 /* best partial match */
256                 tmp_match = full_match;
257                 if (cal_start>*start)
258                     tmp_match -= (cal_start-*start);
259                 if (cal_end<*end)
260                     tmp_match -= (*end-cal_end);                
261                 if (first_part ||
262                     (best_match < tmp_match) ||
263                     (best_match == tmp_match && 
264                      tmp_step_diff < best_step_diff)){ 
265 #ifdef DEBUG
266 fprintf(stderr,"best partial so far\n");
267 #endif
268                     first_part=0;
269                     best_match = tmp_match;
270                     best_step_diff = tmp_step_diff;
271                     best_part_rra =i;
272                 } else {
273 #ifdef DEBUG
274 fprintf(stderr,"partial match, not best\n");
275 #endif
276                 }
277             }
278         }
279     }
280
281     /* lets see how the matching went. */
282     if (first_full==0)
283         chosen_rra = best_full_rra;
284     else if (first_part==0)
285         chosen_rra = best_part_rra;
286     else {
287         rrd_set_error("the RRD does not contain an RRA matching the chosen CF");
288         rrd_free(&rrd);
289         fclose(in_file);
290         return(-1);
291     }
292         
293     /* set the wish parameters to their real values */
294     *step = rrd.stat_head->pdp_step * rrd.rra_def[chosen_rra].pdp_cnt;
295     *start -= (*start % *step);
296     if (*end % *step) *end += (*step - *end % *step);
297     rows = (*end - *start) / *step;
298
299 #ifdef DEBUG
300     fprintf(stderr,"We found:    start %10lu end %10lu step %5lu rows  %lu\n",
301                                                 *start,*end,*step,rows);
302 #endif
303
304 /* Start and end are now multiples of the step size.  The amount of
305 ** steps we want is (end-start)/step and *not* an extra one.
306 ** Reasoning:  if step is s and we want to graph from t to t+s,
307 ** we need exactly ((t+s)-t)/s rows.  The row to collect from the
308 ** database is the one with time stamp (t+s) which means t to t+s.
309 */
310     *ds_cnt =   rrd.stat_head->ds_cnt; 
311     if (((*data) = malloc(*ds_cnt * rows * sizeof(rrd_value_t)))==NULL){
312         rrd_set_error("malloc fetch data area");
313         for (i=0;(unsigned long)i<*ds_cnt;i++)
314               free((*ds_namv)[i]);
315         free(*ds_namv);
316         rrd_free(&rrd);
317         fclose(in_file);
318         return(-1);
319     }
320     
321     data_ptr=(*data);
322     
323     /* find base address of rra */
324     rra_base=ftell(in_file);
325     for(i=0;i<chosen_rra;i++)
326         rra_base += ( *ds_cnt
327                       * rrd.rra_def[i].row_cnt
328                       * sizeof(rrd_value_t));
329
330     /* find start and end offset */
331     rra_end_time = (rrd.live_head->last_up 
332                     - (rrd.live_head->last_up % *step));
333     rra_start_time = (rra_end_time
334                  - ( *step * (rrd.rra_def[chosen_rra].row_cnt-1)));
335     /* here's an error by one if we don't be careful */
336     start_offset =(long)(*start + *step - rra_start_time) / (long)*step;
337     end_offset = (long)(rra_end_time - *end ) / (long)*step; 
338 #ifdef DEBUG
339     fprintf(stderr,"rra_start %lu, rra_end %lu, start_off %li, end_off %li\n",
340             rra_start_time,rra_end_time,start_offset,end_offset);
341 #endif
342
343     /* fill the gap at the start if needs be */
344
345     if (start_offset <= 0)
346         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row+1;
347     else 
348         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row+1+start_offset;
349     
350     if(fseek(in_file,(rra_base 
351                    + (rra_pointer
352                       * *ds_cnt
353                       * sizeof(rrd_value_t))),SEEK_SET) != 0){
354         rrd_set_error("seek error in RRA");
355         for (i=0;(unsigned)i<*ds_cnt;i++)
356               free((*ds_namv)[i]);
357         free(*ds_namv);
358         rrd_free(&rrd);
359         free(*data);
360         *data = NULL;
361         fclose(in_file);
362         return(-1);
363
364     }
365 #ifdef DEBUG
366     fprintf(stderr,"First Seek: rra_base %lu rra_pointer %lu\n",
367             rra_base, rra_pointer);
368 #endif
369     /* step trough the array */
370
371     for (i=start_offset;
372          i< (signed)rrd.rra_def[chosen_rra].row_cnt - end_offset;
373          i++){
374         /* no valid data yet */
375         if (i<0) {
376 #ifdef DEBUG
377             fprintf(stderr,"pre fetch %li -- ",i);
378 #endif
379             for(ii=0;(unsigned)ii<*ds_cnt;ii++){
380                 *(data_ptr++) = DNAN;
381 #ifdef DEBUG
382                 fprintf(stderr,"%10.2f ",*(data_ptr-1));
383 #endif
384             }
385         } 
386         /* past the valid data area */
387         else if (i >= (signed)rrd.rra_def[chosen_rra].row_cnt) {
388 #ifdef DEBUG
389             fprintf(stderr,"post fetch %li -- ",i);
390 #endif
391             for(ii=0;(unsigned)ii<*ds_cnt;ii++){
392                 *(data_ptr++) = DNAN;
393 #ifdef DEBUG
394                 fprintf(stderr,"%10.2f ",*(data_ptr-1));
395 #endif
396             }
397         } else {
398             /* OK we are inside the valid area but the pointer has to 
399              * be wrapped*/
400             if (rra_pointer >= (signed)rrd.rra_def[chosen_rra].row_cnt) {
401                 rra_pointer -= rrd.rra_def[chosen_rra].row_cnt;
402                 if(fseek(in_file,(rra_base+rra_pointer
403                                * *ds_cnt
404                                * sizeof(rrd_value_t)),SEEK_SET) != 0){
405                     rrd_set_error("wrap seek in RRA did fail");
406                     for (ii=0;(unsigned)ii<*ds_cnt;ii++)
407                         free((*ds_namv)[ii]);
408                     free(*ds_namv);
409                     rrd_free(&rrd);
410                     free(*data);
411                     *data = NULL;
412                     fclose(in_file);
413                     return(-1);
414                 }
415 #ifdef DEBUG
416                 fprintf(stderr,"wrap seek ...\n");
417 #endif      
418             }
419             
420             if(fread(data_ptr,
421                      sizeof(rrd_value_t),
422                      *ds_cnt,in_file) != rrd.stat_head->ds_cnt){
423                 rrd_set_error("fetching cdp from rra");
424                 for (ii=0;(unsigned)ii<*ds_cnt;ii++)
425                     free((*ds_namv)[ii]);
426                 free(*ds_namv);
427                 rrd_free(&rrd);
428                 free(*data);
429                 *data = NULL;
430                 fclose(in_file);
431                 return(-1);
432             }
433 #ifdef DEBUG
434             fprintf(stderr,"post fetch %li -- ",i);
435             for(ii=0;ii<*ds_cnt;ii++)
436                 fprintf(stderr,"%10.2f ",*(data_ptr+ii));
437 #endif
438             data_ptr += *ds_cnt;
439             rra_pointer ++;
440         }
441 #ifdef DEBUG
442             fprintf(stderr,"\n");
443 #endif      
444         
445     }
446     rrd_free(&rrd);
447     fclose(in_file);
448     return(0);
449 }