From Bernhard Fischer
[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
73
74     long      step_tmp = 1;
75     time_t    start_tmp = 0, end_tmp = 0;
76     const char *cf;
77
78     struct rrd_time_value start_tv, end_tv;
79     char     *parsetime_error = NULL;
80
81     optind = 0;
82     opterr = 0;         /* initialize getopt */
83
84     /* init start and end time */
85     parsetime("end-24h", &start_tv);
86     parsetime("now", &end_tv);
87
88     while (1) {
89         static struct option long_options[] = {
90             {"resolution", required_argument, 0, 'r'},
91             {"start", required_argument, 0, 's'},
92             {"end", required_argument, 0, 'e'},
93             {0, 0, 0, 0}
94         };
95         int       option_index = 0;
96         int       opt;
97
98         opt = getopt_long(argc, argv, "r:s:e:", long_options, &option_index);
99
100         if (opt == EOF)
101             break;
102
103         switch (opt) {
104         case 's':
105             if ((parsetime_error = parsetime(optarg, &start_tv))) {
106                 rrd_set_error("start time: %s", parsetime_error);
107                 return -1;
108             }
109             break;
110         case 'e':
111             if ((parsetime_error = parsetime(optarg, &end_tv))) {
112                 rrd_set_error("end time: %s", parsetime_error);
113                 return -1;
114             }
115             break;
116         case 'r':
117             step_tmp = atol(optarg);
118             break;
119         case '?':
120             rrd_set_error("unknown option '-%c'", optopt);
121             return (-1);
122         }
123     }
124
125
126     if (proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
127         return -1;
128     }
129
130
131     if (start_tmp < 3600 * 24 * 365 * 10) {
132         rrd_set_error("the first entry to fetch should be after 1980");
133         return (-1);
134     }
135
136     if (end_tmp < start_tmp) {
137         rrd_set_error("start (%ld) should be less than end (%ld)", start_tmp,
138                       end_tmp);
139         return (-1);
140     }
141
142     *start = start_tmp;
143     *end = end_tmp;
144
145     if (step_tmp < 1) {
146         rrd_set_error("step must be >= 1 second");
147         return -1;
148     }
149     *step = step_tmp;
150
151     if (optind + 1 >= argc) {
152         rrd_set_error("not enough arguments");
153         return -1;
154     }
155
156     cf = argv[optind + 1];
157
158     if (rrd_fetch_r(argv[optind], cf, start, end, step, ds_cnt, ds_namv, data)
159         != 0)
160         return (-1);
161     return (0);
162 }
163
164 int rrd_fetch_r(
165     const char *filename,   /* name of the rrd */
166     const char *cf,     /* which consolidation function ? */
167     time_t *start,
168     time_t *end,        /* which time frame do you want ?
169                          * will be changed to represent reality */
170     unsigned long *step,    /* which stepsize do you want? 
171                              * will be changed to represent reality */
172     unsigned long *ds_cnt,  /* number of data sources in file */
173     char ***ds_namv,    /* names of data_sources */
174     rrd_value_t **data)
175 {                       /* two dimensional array containing the data */
176     enum cf_en cf_idx;
177
178     if ((int) (cf_idx = cf_conv(cf)) == -1) {
179         return -1;
180     }
181
182     return (rrd_fetch_fn
183             (filename, cf_idx, start, end, step, ds_cnt, ds_namv, data));
184 }
185
186 int rrd_fetch_fn(
187     const char *filename,   /* name of the rrd */
188     enum cf_en cf_idx,  /* which consolidation function ? */
189     time_t *start,
190     time_t *end,        /* which time frame do you want ?
191                          * will be changed to represent reality */
192     unsigned long *step,    /* which stepsize do you want? 
193                              * will be changed to represent reality */
194     unsigned long *ds_cnt,  /* number of data sources in file */
195     char ***ds_namv,    /* names of data_sources */
196     rrd_value_t **data)
197 {                       /* two dimensional array containing the data */
198     long      i, ii;
199     time_t    cal_start, cal_end, rra_start_time, rra_end_time;
200     long      best_full_rra = 0, best_part_rra = 0, chosen_rra =
201         0, rra_pointer = 0;
202     long      best_full_step_diff = 0, best_part_step_diff =
203         0, tmp_step_diff = 0, tmp_match = 0, best_match = 0;
204     long      full_match, rra_base;
205     long      start_offset, end_offset;
206     int       first_full = 1;
207     int       first_part = 1;
208     rrd_t     rrd;
209     rrd_file_t *rrd_file;
210     rrd_value_t *data_ptr;
211     unsigned long rows;
212
213 #ifdef DEBUG
214     fprintf(stderr, "Entered rrd_fetch_fn() searching for the best match\n");
215     fprintf(stderr, "Looking for: start %10lu end %10lu step %5lu\n",
216             *start, *end, *step);
217 #endif
218
219     rrd_file = rrd_open(filename, &rrd, RRD_READONLY);
220     if (rrd_file == NULL)
221         goto err_free;
222
223     /* when was the really last update of this file ? */
224
225     if (((*ds_namv) =
226          (char **) malloc(rrd.stat_head->ds_cnt * sizeof(char *))) == NULL) {
227         rrd_set_error("malloc fetch ds_namv array");
228         goto err_close;
229     }
230
231     for (i = 0; (unsigned long) i < rrd.stat_head->ds_cnt; i++) {
232         if ((((*ds_namv)[i]) = malloc(sizeof(char) * DS_NAM_SIZE)) == NULL) {
233             rrd_set_error("malloc fetch ds_namv entry");
234             goto err_free_ds_namv;
235         }
236         strncpy((*ds_namv)[i], rrd.ds_def[i].ds_nam, DS_NAM_SIZE - 1);
237         (*ds_namv)[i][DS_NAM_SIZE - 1] = '\0';
238
239     }
240
241     /* find the rra which best matches the requirements */
242     for (i = 0; (unsigned) i < rrd.stat_head->rra_cnt; i++) {
243         if (cf_conv(rrd.rra_def[i].cf_nam) == cf_idx) {
244
245             cal_end = (rrd.live_head->last_up - (rrd.live_head->last_up
246                                                  % (rrd.rra_def[i].pdp_cnt
247                                                     *
248                                                     rrd.stat_head->
249                                                     pdp_step)));
250             cal_start =
251                 (cal_end -
252                  (rrd.rra_def[i].pdp_cnt * rrd.rra_def[i].row_cnt *
253                   rrd.stat_head->pdp_step));
254
255             full_match = *end - *start;
256 #ifdef DEBUG
257             fprintf(stderr, "Considering: start %10lu end %10lu step %5lu ",
258                     cal_start, cal_end,
259                     rrd.stat_head->pdp_step * rrd.rra_def[i].pdp_cnt);
260 #endif
261             /* we need step difference in either full or partial case */
262             tmp_step_diff = labs(*step - (rrd.stat_head->pdp_step
263                                           * rrd.rra_def[i].pdp_cnt));
264             /* best full match */
265             if (cal_end >= *end && cal_start <= *start) {
266                 if (first_full || (tmp_step_diff < best_full_step_diff)) {
267                     first_full = 0;
268                     best_full_step_diff = tmp_step_diff;
269                     best_full_rra = i;
270 #ifdef DEBUG
271                     fprintf(stderr, "best full match so far\n");
272                 } else {
273                     fprintf(stderr, "full match, not best\n");
274 #endif
275                 }
276
277             } else {
278                 /* best partial match */
279                 tmp_match = full_match;
280                 if (cal_start > *start)
281                     tmp_match -= (cal_start - *start);
282                 if (cal_end < *end)
283                     tmp_match -= (*end - cal_end);
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     }
303
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     }
314
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;
320
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
326
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) = 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     }
338
339     data_ptr = (*data);
340
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));
345
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
359
360     /* fill the gap at the start if needs be */
361
362     if (start_offset <= 0)
363         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1;
364     else
365         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1 + start_offset;
366
367     if (rrd_seek(rrd_file, (rra_base + (rra_pointer * (*ds_cnt)
368                                         * sizeof(rrd_value_t))),
369                  SEEK_SET) != 0) {
370         rrd_set_error("seek error in RRA");
371         goto err_free_data;
372     }
373 #ifdef DEBUG
374     fprintf(stderr, "First Seek: rra_base %lu rra_pointer %lu\n",
375             rra_base, rra_pointer);
376 #endif
377     /* step trough the array */
378
379     for (i = start_offset;
380          i < (signed) rrd.rra_def[chosen_rra].row_cnt - end_offset; i++) {
381         /* no valid data yet */
382         if (i < 0) {
383 #ifdef DEBUG
384             fprintf(stderr, "pre fetch %li -- ", i);
385 #endif
386             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
387                 *(data_ptr++) = DNAN;
388 #ifdef DEBUG
389                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
390 #endif
391             }
392         }
393         /* past the valid data area */
394         else if (i >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
395 #ifdef DEBUG
396             fprintf(stderr, "past fetch %li -- ", i);
397 #endif
398             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
399                 *(data_ptr++) = DNAN;
400 #ifdef DEBUG
401                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
402 #endif
403             }
404         } else {
405             /* OK we are inside the valid area but the pointer has to 
406              * be wrapped*/
407             if (rra_pointer >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
408                 rra_pointer -= rrd.rra_def[chosen_rra].row_cnt;
409                 if (rrd_seek(rrd_file, (rra_base + rra_pointer * (*ds_cnt)
410                                         * sizeof(rrd_value_t)),
411                              SEEK_SET) != 0) {
412                     rrd_set_error("wrap seek in RRA did fail");
413                     goto err_free_data;
414                 }
415 #ifdef DEBUG
416                 fprintf(stderr, "wrap seek ...\n");
417 #endif
418             }
419
420             if (rrd_read(rrd_file, data_ptr, sizeof(rrd_value_t) * (*ds_cnt))
421                 != (ssize_t) (sizeof(rrd_value_t) * (*ds_cnt))) {
422                 rrd_set_error("fetching cdp from rra");
423                 goto err_free_data;
424             }
425 #ifdef HAVE_POSIX_FADVISE
426             /* don't pollute the buffer cache with data read from the file. We do this while reading to 
427                keep damage minimal */
428             if (0 !=
429                 posix_fadvise(rrd_file->fd, rrd_file->header_len, 0,
430                               POSIX_FADV_DONTNEED)) {
431                 rrd_set_error("setting POSIX_FADV_DONTNEED on '%s': %s",
432                               filename, rrd_strerror(errno));
433                 goto err_close;/*XXX: should use err_free_all_ds_namv */
434             }
435 #endif
436
437 #ifdef DEBUG
438             fprintf(stderr, "post fetch %li -- ", i);
439             for (ii = 0; ii < *ds_cnt; ii++)
440                 fprintf(stderr, "%10.2f ", *(data_ptr + ii));
441 #endif
442             data_ptr += *ds_cnt;
443             rra_pointer++;
444         }
445 #ifdef DEBUG
446         fprintf(stderr, "\n");
447 #endif
448
449     }
450 #ifdef HAVE_POSIX_FADVISE
451     /* and just to be sure we drop everything except the header at the end */
452     if (0 !=
453         posix_fadvise(rrd_file->fd, rrd_file->header_len, 0,
454                       POSIX_FADV_DONTNEED)) {
455         rrd_set_error("setting POSIX_FADV_DONTNEED on '%s': %s", filename,
456                       rrd_strerror(errno));
457         goto err_free; /*XXX: should use err_free_all_ds_namv */
458     }
459 #endif
460     rrd_close(rrd_file);
461     return (0);
462 err_free_data:
463     free(*data);
464     *data = NULL;
465 err_free_all_ds_namv:
466     for (i = 0; (unsigned long)i < rrd.stat_head->ds_cnt; ++i)
467         free((*ds_namv)[i]);
468 err_free_ds_namv:
469     free(*ds_namv);
470 err_close:
471     rrd_close(rrd_file);
472 err_free:
473     rrd_free(&rrd);
474     return (-1);
475 }