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