Code

Imported upstream version 1.3.8.
[pkg-rrdtool.git] / src / rrd_fetch.c
1 /*****************************************************************************
2  * RRDtool 1.3.8  Copyright by Tobi Oetiker, 1997-2009
3  *****************************************************************************
4  * rrd_fetch.c  read date from an rrd to use for further processing
5  *****************************************************************************
6  * $Id: rrd_fetch.c 1801 2009-05-19 13:45:05Z oetiker $
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  *****************************************************************************/
55 #ifdef WIN32
56 #include <stdlib.h>
57 #endif
59 #include "rrd_tool.h"
61 #include "rrd_is_thread_safe.h"
62 /*#define DEBUG*/
64 int rrd_fetch(
65     int argc,
66     char **argv,
67     time_t *start,
68     time_t *end,        /* which time frame do you want ?
69                          * will be changed to represent reality */
70     unsigned long *step,    /* which stepsize do you want? 
71                              * will be changed to represent reality */
72     unsigned long *ds_cnt,  /* number of data sources in file */
73     char ***ds_namv,    /* names of data sources */
74     rrd_value_t **data)
75 {                       /* two dimensional array containing the data */
76     long      step_tmp = 1;
77     time_t    start_tmp = 0, end_tmp = 0;
78     const char *cf;
80     rrd_time_value_t start_tv, end_tv;
81     char     *parsetime_error = NULL;
82     struct option long_options[] = {
83         {"resolution", required_argument, 0, 'r'},
84         {"start", required_argument, 0, 's'},
85         {"end", required_argument, 0, 'e'},
86         {0, 0, 0, 0}
87     };
89     optind = 0;
90     opterr = 0;         /* initialize getopt */
92     /* init start and end time */
93     rrd_parsetime("end-24h", &start_tv);
94     rrd_parsetime("now", &end_tv);
96     while (1) {
97         int       option_index = 0;
98         int       opt;
100         opt = getopt_long(argc, argv, "r:s:e:", long_options, &option_index);
102         if (opt == EOF)
103             break;
105         switch (opt) {
106         case 's':
107             if ((parsetime_error = rrd_parsetime(optarg, &start_tv))) {
108                 rrd_set_error("start time: %s", parsetime_error);
109                 return -1;
110             }
111             break;
112         case 'e':
113             if ((parsetime_error = rrd_parsetime(optarg, &end_tv))) {
114                 rrd_set_error("end time: %s", parsetime_error);
115                 return -1;
116             }
117             break;
118         case 'r':
119             step_tmp = atol(optarg);
120             break;
121         case '?':
122             rrd_set_error("unknown option '-%c'", optopt);
123             return (-1);
124         }
125     }
128     if (rrd_proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
129         return -1;
130     }
133     if (start_tmp < 3600 * 24 * 365 * 10) {
134         rrd_set_error("the first entry to fetch should be after 1980");
135         return (-1);
136     }
138     if (end_tmp < start_tmp) {
139         rrd_set_error("start (%ld) should be less than end (%ld)", start_tmp,
140                       end_tmp);
141         return (-1);
142     }
144     *start = start_tmp;
145     *end = end_tmp;
147     if (step_tmp < 1) {
148         rrd_set_error("step must be >= 1 second");
149         return -1;
150     }
151     *step = step_tmp;
153     if (optind + 1 >= argc) {
154         rrd_set_error("not enough arguments");
155         return -1;
156     }
158     cf = argv[optind + 1];
160     if (rrd_fetch_r(argv[optind], cf, start, end, step, ds_cnt, ds_namv, data)
161         != 0)
162         return (-1);
163     return (0);
166 int rrd_fetch_r(
167     const char *filename,   /* name of the rrd */
168     const char *cf,     /* which consolidation function ? */
169     time_t *start,
170     time_t *end,        /* which time frame do you want ?
171                          * will be changed to represent reality */
172     unsigned long *step,    /* which stepsize do you want? 
173                              * will be changed to represent reality */
174     unsigned long *ds_cnt,  /* number of data sources in file */
175     char ***ds_namv,    /* names of data_sources */
176     rrd_value_t **data)
177 {                       /* two dimensional array containing the data */
178     enum cf_en cf_idx;
180     if ((int) (cf_idx = cf_conv(cf)) == -1) {
181         return -1;
182     }
184     return (rrd_fetch_fn
185             (filename, cf_idx, start, end, step, ds_cnt, ds_namv, data));
188 int rrd_fetch_fn(
189     const char *filename,   /* name of the rrd */
190     enum cf_en cf_idx,  /* which consolidation function ? */
191     time_t *start,
192     time_t *end,        /* which time frame do you want ?
193                          * will be changed to represent reality */
194     unsigned long *step,    /* which stepsize do you want? 
195                              * will be changed to represent reality */
196     unsigned long *ds_cnt,  /* number of data sources in file */
197     char ***ds_namv,    /* names of data_sources */
198     rrd_value_t **data)
199 {                       /* two dimensional array containing the data */
200     long      i, ii;
201     time_t    cal_start, cal_end, rra_start_time, rra_end_time;
202     long      best_full_rra = 0, best_part_rra = 0, chosen_rra =
203         0, rra_pointer = 0;
204     long      best_full_step_diff = 0, best_part_step_diff =
205         0, tmp_step_diff = 0, tmp_match = 0, best_match = 0;
206     long      full_match, rra_base;
207     long      start_offset, end_offset;
208     int       first_full = 1;
209     int       first_part = 1;
210     rrd_t     rrd;
211     rrd_file_t *rrd_file;
212     rrd_value_t *data_ptr;
213     unsigned long rows;
215 #ifdef DEBUG
216     fprintf(stderr, "Entered rrd_fetch_fn() searching for the best match\n");
217     fprintf(stderr, "Looking for: start %10lu end %10lu step %5lu\n",
218             *start, *end, *step);
219 #endif
221     rrd_file = rrd_open(filename, &rrd, RRD_READONLY);
222     if (rrd_file == NULL)
223         goto err_free;
225     /* when was the really last update of this file ? */
227     if (((*ds_namv) =
228          (char **) malloc(rrd.stat_head->ds_cnt * sizeof(char *))) == NULL) {
229         rrd_set_error("malloc fetch ds_namv array");
230         goto err_close;
231     }
233     for (i = 0; (unsigned long) i < rrd.stat_head->ds_cnt; i++) {
234         if ((((*ds_namv)[i]) = (char*)malloc(sizeof(char) * DS_NAM_SIZE)) == NULL) {
235             rrd_set_error("malloc fetch ds_namv entry");
236             goto err_free_ds_namv;
237         }
238         strncpy((*ds_namv)[i], rrd.ds_def[i].ds_nam, DS_NAM_SIZE - 1);
239         (*ds_namv)[i][DS_NAM_SIZE - 1] = '\0';
241     }
243     /* find the rra which best matches the requirements */
244     for (i = 0; (unsigned) i < rrd.stat_head->rra_cnt; i++) {
245         if (cf_conv(rrd.rra_def[i].cf_nam) == cf_idx) {
247             cal_end = (rrd.live_head->last_up - (rrd.live_head->last_up
248                                                  % (rrd.rra_def[i].pdp_cnt
249                                                     *
250                                                     rrd.stat_head->
251                                                     pdp_step)));
252             cal_start =
253                 (cal_end -
254                  (rrd.rra_def[i].pdp_cnt * rrd.rra_def[i].row_cnt *
255                   rrd.stat_head->pdp_step));
257             full_match = *end - *start;
258 #ifdef DEBUG
259             fprintf(stderr, "Considering: start %10lu end %10lu step %5lu ",
260                     cal_start, cal_end,
261                     rrd.stat_head->pdp_step * rrd.rra_def[i].pdp_cnt);
262 #endif
263             /* we need step difference in either full or partial case */
264             tmp_step_diff = labs(*step - (rrd.stat_head->pdp_step
265                                           * rrd.rra_def[i].pdp_cnt));
266             /* best full match */
267             if (cal_start <= *start) {
268                 if (first_full || (tmp_step_diff < best_full_step_diff)) {
269                     first_full = 0;
270                     best_full_step_diff = tmp_step_diff;
271                     best_full_rra = i;
272 #ifdef DEBUG
273                     fprintf(stderr, "best full match so far\n");
274                 } else {
275                     fprintf(stderr, "full match, not best\n");
276 #endif
277                 }
279             } else {
280                 /* best partial match */
281                 tmp_match = full_match;
282                 if (cal_start > *start)
283                     tmp_match -= (cal_start - *start);
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     }
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
311             ("the RRD does not contain an RRA matching the chosen CF");
312         goto err_free_all_ds_namv;
313     }
315     /* set the wish parameters to their real values */
316     *step = rrd.stat_head->pdp_step * rrd.rra_def[chosen_rra].pdp_cnt;
317     *start -= (*start % *step);
318     *end += (*step - *end % *step);
319     rows = (*end - *start) / *step + 1;
321 #ifdef DEBUG
322     fprintf(stderr,
323             "We found:    start %10lu end %10lu step %5lu rows  %lu\n",
324             *start, *end, *step, rows);
325 #endif
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) = (rrd_value_t *)malloc(*ds_cnt * rows * sizeof(rrd_value_t))) == NULL) {
335         rrd_set_error("malloc fetch data area");
336         goto err_free_all_ds_namv;
337     }
339     data_ptr = (*data);
341     /* find base address of rra */
342     rra_base = rrd_file->header_len;
343     for (i = 0; i < chosen_rra; i++)
344         rra_base += (*ds_cnt * rrd.rra_def[i].row_cnt * sizeof(rrd_value_t));
346     /* find start and end offset */
347     rra_end_time = (rrd.live_head->last_up
348                     - (rrd.live_head->last_up % *step));
349     rra_start_time = (rra_end_time
350                       - (*step * (rrd.rra_def[chosen_rra].row_cnt - 1)));
351     /* here's an error by one if we don't be careful */
352     start_offset = (long) (*start + *step - rra_start_time) / (long) *step;
353     end_offset = (long) (rra_end_time - *end) / (long) *step;
354 #ifdef DEBUG
355     fprintf(stderr,
356             "rra_start %lu, rra_end %lu, start_off %li, end_off %li\n",
357             rra_start_time, rra_end_time, start_offset, end_offset);
358 #endif
360     /* fill the gap at the start if needs be */
362     if (*start <= rra_end_time && *end >= rra_start_time - *step){
363         
364         if (start_offset <= 0)
365             rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1;
366         else
367             rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1 + start_offset;
369         rra_pointer = rra_pointer % (signed) rrd.rra_def[chosen_rra].row_cnt;
370          
371         if (rrd_seek(rrd_file, (rra_base + (rra_pointer * (*ds_cnt)
372                                             * sizeof(rrd_value_t))),
373                  SEEK_SET) != 0) {
374             rrd_set_error("seek error in RRA");
375             goto err_free_data;
376         }        
377 #ifdef DEBUG
378         fprintf(stderr, "First Seek: rra_base %lu rra_pointer %lu\n",
379             rra_base, rra_pointer);
380 #endif
381     }
382     
383     /* step trough the array */
385     for (i = start_offset;
386          i < (signed) rrd.rra_def[chosen_rra].row_cnt - end_offset; i++) {
387         /* no valid data yet */
388         if (i < 0) {
389 #ifdef DEBUG
390             fprintf(stderr, "pre 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         }
399         /* past the valid data area */
400         else if (i >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
401 #ifdef DEBUG
402             fprintf(stderr, "past fetch %li -- ", i);
403 #endif
404             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
405                 *(data_ptr++) = DNAN;
406 #ifdef DEBUG
407                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
408 #endif
409             }
410         } else {
411             /* OK we are inside the valid area but the pointer has to 
412              * be wrapped*/
413             if (rra_pointer >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
414                 rra_pointer -= rrd.rra_def[chosen_rra].row_cnt;
415                 if (rrd_seek(rrd_file, (rra_base + rra_pointer * (*ds_cnt)
416                                         * sizeof(rrd_value_t)),
417                              SEEK_SET) != 0) {
418                     rrd_set_error("wrap seek in RRA did fail");
419                     goto err_free_data;
420                 }
421 #ifdef DEBUG
422                 fprintf(stderr, "wrap seek ...\n");
423 #endif
424             }
426             if (rrd_read(rrd_file, data_ptr, sizeof(rrd_value_t) * (*ds_cnt))
427                 != (ssize_t) (sizeof(rrd_value_t) * (*ds_cnt))) {
428                 rrd_set_error("fetching cdp from rra");
429                 goto err_free_data;
430             }
431 #ifdef DEBUG
432             fprintf(stderr, "post fetch %li -- ", i);
433             for (ii = 0; ii < *ds_cnt; ii++)
434                 fprintf(stderr, "%10.2f ", *(data_ptr + ii));
435 #endif
436             data_ptr += *ds_cnt;
437             rra_pointer++;
438         }
439 #ifdef DEBUG
440         fprintf(stderr, "\n");
441 #endif
443     }
445     rrd_close(rrd_file);
446     rrd_free(&rrd);
448     return (0);
449   err_free_data:
450     free(*data);
451     *data = NULL;
452   err_free_all_ds_namv:
453     for (i = 0; (unsigned long) i < rrd.stat_head->ds_cnt; ++i)
454         free((*ds_namv)[i]);
455   err_free_ds_namv:
456     free(*ds_namv);
457   err_close:
458     rrd_close(rrd_file);
459   err_free:
460     rrd_free(&rrd);
461     return (-1);