fix off by 1 error
[rrdtool.git] / src / rrd_fetch.c
1 /*****************************************************************************
2  * RRDtool 1.4.3  Copyright by Tobi Oetiker, 1997-2010
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 #include "rrd_client.h"
57
58 #include "rrd_is_thread_safe.h"
59 /* #define DEBUG */
60
61 int rrd_fetch(
62     int argc,
63     char **argv,
64     time_t *start,
65     time_t *end,        /* which time frame do you want ?
66                          * will be changed to represent reality */
67     unsigned long *step,    /* which stepsize do you want? 
68                              * will be changed to represent reality */
69     unsigned long *ds_cnt,  /* number of data sources in file */
70     char ***ds_namv,    /* names of data sources */
71     rrd_value_t **data)
72 {                       /* two dimensional array containing the data */
73     long      step_tmp = 1;
74     time_t    start_tmp = 0, end_tmp = 0;
75     const char *cf;
76     char *opt_daemon = NULL;
77     int status;
78
79     rrd_time_value_t start_tv, end_tv;
80     char     *parsetime_error = NULL;
81     struct option long_options[] = {
82         {"resolution", required_argument, 0, 'r'},
83         {"start", required_argument, 0, 's'},
84         {"end", required_argument, 0, 'e'},
85         {"daemon", required_argument, 0, 'd'},
86         {0, 0, 0, 0}
87     };
88
89     optind = 0;
90     opterr = 0;         /* initialize getopt */
91
92     /* init start and end time */
93     rrd_parsetime("end-24h", &start_tv);
94     rrd_parsetime("now", &end_tv);
95
96     while (1) {
97         int       option_index = 0;
98         int       opt;
99
100         opt = getopt_long(argc, argv, "r:s:e:d:", long_options, &option_index);
101
102         if (opt == EOF)
103             break;
104
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
122         case 'd':
123             if (opt_daemon != NULL)
124                     free (opt_daemon);
125             opt_daemon = strdup (optarg);
126             if (opt_daemon == NULL)
127             {
128                 rrd_set_error ("strdup failed.");
129                 return (-1);
130             }
131             break;
132
133         case '?':
134             rrd_set_error("unknown option '-%c'", optopt);
135             return (-1);
136         }
137     }
138
139
140     if (rrd_proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
141         return -1;
142     }
143
144
145     if (start_tmp < 3600 * 24 * 365 * 10) {
146         rrd_set_error("the first entry to fetch should be after 1980");
147         return (-1);
148     }
149
150     if (end_tmp < start_tmp) {
151         rrd_set_error("start (%ld) should be less than end (%ld)", start_tmp,
152                       end_tmp);
153         return (-1);
154     }
155
156     *start = start_tmp;
157     *end = end_tmp;
158
159     if (step_tmp < 1) {
160         rrd_set_error("step must be >= 1 second");
161         return -1;
162     }
163     *step = step_tmp;
164
165     if (optind + 1 >= argc) {
166         rrd_set_error("Usage: rrdtool %s <file> <CF> [options]", argv[0]);
167         return -1;
168     }
169
170     cf = argv[optind + 1];
171
172     rrdc_connect (opt_daemon);
173     if (rrdc_is_connected (opt_daemon))
174             status = rrdc_fetch (argv[optind], cf, start, end, step,
175                             ds_cnt, ds_namv, data);
176
177     else
178             status = rrd_fetch_r(argv[optind], cf, start, end, step,
179                             ds_cnt, ds_namv, data);
180
181     if (status != 0)
182         return (-1);
183     return (0);
184 }
185
186 int rrd_fetch_r(
187     const char *filename,   /* name of the rrd */
188     const char *cf,     /* 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     enum cf_en cf_idx;
199
200     if ((int) (cf_idx = cf_conv(cf)) == -1) {
201         return -1;
202     }
203
204     return (rrd_fetch_fn
205             (filename, cf_idx, start, end, step, ds_cnt, ds_namv, data));
206 } /* int rrd_fetch_r */
207
208 int rrd_fetch_fn(
209     const char *filename,   /* name of the rrd */
210     enum cf_en cf_idx,  /* which consolidation function ? */
211     time_t *start,
212     time_t *end,        /* which time frame do you want ?
213                          * will be changed to represent reality */
214     unsigned long *step,    /* which stepsize do you want? 
215                              * will be changed to represent reality */
216     unsigned long *ds_cnt,  /* number of data sources in file */
217     char ***ds_namv,    /* names of data_sources */
218     rrd_value_t **data)
219 {                       /* two dimensional array containing the data */
220     long      i, ii;
221     time_t    cal_start, cal_end, rra_start_time, rra_end_time;
222     long      best_full_rra = 0, best_part_rra = 0, chosen_rra =
223         0, rra_pointer = 0;
224     long      best_full_step_diff = 0, best_part_step_diff =
225         0, tmp_step_diff = 0, tmp_match = 0, best_match = 0;
226     long      full_match, rra_base;
227     off_t     start_offset, end_offset;
228     int       first_full = 1;
229     int       first_part = 1;
230     rrd_t     rrd;
231     rrd_file_t *rrd_file;
232     rrd_value_t *data_ptr;
233     unsigned long rows;
234
235 #ifdef DEBUG
236     fprintf(stderr, "Entered rrd_fetch_fn() searching for the best match\n");
237     fprintf(stderr, "Looking for: start %10lu end %10lu step %5lu\n",
238             *start, *end, *step);
239 #endif
240
241 #ifdef HAVE_LIBDBI
242     /* handle libdbi datasources */
243     if (strncmp("sql//",filename,5)==0) {
244         return rrd_fetch_fn_libdbi(filename,cf_idx,start,end,step,ds_cnt,ds_namv,data);
245     }
246 #endif
247
248     rrd_init(&rrd);
249     rrd_file = rrd_open(filename, &rrd, RRD_READONLY);
250     if (rrd_file == NULL)
251         goto err_free;
252
253     /* when was the really last update of this file ? */
254
255     if (((*ds_namv) =
256          (char **) malloc(rrd.stat_head->ds_cnt * sizeof(char *))) == NULL) {
257         rrd_set_error("malloc fetch ds_namv array");
258         goto err_close;
259     }
260
261     for (i = 0; (unsigned long) i < rrd.stat_head->ds_cnt; i++) {
262         if ((((*ds_namv)[i]) = (char*)malloc(sizeof(char) * DS_NAM_SIZE)) == NULL) {
263             rrd_set_error("malloc fetch ds_namv entry");
264             goto err_free_ds_namv;
265         }
266         strncpy((*ds_namv)[i], rrd.ds_def[i].ds_nam, DS_NAM_SIZE - 1);
267         (*ds_namv)[i][DS_NAM_SIZE - 1] = '\0';
268
269     }
270
271     /* find the rra which best matches the requirements */
272     for (i = 0; (unsigned) i < rrd.stat_head->rra_cnt; i++) {
273       enum cf_en rratype=cf_conv(rrd.rra_def[i].cf_nam);
274       /* handle this RRA */
275       if (
276           /* if we found a direct match */
277           (rratype == cf_idx)
278           || 
279           /*if we found a DS with interval 1 
280             and CF (requested,available) are MIN,MAX,AVERAGE,LAST
281           */
282           ( 
283               /* only if we are on interval 1 */
284               (rrd.rra_def[i].pdp_cnt==1) 
285               && ( 
286                   /* and requested CF is MIN,MAX,AVERAGE,LAST */
287                   (cf_idx == CF_MINIMUM)
288                   ||(cf_idx == CF_MAXIMUM)
289                   ||(cf_idx == CF_AVERAGE)
290                   ||(cf_idx == CF_LAST)
291                   )
292               && (
293                   /* and found CF is MIN,MAX,AVERAGE,LAST */
294                   (rratype == CF_MINIMUM)
295                   ||(rratype == CF_MAXIMUM)
296                   ||(rratype == CF_AVERAGE)
297                   ||(rratype == CF_LAST)
298                   )
299               )
300           ){
301
302             cal_end = (rrd.live_head->last_up - (rrd.live_head->last_up
303                                                  % (rrd.rra_def[i].pdp_cnt
304                                                     *
305                                                     rrd.stat_head->
306                                                     pdp_step)));
307             cal_start =
308                 (cal_end -
309                  (rrd.rra_def[i].pdp_cnt * rrd.rra_def[i].row_cnt *
310                   rrd.stat_head->pdp_step));
311
312             full_match = *end - *start;
313 #ifdef DEBUG
314             fprintf(stderr, "Considering: start %10lu end %10lu step %5lu ",
315                     cal_start, cal_end,
316                     rrd.stat_head->pdp_step * rrd.rra_def[i].pdp_cnt);
317 #endif
318             /* we need step difference in either full or partial case */
319             tmp_step_diff = labs(*step - (rrd.stat_head->pdp_step
320                                           * rrd.rra_def[i].pdp_cnt));
321             /* best full match */
322             if (cal_start <= *start) {
323                 if (first_full || (tmp_step_diff < best_full_step_diff)) {
324                     first_full = 0;
325                     best_full_step_diff = tmp_step_diff;
326                     best_full_rra = i;
327 #ifdef DEBUG
328                     fprintf(stderr, "best full match so far\n");
329                 } else {
330                     fprintf(stderr, "full match, not best\n");
331 #endif
332                 }
333
334             } else {
335                 /* best partial match */
336                 tmp_match = full_match;
337                 if (cal_start > *start)
338                     tmp_match -= (cal_start - *start);
339                 if (first_part ||
340                     (best_match < tmp_match) ||
341                     (best_match == tmp_match &&
342                      tmp_step_diff < best_part_step_diff)) {
343 #ifdef DEBUG
344                     fprintf(stderr, "best partial so far\n");
345 #endif
346                     first_part = 0;
347                     best_match = tmp_match;
348                     best_part_step_diff = tmp_step_diff;
349                     best_part_rra = i;
350                 } else {
351 #ifdef DEBUG
352                     fprintf(stderr, "partial match, not best\n");
353 #endif
354                 }
355             }
356         }
357     }
358
359     /* lets see how the matching went. */
360     if (first_full == 0)
361         chosen_rra = best_full_rra;
362     else if (first_part == 0)
363         chosen_rra = best_part_rra;
364     else {
365         rrd_set_error
366             ("the RRD does not contain an RRA matching the chosen CF");
367         goto err_free_all_ds_namv;
368     }
369
370     /* set the wish parameters to their real values */
371     *step = rrd.stat_head->pdp_step * rrd.rra_def[chosen_rra].pdp_cnt;
372     *start -= (*start % *step);
373     *end += (*step - *end % *step);
374     rows = (*end - *start) / *step + 1;
375
376 #ifdef DEBUG
377     fprintf(stderr,
378             "We found:    start %10lu end %10lu step %5lu rows  %lu\n",
379             *start, *end, *step, rows);
380 #endif
381
382 /* Start and end are now multiples of the step size.  The amount of
383 ** steps we want is (end-start)/step and *not* an extra one.
384 ** Reasoning:  if step is s and we want to graph from t to t+s,
385 ** we need exactly ((t+s)-t)/s rows.  The row to collect from the
386 ** database is the one with time stamp (t+s) which means t to t+s.
387 */
388     *ds_cnt = rrd.stat_head->ds_cnt;
389     if (((*data) = (rrd_value_t*)malloc(*ds_cnt * rows * sizeof(rrd_value_t))) == NULL) {
390         rrd_set_error("malloc fetch data area");
391         goto err_free_all_ds_namv;
392     }
393
394     data_ptr = (*data);
395
396     /* find base address of rra */
397     rra_base = rrd_file->header_len;
398     for (i = 0; i < chosen_rra; i++)
399         rra_base += (*ds_cnt * rrd.rra_def[i].row_cnt * sizeof(rrd_value_t));
400
401     /* find start and end offset */
402     rra_end_time = (rrd.live_head->last_up
403                     - (rrd.live_head->last_up % *step));
404     rra_start_time = (rra_end_time
405                       - (*step * (rrd.rra_def[chosen_rra].row_cnt - 1)));
406     /* here's an error by one if we don't be careful */
407     start_offset = (long) (*start + *step - rra_start_time) / (long) *step;
408     end_offset = (long) (rra_end_time - *end) / (long) *step;
409 #ifdef DEBUG
410     fprintf(stderr,
411             "rra_start %lu, rra_end %lu, start_off %li, end_off %li\n",
412             rra_start_time, rra_end_time, start_offset, end_offset);
413 #endif
414     /* only seek if the start time is before the end time */
415     if (*start <= rra_end_time && *end >= rra_start_time - (off_t)*step ){
416         if (start_offset <= 0)
417             rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1;
418         else
419             rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1 + start_offset;
420
421         rra_pointer = rra_pointer % (signed) rrd.rra_def[chosen_rra].row_cnt;
422          
423         if (rrd_seek(rrd_file, (rra_base + (rra_pointer * (*ds_cnt)
424                                         * sizeof(rrd_value_t))),
425                  SEEK_SET) != 0) {
426             rrd_set_error("seek error in RRA");
427             goto err_free_data;
428         }
429 #ifdef DEBUG
430         fprintf(stderr, "First Seek: rra_base %lu rra_pointer %lu\n",
431                 rra_base, rra_pointer);
432 #endif
433     }
434     
435     /* step trough the array */
436
437     for (i = start_offset;
438          i < (signed) rrd.rra_def[chosen_rra].row_cnt - end_offset; i++) {
439         /* no valid data yet */
440         if (i < 0) {
441 #ifdef DEBUG
442             fprintf(stderr, "pre fetch %li -- ", i);
443 #endif
444             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
445                 *(data_ptr++) = DNAN;
446 #ifdef DEBUG
447                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
448 #endif
449             }
450         }
451         /* past the valid data area */
452         else if (i >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
453 #ifdef DEBUG
454             fprintf(stderr, "past fetch %li -- ", i);
455 #endif
456             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
457                 *(data_ptr++) = DNAN;
458 #ifdef DEBUG
459                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
460 #endif
461             }
462         } else {
463             /* OK we are inside the valid area but the pointer has to 
464              * be wrapped*/
465             if (rra_pointer >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
466                 rra_pointer -= rrd.rra_def[chosen_rra].row_cnt;
467                 if (rrd_seek(rrd_file, (rra_base + rra_pointer * (*ds_cnt)
468                                         * sizeof(rrd_value_t)),
469                              SEEK_SET) != 0) {
470                     rrd_set_error("wrap seek in RRA did fail");
471                     goto err_free_data;
472                 }
473 #ifdef DEBUG
474                 fprintf(stderr, "wrap seek ...\n");
475 #endif
476             }
477
478             if (rrd_read(rrd_file, data_ptr, sizeof(rrd_value_t) * (*ds_cnt))
479                 != (ssize_t) (sizeof(rrd_value_t) * (*ds_cnt))) {
480                 rrd_set_error("fetching cdp from rra");
481                 goto err_free_data;
482             }
483 #ifdef DEBUG
484             fprintf(stderr, "post fetch %li -- ", i);
485             for (ii = 0; ii < *ds_cnt; ii++)
486                 fprintf(stderr, "%10.2f ", *(data_ptr + ii));
487 #endif
488             data_ptr += *ds_cnt;
489             rra_pointer++;
490         }
491 #ifdef DEBUG
492         fprintf(stderr, "\n");
493 #endif
494
495     }
496
497     rrd_close(rrd_file);
498     rrd_free(&rrd);
499     return (0);
500   err_free_data:
501     free(*data);
502     *data = NULL;
503   err_free_all_ds_namv:
504     for (i = 0; (unsigned long) i < rrd.stat_head->ds_cnt; ++i)
505         free((*ds_namv)[i]);
506   err_free_ds_namv:
507     free(*ds_namv);
508   err_close:
509     rrd_close(rrd_file);
510   err_free:
511     rrd_free(&rrd);
512     return (-1);
513 }