src/rrd_{fetch,graph}.c: Implement `--daemon'.
[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     cf = argv[optind + 1];
170
171     if (rrd_fetch_r(argv[optind], cf, start, end, step, daemon, ds_cnt,
172                             ds_namv, data) != 0)
173         return (-1);
174     return (0);
175 }
176
177 int rrd_fetch_r(
178     const char *filename,   /* name of the rrd */
179     const char *cf,     /* which consolidation function ? */
180     time_t *start,
181     time_t *end,        /* which time frame do you want ?
182                          * will be changed to represent reality */
183     unsigned long *step,    /* which stepsize do you want? 
184                              * will be changed to represent reality */
185     const char *daemon,
186     unsigned long *ds_cnt,  /* number of data sources in file */
187     char ***ds_namv,    /* names of data_sources */
188     rrd_value_t **data)
189 {                       /* two dimensional array containing the data */
190     enum cf_en cf_idx;
191     int status;
192
193     if ((int) (cf_idx = cf_conv(cf)) == -1) {
194         return -1;
195     }
196
197     if (daemon != NULL)
198     {
199         status = rrdc_connect (daemon);
200         if (status != 0)
201         {
202             rrd_set_error ("rrdc_connect failed with status %i.", status);
203             return (-1);
204         }
205     }
206
207     status = rrd_fetch_fn (filename, cf_idx, start, end, step,
208             (daemon == NULL) ? 0 : 1,
209             ds_cnt, ds_namv, data);
210
211     rrdc_disconnect ();
212
213     return (status);
214 } /* int rrd_fetch_r */
215
216 int rrd_fetch_fn(
217     const char *filename,   /* name of the rrd */
218     enum cf_en cf_idx,  /* which consolidation function ? */
219     time_t *start,
220     time_t *end,        /* which time frame do you want ?
221                          * will be changed to represent reality */
222     unsigned long *step,    /* which stepsize do you want? 
223                              * will be changed to represent reality */
224     int use_rrdcached,
225     unsigned long *ds_cnt,  /* number of data sources in file */
226     char ***ds_namv,    /* names of data_sources */
227     rrd_value_t **data)
228 {                       /* two dimensional array containing the data */
229     long      i, ii;
230     time_t    cal_start, cal_end, rra_start_time, rra_end_time;
231     long      best_full_rra = 0, best_part_rra = 0, chosen_rra =
232         0, rra_pointer = 0;
233     long      best_full_step_diff = 0, best_part_step_diff =
234         0, tmp_step_diff = 0, tmp_match = 0, best_match = 0;
235     long      full_match, rra_base;
236     long      start_offset, end_offset;
237     int       first_full = 1;
238     int       first_part = 1;
239     rrd_t     rrd;
240     rrd_file_t *rrd_file;
241     rrd_value_t *data_ptr;
242     unsigned long rows;
243
244     if (use_rrdcached)
245     {
246         int status;
247
248         status = rrdc_flush (filename);
249         if (status != 0)
250         {
251             rrd_set_error ("rrdc_flush failed with status %i.", status);
252             return (-1);
253         }
254     }
255
256 #ifdef DEBUG
257     fprintf(stderr, "Entered rrd_fetch_fn() searching for the best match\n");
258     fprintf(stderr, "Looking for: start %10lu end %10lu step %5lu\n",
259             *start, *end, *step);
260 #endif
261
262     rrd_file = rrd_open(filename, &rrd, RRD_READONLY);
263     if (rrd_file == NULL)
264         goto err_free;
265
266     /* when was the really last update of this file ? */
267
268     if (((*ds_namv) =
269          (char **) malloc(rrd.stat_head->ds_cnt * sizeof(char *))) == NULL) {
270         rrd_set_error("malloc fetch ds_namv array");
271         goto err_close;
272     }
273
274     for (i = 0; (unsigned long) i < rrd.stat_head->ds_cnt; i++) {
275         if ((((*ds_namv)[i]) = malloc(sizeof(char) * DS_NAM_SIZE)) == NULL) {
276             rrd_set_error("malloc fetch ds_namv entry");
277             goto err_free_ds_namv;
278         }
279         strncpy((*ds_namv)[i], rrd.ds_def[i].ds_nam, DS_NAM_SIZE - 1);
280         (*ds_namv)[i][DS_NAM_SIZE - 1] = '\0';
281
282     }
283
284     /* find the rra which best matches the requirements */
285     for (i = 0; (unsigned) i < rrd.stat_head->rra_cnt; i++) {
286         if (cf_conv(rrd.rra_def[i].cf_nam) == cf_idx) {
287
288             cal_end = (rrd.live_head->last_up - (rrd.live_head->last_up
289                                                  % (rrd.rra_def[i].pdp_cnt
290                                                     *
291                                                     rrd.stat_head->
292                                                     pdp_step)));
293             cal_start =
294                 (cal_end -
295                  (rrd.rra_def[i].pdp_cnt * rrd.rra_def[i].row_cnt *
296                   rrd.stat_head->pdp_step));
297
298             full_match = *end - *start;
299 #ifdef DEBUG
300             fprintf(stderr, "Considering: start %10lu end %10lu step %5lu ",
301                     cal_start, cal_end,
302                     rrd.stat_head->pdp_step * rrd.rra_def[i].pdp_cnt);
303 #endif
304             /* we need step difference in either full or partial case */
305             tmp_step_diff = labs(*step - (rrd.stat_head->pdp_step
306                                           * rrd.rra_def[i].pdp_cnt));
307             /* best full match */
308             if (cal_start <= *start) {
309                 if (first_full || (tmp_step_diff < best_full_step_diff)) {
310                     first_full = 0;
311                     best_full_step_diff = tmp_step_diff;
312                     best_full_rra = i;
313 #ifdef DEBUG
314                     fprintf(stderr, "best full match so far\n");
315                 } else {
316                     fprintf(stderr, "full match, not best\n");
317 #endif
318                 }
319
320             } else {
321                 /* best partial match */
322                 tmp_match = full_match;
323                 if (cal_start > *start)
324                     tmp_match -= (cal_start - *start);
325                 if (first_part ||
326                     (best_match < tmp_match) ||
327                     (best_match == tmp_match &&
328                      tmp_step_diff < best_part_step_diff)) {
329 #ifdef DEBUG
330                     fprintf(stderr, "best partial so far\n");
331 #endif
332                     first_part = 0;
333                     best_match = tmp_match;
334                     best_part_step_diff = tmp_step_diff;
335                     best_part_rra = i;
336                 } else {
337 #ifdef DEBUG
338                     fprintf(stderr, "partial match, not best\n");
339 #endif
340                 }
341             }
342         }
343     }
344
345     /* lets see how the matching went. */
346     if (first_full == 0)
347         chosen_rra = best_full_rra;
348     else if (first_part == 0)
349         chosen_rra = best_part_rra;
350     else {
351         rrd_set_error
352             ("the RRD does not contain an RRA matching the chosen CF");
353         goto err_free_all_ds_namv;
354     }
355
356     /* set the wish parameters to their real values */
357     *step = rrd.stat_head->pdp_step * rrd.rra_def[chosen_rra].pdp_cnt;
358     *start -= (*start % *step);
359     *end += (*step - *end % *step);
360     rows = (*end - *start) / *step + 1;
361
362 #ifdef DEBUG
363     fprintf(stderr,
364             "We found:    start %10lu end %10lu step %5lu rows  %lu\n",
365             *start, *end, *step, rows);
366 #endif
367
368 /* Start and end are now multiples of the step size.  The amount of
369 ** steps we want is (end-start)/step and *not* an extra one.
370 ** Reasoning:  if step is s and we want to graph from t to t+s,
371 ** we need exactly ((t+s)-t)/s rows.  The row to collect from the
372 ** database is the one with time stamp (t+s) which means t to t+s.
373 */
374     *ds_cnt = rrd.stat_head->ds_cnt;
375     if (((*data) = malloc(*ds_cnt * rows * sizeof(rrd_value_t))) == NULL) {
376         rrd_set_error("malloc fetch data area");
377         goto err_free_all_ds_namv;
378     }
379
380     data_ptr = (*data);
381
382     /* find base address of rra */
383     rra_base = rrd_file->header_len;
384     for (i = 0; i < chosen_rra; i++)
385         rra_base += (*ds_cnt * rrd.rra_def[i].row_cnt * sizeof(rrd_value_t));
386
387     /* find start and end offset */
388     rra_end_time = (rrd.live_head->last_up
389                     - (rrd.live_head->last_up % *step));
390     rra_start_time = (rra_end_time
391                       - (*step * (rrd.rra_def[chosen_rra].row_cnt - 1)));
392     /* here's an error by one if we don't be careful */
393     start_offset = (long) (*start + *step - rra_start_time) / (long) *step;
394     end_offset = (long) (rra_end_time - *end) / (long) *step;
395 #ifdef DEBUG
396     fprintf(stderr,
397             "rra_start %lu, rra_end %lu, start_off %li, end_off %li\n",
398             rra_start_time, rra_end_time, start_offset, end_offset);
399 #endif
400
401     /* fill the gap at the start if needs be */
402
403     if (start_offset <= 0)
404         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1;
405     else
406         rra_pointer = rrd.rra_ptr[chosen_rra].cur_row + 1 + start_offset;
407
408     if (rrd_seek(rrd_file, (rra_base + (rra_pointer * (*ds_cnt)
409                                         * sizeof(rrd_value_t))),
410                  SEEK_SET) != 0) {
411         rrd_set_error("seek error in RRA");
412         goto err_free_data;
413     }
414 #ifdef DEBUG
415     fprintf(stderr, "First Seek: rra_base %lu rra_pointer %lu\n",
416             rra_base, rra_pointer);
417 #endif
418     /* step trough the array */
419
420     for (i = start_offset;
421          i < (signed) rrd.rra_def[chosen_rra].row_cnt - end_offset; i++) {
422         /* no valid data yet */
423         if (i < 0) {
424 #ifdef DEBUG
425             fprintf(stderr, "pre fetch %li -- ", i);
426 #endif
427             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
428                 *(data_ptr++) = DNAN;
429 #ifdef DEBUG
430                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
431 #endif
432             }
433         }
434         /* past the valid data area */
435         else if (i >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
436 #ifdef DEBUG
437             fprintf(stderr, "past fetch %li -- ", i);
438 #endif
439             for (ii = 0; (unsigned) ii < *ds_cnt; ii++) {
440                 *(data_ptr++) = DNAN;
441 #ifdef DEBUG
442                 fprintf(stderr, "%10.2f ", *(data_ptr - 1));
443 #endif
444             }
445         } else {
446             /* OK we are inside the valid area but the pointer has to 
447              * be wrapped*/
448             if (rra_pointer >= (signed) rrd.rra_def[chosen_rra].row_cnt) {
449                 rra_pointer -= rrd.rra_def[chosen_rra].row_cnt;
450                 if (rrd_seek(rrd_file, (rra_base + rra_pointer * (*ds_cnt)
451                                         * sizeof(rrd_value_t)),
452                              SEEK_SET) != 0) {
453                     rrd_set_error("wrap seek in RRA did fail");
454                     goto err_free_data;
455                 }
456 #ifdef DEBUG
457                 fprintf(stderr, "wrap seek ...\n");
458 #endif
459             }
460
461             if (rrd_read(rrd_file, data_ptr, sizeof(rrd_value_t) * (*ds_cnt))
462                 != (ssize_t) (sizeof(rrd_value_t) * (*ds_cnt))) {
463                 rrd_set_error("fetching cdp from rra");
464                 goto err_free_data;
465             }
466 #ifdef DEBUG
467             fprintf(stderr, "post fetch %li -- ", i);
468             for (ii = 0; ii < *ds_cnt; ii++)
469                 fprintf(stderr, "%10.2f ", *(data_ptr + ii));
470 #endif
471             data_ptr += *ds_cnt;
472             rra_pointer++;
473         }
474 #ifdef DEBUG
475         fprintf(stderr, "\n");
476 #endif
477
478     }
479
480     rrd_close(rrd_file);
481     return (0);
482   err_free_data:
483     free(*data);
484     *data = NULL;
485   err_free_all_ds_namv:
486     for (i = 0; (unsigned long) i < rrd.stat_head->ds_cnt; ++i)
487         free((*ds_namv)[i]);
488   err_free_ds_namv:
489     free(*ds_namv);
490   err_close:
491     rrd_close(rrd_file);
492   err_free:
493     rrd_free(&rrd);
494     return (-1);
495 }