indent all the rest of the code, and add some typedefs to indent.pro
[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         == -1)
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 HAVE_POSIX_FADVISE
214     long      rrd_head_size;
215 #endif
216
217 #ifdef DEBUG
218     fprintf(stderr, "Entered rrd_fetch_fn() searching for the best match\n");
219     fprintf(stderr, "Looking for: start %10lu end %10lu step %5lu\n",
220             *start, *end, *step);
221 #endif
222
223     rrd_file = rrd_open(filename, &rrd, RRD_READONLY);
224     if (rrd_file == NULL)
225         return (-1);
226
227 #ifdef HAVE_POSIX_FADVISE
228     rrd_head_size = rrd_file->header_len;
229 #endif
230     /* when was the really last update of this file ? */
231
232     if (((*ds_namv) =
233          (char **) malloc(rrd.stat_head->ds_cnt * sizeof(char *))) == NULL) {
234         rrd_set_error("malloc fetch ds_namv array");
235         rrd_free(&rrd);
236         close(rrd_file->fd);
237         return (-1);
238     }
239
240     for (i = 0; (unsigned long) i < rrd.stat_head->ds_cnt; i++) {
241         if ((((*ds_namv)[i]) = malloc(sizeof(char) * DS_NAM_SIZE)) == NULL) {
242             rrd_set_error("malloc fetch ds_namv entry");
243             rrd_free(&rrd);
244             free(*ds_namv);
245             close(rrd_file->fd);
246             return (-1);
247         }
248         strncpy((*ds_namv)[i], rrd.ds_def[i].ds_nam, DS_NAM_SIZE - 1);
249         (*ds_namv)[i][DS_NAM_SIZE - 1] = '\0';
250
251     }
252
253     /* find the rra which best matches the requirements */
254     for (i = 0; (unsigned) i < rrd.stat_head->rra_cnt; i++) {
255         if (cf_conv(rrd.rra_def[i].cf_nam) == cf_idx) {
256
257             cal_end = (rrd.live_head->last_up - (rrd.live_head->last_up
258                                                  % (rrd.rra_def[i].pdp_cnt
259                                                     *
260                                                     rrd.stat_head->
261                                                     pdp_step)));
262             cal_start =
263                 (cal_end -
264                  (rrd.rra_def[i].pdp_cnt * rrd.rra_def[i].row_cnt *
265                   rrd.stat_head->pdp_step));
266
267             full_match = *end - *start;
268 #ifdef DEBUG
269             fprintf(stderr, "Considering: start %10lu end %10lu step %5lu ",
270                     cal_start, cal_end,
271                     rrd.stat_head->pdp_step * rrd.rra_def[i].pdp_cnt);
272 #endif
273             /* we need step difference in either full or partial case */
274             tmp_step_diff = labs(*step - (rrd.stat_head->pdp_step
275                                           * rrd.rra_def[i].pdp_cnt));
276             /* best full match */
277             if (cal_end >= *end && cal_start <= *start) {
278                 if (first_full || (tmp_step_diff < best_full_step_diff)) {
279                     first_full = 0;
280                     best_full_step_diff = tmp_step_diff;
281                     best_full_rra = i;
282 #ifdef DEBUG
283                     fprintf(stderr, "best full match so far\n");
284 #endif
285                 } else {
286 #ifdef DEBUG
287                     fprintf(stderr, "full match, not best\n");
288 #endif
289                 }
290
291             } else {
292                 /* best partial match */
293                 tmp_match = full_match;
294                 if (cal_start > *start)
295                     tmp_match -= (cal_start - *start);
296                 if (cal_end < *end)
297                     tmp_match -= (*end - cal_end);
298                 if (first_part ||
299                     (best_match < tmp_match) ||
300                     (best_match == tmp_match &&
301                      tmp_step_diff < best_part_step_diff)) {
302 #ifdef DEBUG
303                     fprintf(stderr, "best partial so far\n");
304 #endif
305                     first_part = 0;
306                     best_match = tmp_match;
307                     best_part_step_diff = tmp_step_diff;
308                     best_part_rra = i;
309                 } else {
310 #ifdef DEBUG
311                     fprintf(stderr, "partial match, not best\n");
312 #endif
313                 }
314             }
315         }
316     }
317
318     /* lets see how the matching went. */
319     if (first_full == 0)
320         chosen_rra = best_full_rra;
321     else if (first_part == 0)
322         chosen_rra = best_part_rra;
323     else {
324         rrd_set_error
325             ("the RRD does not contain an RRA matching the chosen CF");
326         rrd_free(&rrd);
327         close(rrd_file->fd);
328         return (-1);
329     }
330
331     /* set the wish parameters to their real values */
332     *step = rrd.stat_head->pdp_step * rrd.rra_def[chosen_rra].pdp_cnt;
333     *start -= (*start % *step);
334     *end += (*step - *end % *step);
335     rows = (*end - *start) / *step + 1;
336
337 #ifdef DEBUG
338     fprintf(stderr,
339             "We found:    start %10lu end %10lu step %5lu rows  %lu\n",
340             *start, *end, *step, rows);
341 #endif
342
343 /* Start and end are now multiples of the step size.  The amount of
344 ** steps we want is (end-start)/step and *not* an extra one.
345 ** Reasoning:  if step is s and we want to graph from t to t+s,
346 ** we need exactly ((t+s)-t)/s rows.  The row to collect from the
347 ** database is the one with time stamp (t+s) which means t to t+s.
348 */
349     *ds_cnt = rrd.stat_head->ds_cnt;
350     if (((*data) = malloc(*ds_cnt * rows * sizeof(rrd_value_t))) == NULL) {
351         rrd_set_error("malloc fetch data area");
352         for (i = 0; (unsigned long) i < *ds_cnt; i++)
353             free((*ds_namv)[i]);
354         free(*ds_namv);
355         rrd_free(&rrd);
356         close(rrd_file->fd);
357         return (-1);
358     }
359
360     data_ptr = (*data);
361
362     /* find base address of rra */
363     rra_base = rrd_file->header_len;
364     for (i = 0; i < chosen_rra; i++)
365         rra_base += (*ds_cnt * rrd.rra_def[i].row_cnt * sizeof(rrd_value_t));
366
367     /* find start and end offset */
368     rra_end_time = (rrd.live_head->last_up
369                     - (rrd.live_head->last_up % *step));
370     rra_start_time = (rra_end_time
371                       - (*step * (rrd.rra_def[chosen_rra].row_cnt - 1)));
372     /* here's an error by one if we don't be careful */
373     start_offset = (long) (*start + *step - rra_start_time) / (long) *step;
374     end_offset = (long) (rra_end_time - *end) / (long) *step;
375 #ifdef DEBUG
376     fprintf(stderr,
377             "rra_start %lu, rra_end %lu, start_off %li, end_off %li\n",
378             rra_start_time, rra_end_time, start_offset, end_offset);
379 #endif
380
381     /* fill the gap at the start if needs be */
382
383     if (start_offset <= 0)
384         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1;
385     else
386         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1 + start_offset;
387
388     if (rrd_seek(rrd_file, (rra_base
389                             + (rra_pointer
390                                * *ds_cnt
391                                * sizeof(rrd_value_t))), SEEK_SET) != 0) {
392         rrd_set_error("seek error in RRA");
393         for (i = 0; (unsigned) i < *ds_cnt; i++)
394             free((*ds_namv)[i]);
395         free(*ds_namv);
396         rrd_free(&rrd);
397         free(*data);
398         *data = NULL;
399         close(rrd_file->fd);
400         return (-1);
401
402     }
403 #ifdef DEBUG
404     fprintf(stderr, "First Seek: rra_base %lu rra_pointer %lu\n",
405             rra_base, rra_pointer);
406 #endif
407     /* step trough the array */
408
409     for (i = start_offset;
410          i < (signed) rrd.rra_def[chosen_rra].row_cnt - end_offset; i++) {
411         /* no valid data yet */
412         if (i < 0) {
413 #ifdef DEBUG
414             fprintf(stderr, "pre fetch %li -- ", i);
415 #endif
416             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
417                 *(data_ptr++) = DNAN;
418 #ifdef DEBUG
419                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
420 #endif
421             }
422         }
423         /* past the valid data area */
424         else if (i >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
425 #ifdef DEBUG
426             fprintf(stderr, "post fetch %li -- ", i);
427 #endif
428             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
429                 *(data_ptr++) = DNAN;
430 #ifdef DEBUG
431                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
432 #endif
433             }
434         } else {
435             /* OK we are inside the valid area but the pointer has to 
436              * be wrapped*/
437             if (rra_pointer >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
438                 rra_pointer -= rrd.rra_def[chosen_rra].row_cnt;
439                 if (rrd_seek(rrd_file, (rra_base + rra_pointer
440                                         * *ds_cnt
441                                         * sizeof(rrd_value_t)),
442                              SEEK_SET) != 0) {
443                     rrd_set_error("wrap seek in RRA did fail");
444                     for (ii = 0; (unsigned) ii < *ds_cnt; ii++)
445                         free((*ds_namv)[ii]);
446                     free(*ds_namv);
447                     rrd_free(&rrd);
448                     free(*data);
449                     *data = NULL;
450                     close(rrd_file->fd);
451                     return (-1);
452                 }
453 #ifdef DEBUG
454                 fprintf(stderr, "wrap seek ...\n");
455 #endif
456             }
457
458             if (rrd_read(rrd_file, data_ptr, sizeof(rrd_value_t) * (*ds_cnt))
459                 != (ssize_t) (sizeof(rrd_value_t) * (*ds_cnt) *
460                               rrd.stat_head->ds_cnt)) {
461                 rrd_set_error("fetching cdp from rra");
462                 for (ii = 0; (unsigned) ii < *ds_cnt; ii++)
463                     free((*ds_namv)[ii]);
464                 free(*ds_namv);
465                 rrd_free(&rrd);
466                 free(*data);
467                 *data = NULL;
468                 close(rrd_file->fd);
469                 return (-1);
470             }
471 #ifdef HAVE_POSIX_FADVISE
472             /* don't pollute the buffer cache with data read from the file. We do this while reading to 
473                keep damage minimal */
474             if (0 !=
475                 posix_fadvise(rrd_file->fd, rrd_head_size, 0,
476                               POSIX_FADV_DONTNEED)) {
477                 rrd_set_error("setting POSIX_FADV_DONTNEED on '%s': %s",
478                               filename, rrd_strerror(errno));
479                 close(rrd_file->fd);
480                 return (-1);
481             }
482 #endif
483
484 #ifdef DEBUG
485             fprintf(stderr, "post fetch %li -- ", i);
486             for (ii = 0; ii < *ds_cnt; ii++)
487                 fprintf(stderr, "%10.2f ", *(data_ptr + ii));
488 #endif
489             data_ptr += *ds_cnt;
490             rra_pointer++;
491         }
492 #ifdef DEBUG
493         fprintf(stderr, "\n");
494 #endif
495
496     }
497     rrd_free(&rrd);
498 #ifdef HAVE_POSIX_FADVISE
499     /* and just to be sure we drop everything except the header at the end */
500     if (0 !=
501         posix_fadvise(rrd_file->fd, rrd_head_size, 0, POSIX_FADV_DONTNEED)) {
502         rrd_set_error("setting POSIX_FADV_DONTNEED on '%s': %s", filename,
503                       rrd_strerror(errno));
504         close(rrd_file->fd);
505         return (-1);
506     }
507 #endif
508     close(rrd_file->fd);
509     return (0);
510 }