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