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