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