flip check for row_count with setting for better code logic
[rrdtool.git] / src / rrd_create.c
1 /*****************************************************************************
2  * RRDtool 1.3rc9  Copyright by Tobi Oetiker, 1997-2008
3  *****************************************************************************
4  * rrd_create.c  creates new rrds
5  *****************************************************************************/
6
7 #include <stdlib.h>
8 #include <time.h>
9 #include <locale.h>
10
11 #include "rrd_tool.h"
12 #include "rrd_rpncalc.h"
13 #include "rrd_hw.h"
14
15 #include "rrd_is_thread_safe.h"
16
17 unsigned long FnvHash(
18     const char *str);
19 int       create_hw_contingent_rras(
20     rrd_t *rrd,
21     unsigned short period,
22     unsigned long hashed_name);
23 void      parseGENERIC_DS(
24     const char *def,
25     rrd_t *rrd,
26     int ds_idx);
27 long int  rra_random_row(
28     rra_def_t *);
29
30 int rrd_create(
31     int argc,
32     char **argv)
33 {
34     struct option long_options[] = {
35         {"start", required_argument, 0, 'b'},
36         {"step", required_argument, 0, 's'},
37         {0, 0, 0, 0}
38     };
39     int       option_index = 0;
40     int       opt;
41     time_t    last_up = time(NULL) - 10;
42     unsigned long pdp_step = 300;
43     rrd_time_value_t last_up_tv;
44     char     *parsetime_error = NULL;
45     long      long_tmp;
46     int       rc;
47
48     optind = 0;
49     opterr = 0;         /* initialize getopt */
50
51     while (1) {
52         opt = getopt_long(argc, argv, "b:s:", long_options, &option_index);
53
54         if (opt == EOF)
55             break;
56
57         switch (opt) {
58         case 'b':
59             if ((parsetime_error = rrd_parsetime(optarg, &last_up_tv))) {
60                 rrd_set_error("start time: %s", parsetime_error);
61                 return (-1);
62             }
63             if (last_up_tv.type == RELATIVE_TO_END_TIME ||
64                 last_up_tv.type == RELATIVE_TO_START_TIME) {
65                 rrd_set_error("specifying time relative to the 'start' "
66                               "or 'end' makes no sense here");
67                 return (-1);
68             }
69
70             last_up = mktime(&last_up_tv.tm) +last_up_tv.offset;
71
72             if (last_up < 3600 * 24 * 365 * 10) {
73                 rrd_set_error
74                     ("the first entry to the RRD should be after 1980");
75                 return (-1);
76             }
77             break;
78
79         case 's':
80             long_tmp = atol(optarg);
81             if (long_tmp < 1) {
82                 rrd_set_error("step size should be no less than one second");
83                 return (-1);
84             }
85             pdp_step = long_tmp;
86             break;
87
88         case '?':
89             if (optopt != 0)
90                 rrd_set_error("unknown option '%c'", optopt);
91             else
92                 rrd_set_error("unknown option '%s'", argv[optind - 1]);
93             return (-1);
94         }
95     }
96     if (optind == argc) {
97         rrd_set_error("need name of an rrd file to create");
98         return -1;
99     }
100     rc = rrd_create_r(argv[optind],
101                       pdp_step, last_up,
102                       argc - optind - 1, (const char **) (argv + optind + 1));
103
104     return rc;
105 }
106
107 /* #define DEBUG */
108 int rrd_create_r(
109     const char *filename,
110     unsigned long pdp_step,
111     time_t last_up,
112     int argc,
113     const char **argv)
114 {
115     rrd_t     rrd;
116     long      i;
117     int       offset;
118     char     *token;
119     char      dummychar1[2], dummychar2[2];
120     unsigned short token_idx, error_flag, period = 0;
121     unsigned long hashed_name;
122
123     /* init rrd clean */
124     rrd_init(&rrd);
125     /* static header */
126     if ((rrd.stat_head = calloc(1, sizeof(stat_head_t))) == NULL) {
127         rrd_set_error("allocating rrd.stat_head");
128         free(rrd.stat_head);
129         return (-1);
130     }
131
132     /* live header */
133     if ((rrd.live_head = calloc(1, sizeof(live_head_t))) == NULL) {
134         rrd_set_error("allocating rrd.live_head");
135         free(rrd.stat_head);
136         free(rrd.live_head);
137         return (-1);
138     }
139
140     /* set some defaults */
141     strcpy(rrd.stat_head->cookie, RRD_COOKIE);
142     strcpy(rrd.stat_head->version, RRD_VERSION3);   /* by default we are still version 3 */
143     rrd.stat_head->float_cookie = FLOAT_COOKIE;
144     rrd.stat_head->ds_cnt = 0;  /* this will be adjusted later */
145     rrd.stat_head->rra_cnt = 0; /* ditto */
146     rrd.stat_head->pdp_step = pdp_step; /* 5 minute default */
147
148     /* a default value */
149     rrd.ds_def = NULL;
150     rrd.rra_def = NULL;
151
152     rrd.live_head->last_up = last_up;
153
154     /* optind points to the first non-option command line arg,
155      * in this case, the file name. */
156     /* Compute the FNV hash value (used by SEASONAL and DEVSEASONAL
157      * arrays. */
158     hashed_name = FnvHash(filename);
159     for (i = 0; i < argc; i++) {
160         unsigned int ii;
161
162         if (strncmp(argv[i], "DS:", 3) == 0) {
163             size_t    old_size = sizeof(ds_def_t) * (rrd.stat_head->ds_cnt);
164
165             if ((rrd.ds_def = rrd_realloc(rrd.ds_def,
166                                           old_size + sizeof(ds_def_t))) ==
167                 NULL) {
168                 rrd_set_error("allocating rrd.ds_def");
169                 free(rrd.stat_head);
170                 free(rrd.live_head);
171                 return (-1);
172             }
173             memset(&rrd.ds_def[rrd.stat_head->ds_cnt], 0, sizeof(ds_def_t));
174             /* extract the name and type */
175             switch (sscanf(&argv[i][3],
176                            DS_NAM_FMT "%1[:]" DST_FMT "%1[:]%n",
177                            rrd.ds_def[rrd.stat_head->ds_cnt].ds_nam,
178                            dummychar1,
179                            rrd.ds_def[rrd.stat_head->ds_cnt].dst,
180                            dummychar2, &offset)) {
181             case 0:
182             case 1:
183                 rrd_set_error("Invalid DS name");
184                 break;
185             case 2:
186             case 3:
187                 rrd_set_error("Invalid DS type");
188                 break;
189             case 4:    /* (%n may or may not be counted) */
190             case 5:    /* check for duplicate datasource names */
191                 for (ii = 0; ii < rrd.stat_head->ds_cnt; ii++)
192                     if (strcmp(rrd.ds_def[rrd.stat_head->ds_cnt].ds_nam,
193                                rrd.ds_def[ii].ds_nam) == 0)
194                         rrd_set_error("Duplicate DS name: %s",
195                                       rrd.ds_def[ii].ds_nam);
196                 /* DS_type may be valid or not. Checked later */
197                 break;
198             default:
199                 rrd_set_error("invalid DS format");
200             }
201             if (rrd_test_error()) {
202                 free(rrd.stat_head);
203                 free(rrd.live_head);
204                 return -1;
205             }
206
207             /* parse the remainder of the arguments */
208             switch (dst_conv(rrd.ds_def[rrd.stat_head->ds_cnt].dst)) {
209             case DST_COUNTER:
210             case DST_ABSOLUTE:
211             case DST_GAUGE:
212             case DST_DERIVE:
213                 parseGENERIC_DS(&argv[i][offset + 3], &rrd,
214                                 rrd.stat_head->ds_cnt);
215                 break;
216             case DST_CDEF:
217                 parseCDEF_DS(&argv[i][offset + 3], &rrd,
218                              rrd.stat_head->ds_cnt);
219                 break;
220             default:
221                 rrd_set_error("invalid DS type specified");
222                 break;
223             }
224
225             if (rrd_test_error()) {
226                 free(rrd.stat_head);
227                 free(rrd.live_head);
228                 return -1;
229             }
230             rrd.stat_head->ds_cnt++;
231         } else if (strncmp(argv[i], "RRA:", 4) == 0) {
232             char     *argvcopy;
233             char     *tokptr;
234             size_t    old_size = sizeof(rra_def_t) * (rrd.stat_head->rra_cnt);
235             int       row_cnt;
236
237             if ((rrd.rra_def = rrd_realloc(rrd.rra_def,
238                                            old_size + sizeof(rra_def_t))) ==
239                 NULL) {
240                 rrd_set_error("allocating rrd.rra_def");
241                 free(rrd.stat_head);
242                 free(rrd.live_head);
243                 return (-1);
244             }
245             memset(&rrd.rra_def[rrd.stat_head->rra_cnt], 0,
246                    sizeof(rra_def_t));
247
248             argvcopy = strdup(argv[i]);
249             token = strtok_r(&argvcopy[4], ":", &tokptr);
250             token_idx = error_flag = 0;
251             while (token != NULL) {
252                 switch (token_idx) {
253                 case 0:
254                     if (sscanf(token, CF_NAM_FMT,
255                                rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam) !=
256                         1)
257                         rrd_set_error("Failed to parse CF name");
258                     switch (cf_conv
259                             (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
260                     case CF_MHWPREDICT:
261                         strcpy(rrd.stat_head->version, RRD_VERSION);    /* MHWPREDICT causes Version 4 */
262                     case CF_HWPREDICT:
263                         /* initialize some parameters */
264                         rrd.rra_def[rrd.stat_head->rra_cnt].par[RRA_hw_alpha].
265                             u_val = 0.1;
266                         rrd.rra_def[rrd.stat_head->rra_cnt].par[RRA_hw_beta].
267                             u_val = 1.0 / 288;
268                         rrd.rra_def[rrd.stat_head->rra_cnt].
269                             par[RRA_dependent_rra_idx].u_cnt =
270                             rrd.stat_head->rra_cnt;
271                         break;
272                     case CF_DEVSEASONAL:
273                     case CF_SEASONAL:
274                         /* initialize some parameters */
275                         rrd.rra_def[rrd.stat_head->rra_cnt].
276                             par[RRA_seasonal_gamma].u_val = 0.1;
277                         rrd.rra_def[rrd.stat_head->rra_cnt].
278                             par[RRA_seasonal_smoothing_window].u_val = 0.05;
279                         /* fall through */
280                     case CF_DEVPREDICT:
281                         rrd.rra_def[rrd.stat_head->rra_cnt].
282                             par[RRA_dependent_rra_idx].u_cnt = -1;
283                         break;
284                     case CF_FAILURES:
285                         rrd.rra_def[rrd.stat_head->rra_cnt].
286                             par[RRA_delta_pos].u_val = 2.0;
287                         rrd.rra_def[rrd.stat_head->rra_cnt].
288                             par[RRA_delta_neg].u_val = 2.0;
289                         rrd.rra_def[rrd.stat_head->rra_cnt].
290                             par[RRA_window_len].u_cnt = 3;
291                         rrd.rra_def[rrd.stat_head->rra_cnt].
292                             par[RRA_failure_threshold].u_cnt = 2;
293                         rrd.rra_def[rrd.stat_head->rra_cnt].
294                             par[RRA_dependent_rra_idx].u_cnt = -1;
295                         break;
296                         /* invalid consolidation function */
297                     case -1:
298                         rrd_set_error
299                             ("Unrecognized consolidation function %s",
300                              rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam);
301                     default:
302                         break;
303                     }
304                     /* default: 1 pdp per cdp */
305                     rrd.rra_def[rrd.stat_head->rra_cnt].pdp_cnt = 1;
306                     break;
307                 case 1:
308                     switch (cf_conv
309                             (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
310                     case CF_HWPREDICT:
311                     case CF_MHWPREDICT:
312                     case CF_DEVSEASONAL:
313                     case CF_SEASONAL:
314                     case CF_DEVPREDICT:
315                     case CF_FAILURES:
316                         row_cnt = atoi(token);
317                         if (row_cnt <= 0)
318                             rrd_set_error("Invalid row count: %i", row_cnt);
319                         rrd.rra_def[rrd.stat_head->rra_cnt].row_cnt = row_cnt;
320                         break;
321                     default:
322                         rrd.rra_def[rrd.stat_head->rra_cnt].
323                             par[RRA_cdp_xff_val].u_val = atof(token);
324                         if (rrd.rra_def[rrd.stat_head->rra_cnt].
325                             par[RRA_cdp_xff_val].u_val < 0.0
326                             || rrd.rra_def[rrd.stat_head->rra_cnt].
327                             par[RRA_cdp_xff_val].u_val >= 1.0)
328                             rrd_set_error
329                                 ("Invalid xff: must be between 0 and 1");
330                         break;
331                     }
332                     break;
333                 case 2:
334                     switch (cf_conv
335                             (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
336                     case CF_HWPREDICT:
337                     case CF_MHWPREDICT:
338                         rrd.rra_def[rrd.stat_head->rra_cnt].par[RRA_hw_alpha].
339                             u_val = atof(token);
340                         if (atof(token) <= 0.0 || atof(token) >= 1.0)
341                             rrd_set_error
342                                 ("Invalid alpha: must be between 0 and 1");
343                         break;
344                     case CF_DEVSEASONAL:
345                     case CF_SEASONAL:
346                         rrd.rra_def[rrd.stat_head->rra_cnt].
347                             par[RRA_seasonal_gamma].u_val = atof(token);
348                         if (atof(token) <= 0.0 || atof(token) >= 1.0)
349                             rrd_set_error
350                                 ("Invalid gamma: must be between 0 and 1");
351                         rrd.rra_def[rrd.stat_head->rra_cnt].
352                             par[RRA_seasonal_smooth_idx].u_cnt =
353                             hashed_name %
354                             rrd.rra_def[rrd.stat_head->rra_cnt].row_cnt;
355                         break;
356                     case CF_FAILURES:
357                         /* specifies the # of violations that constitutes the failure threshold */
358                         rrd.rra_def[rrd.stat_head->rra_cnt].
359                             par[RRA_failure_threshold].u_cnt = atoi(token);
360                         if (atoi(token) < 1
361                             || atoi(token) > MAX_FAILURES_WINDOW_LEN)
362                             rrd_set_error
363                                 ("Failure threshold is out of range %d, %d",
364                                  1, MAX_FAILURES_WINDOW_LEN);
365                         break;
366                     case CF_DEVPREDICT:
367                         /* specifies the index (1-based) of CF_DEVSEASONAL array
368                          * associated with this CF_DEVPREDICT array. */
369                         rrd.rra_def[rrd.stat_head->rra_cnt].
370                             par[RRA_dependent_rra_idx].u_cnt =
371                             atoi(token) - 1;
372                         break;
373                     default:
374                         rrd.rra_def[rrd.stat_head->rra_cnt].pdp_cnt =
375                             atoi(token);
376                         break;
377                     }
378                     break;
379                 case 3:
380                     switch (cf_conv
381                             (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
382                     case CF_HWPREDICT:
383                     case CF_MHWPREDICT:
384                         rrd.rra_def[rrd.stat_head->rra_cnt].par[RRA_hw_beta].
385                             u_val = atof(token);
386                         if (atof(token) < 0.0 || atof(token) > 1.0)
387                             rrd_set_error
388                                 ("Invalid beta: must be between 0 and 1");
389                         break;
390                     case CF_DEVSEASONAL:
391                     case CF_SEASONAL:
392                         /* specifies the index (1-based) of CF_HWPREDICT array
393                          * associated with this CF_DEVSEASONAL or CF_SEASONAL array. 
394                          * */
395                         rrd.rra_def[rrd.stat_head->rra_cnt].
396                             par[RRA_dependent_rra_idx].u_cnt =
397                             atoi(token) - 1;
398                         break;
399                     case CF_FAILURES:
400                         /* specifies the window length */
401                         rrd.rra_def[rrd.stat_head->rra_cnt].
402                             par[RRA_window_len].u_cnt = atoi(token);
403                         if (atoi(token) < 1
404                             || atoi(token) > MAX_FAILURES_WINDOW_LEN)
405                             rrd_set_error
406                                 ("Window length is out of range %d, %d", 1,
407                                  MAX_FAILURES_WINDOW_LEN);
408                         /* verify that window length exceeds the failure threshold */
409                         if (rrd.rra_def[rrd.stat_head->rra_cnt].
410                             par[RRA_window_len].u_cnt <
411                             rrd.rra_def[rrd.stat_head->rra_cnt].
412                             par[RRA_failure_threshold].u_cnt)
413                             rrd_set_error
414                                 ("Window length is shorter than the failure threshold");
415                         break;
416                     case CF_DEVPREDICT:
417                         /* shouldn't be any more arguments */
418                         rrd_set_error
419                             ("Unexpected extra argument for consolidation function DEVPREDICT");
420                         break;
421                     default:
422                         row_cnt = atoi(token);
423                         if (row_cnt <= 0)
424                             rrd_set_error("Invalid row count: %i", row_cnt);
425                         rrd.rra_def[rrd.stat_head->rra_cnt].row_cnt = row_cnt;
426                         break;
427                     }
428                     break;
429                 case 4:
430                     switch (cf_conv
431                             (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
432                     case CF_FAILURES:
433                         /* specifies the index (1-based) of CF_DEVSEASONAL array
434                          * associated with this CF_DEVFAILURES array. */
435                         rrd.rra_def[rrd.stat_head->rra_cnt].
436                             par[RRA_dependent_rra_idx].u_cnt =
437                             atoi(token) - 1;
438                         break;
439                     case CF_DEVSEASONAL:
440                     case CF_SEASONAL:
441                         /* optional smoothing window */
442                         if (sscanf(token, "smoothing-window=%lf",
443                                    &(rrd.rra_def[rrd.stat_head->rra_cnt].
444                                      par[RRA_seasonal_smoothing_window].
445                                      u_val))) {
446                             strcpy(rrd.stat_head->version, RRD_VERSION);    /* smoothing-window causes Version 4 */
447                             if (rrd.rra_def[rrd.stat_head->rra_cnt].
448                                 par[RRA_seasonal_smoothing_window].u_val < 0.0
449                                 || rrd.rra_def[rrd.stat_head->rra_cnt].
450                                 par[RRA_seasonal_smoothing_window].u_val >
451                                 1.0) {
452                                 rrd_set_error
453                                     ("Invalid smoothing-window %f: must be between 0 and 1",
454                                      rrd.rra_def[rrd.stat_head->rra_cnt].
455                                      par[RRA_seasonal_smoothing_window].
456                                      u_val);
457                             }
458                         } else {
459                             rrd_set_error("Invalid option %s", token);
460                         }
461                         break;
462                     case CF_HWPREDICT:
463                     case CF_MHWPREDICT:
464                         /* length of the associated CF_SEASONAL and CF_DEVSEASONAL arrays. */
465                         period = atoi(token);
466                         if (period >
467                             rrd.rra_def[rrd.stat_head->rra_cnt].row_cnt)
468                             rrd_set_error
469                                 ("Length of seasonal cycle exceeds length of HW prediction array");
470                         break;
471                     default:
472                         /* shouldn't be any more arguments */
473                         rrd_set_error
474                             ("Unexpected extra argument for consolidation function %s",
475                              rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam);
476                         break;
477                     }
478                     break;
479                 case 5:
480                     /* If we are here, this must be a CF_HWPREDICT RRA.
481                      * Specifies the index (1-based) of CF_SEASONAL array
482                      * associated with this CF_HWPREDICT array. If this argument 
483                      * is missing, then the CF_SEASONAL, CF_DEVSEASONAL, CF_DEVPREDICT,
484                      * CF_FAILURES.
485                      * arrays are created automatically. */
486                     rrd.rra_def[rrd.stat_head->rra_cnt].
487                         par[RRA_dependent_rra_idx].u_cnt = atoi(token) - 1;
488                     break;
489                 default:
490                     /* should never get here */
491                     rrd_set_error("Unknown error");
492                     break;
493                 }       /* end switch */
494                 if (rrd_test_error()) {
495                     /* all errors are unrecoverable */
496                     free(argvcopy);
497                     free(rrd.stat_head);
498                     free(rrd.live_head);
499                     return (-1);
500                 }
501                 token = strtok_r(NULL, ":", &tokptr);
502                 token_idx++;
503             }           /* end while */
504             free(argvcopy);
505 #ifdef DEBUG
506             fprintf(stderr,
507                     "Creating RRA CF: %s, dep idx %lu, current idx %lu\n",
508                     rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam,
509                     rrd.rra_def[rrd.stat_head->rra_cnt].
510                     par[RRA_dependent_rra_idx].u_cnt, rrd.stat_head->rra_cnt);
511 #endif
512             /* should we create CF_SEASONAL, CF_DEVSEASONAL, and CF_DEVPREDICT? */
513             if ((cf_conv(rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam) ==
514                  CF_HWPREDICT
515                  || cf_conv(rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam) ==
516                  CF_MHWPREDICT)
517                 && rrd.rra_def[rrd.stat_head->rra_cnt].
518                 par[RRA_dependent_rra_idx].u_cnt == rrd.stat_head->rra_cnt) {
519 #ifdef DEBUG
520                 fprintf(stderr, "Creating HW contingent RRAs\n");
521 #endif
522                 if (create_hw_contingent_rras(&rrd, period, hashed_name) ==
523                     -1) {
524                     rrd_set_error("creating contingent RRA");
525                     free(rrd.stat_head);
526                     free(rrd.live_head);
527                     return -1;
528                 }
529             }
530             rrd.stat_head->rra_cnt++;
531         } else {
532             rrd_set_error("can't parse argument '%s'", argv[i]);
533             free(rrd.stat_head);
534             free(rrd.live_head);
535             return -1;
536         }
537     }
538
539
540     if (rrd.stat_head->rra_cnt < 1) {
541         rrd_set_error("you must define at least one Round Robin Archive");
542         free(rrd.stat_head);
543         free(rrd.live_head);
544         return (-1);
545     }
546
547     if (rrd.stat_head->ds_cnt < 1) {
548         rrd_set_error("you must define at least one Data Source");
549         free(rrd.stat_head);
550         free(rrd.live_head);
551         return (-1);
552     }
553     return rrd_create_fn(filename, &rrd);
554 }
555
556 void parseGENERIC_DS(
557     const char *def,
558     rrd_t *rrd,
559     int ds_idx)
560 {
561     char      minstr[DS_NAM_SIZE], maxstr[DS_NAM_SIZE];
562     char     *old_locale;
563
564     /*
565        int temp;
566
567        temp = sscanf(def,"%lu:%18[^:]:%18[^:]", 
568        &(rrd -> ds_def[ds_idx].par[DS_mrhb_cnt].u_cnt),
569        minstr,maxstr);
570      */
571     old_locale = setlocale(LC_NUMERIC, "C");
572     if (sscanf(def, "%lu:%18[^:]:%18[^:]",
573                &(rrd->ds_def[ds_idx].par[DS_mrhb_cnt].u_cnt),
574                minstr, maxstr) == 3) {
575         if (minstr[0] == 'U' && minstr[1] == 0)
576             rrd->ds_def[ds_idx].par[DS_min_val].u_val = DNAN;
577         else
578             rrd->ds_def[ds_idx].par[DS_min_val].u_val = atof(minstr);
579
580         if (maxstr[0] == 'U' && maxstr[1] == 0)
581             rrd->ds_def[ds_idx].par[DS_max_val].u_val = DNAN;
582         else
583             rrd->ds_def[ds_idx].par[DS_max_val].u_val = atof(maxstr);
584
585         if (!isnan(rrd->ds_def[ds_idx].par[DS_min_val].u_val) &&
586             !isnan(rrd->ds_def[ds_idx].par[DS_max_val].u_val) &&
587             rrd->ds_def[ds_idx].par[DS_min_val].u_val
588             >= rrd->ds_def[ds_idx].par[DS_max_val].u_val) {
589             rrd_set_error("min must be less than max in DS definition");
590             setlocale(LC_NUMERIC, old_locale);
591             return;
592         }
593     } else {
594         rrd_set_error("failed to parse data source %s", def);
595     }
596     setlocale(LC_NUMERIC, old_locale);
597 }
598
599 /* Create the CF_DEVPREDICT, CF_DEVSEASONAL, CF_SEASONAL, and CF_FAILURES RRAs
600  * associated with a CF_HWPREDICT RRA. */
601 int create_hw_contingent_rras(
602     rrd_t *rrd,
603     unsigned short period,
604     unsigned long hashed_name)
605 {
606     size_t    old_size;
607     rra_def_t *current_rra;
608
609     /* save index to CF_HWPREDICT */
610     unsigned long hw_index = rrd->stat_head->rra_cnt;
611
612     /* advance the pointer */
613     (rrd->stat_head->rra_cnt)++;
614     /* allocate the memory for the 4 contingent RRAs */
615     old_size = sizeof(rra_def_t) * (rrd->stat_head->rra_cnt);
616     if ((rrd->rra_def = rrd_realloc(rrd->rra_def,
617                                     old_size + 4 * sizeof(rra_def_t))) ==
618         NULL) {
619         rrd_set_error("allocating rrd.rra_def");
620         return (-1);
621     }
622     /* clear memory */
623     memset(&(rrd->rra_def[rrd->stat_head->rra_cnt]), 0,
624            4 * sizeof(rra_def_t));
625
626     /* create the CF_SEASONAL RRA */
627     current_rra = &(rrd->rra_def[rrd->stat_head->rra_cnt]);
628     strcpy(current_rra->cf_nam, "SEASONAL");
629     current_rra->row_cnt = period;
630     current_rra->par[RRA_seasonal_smooth_idx].u_cnt = hashed_name % period;
631     current_rra->pdp_cnt = 1;
632     current_rra->par[RRA_seasonal_gamma].u_val =
633         rrd->rra_def[hw_index].par[RRA_hw_alpha].u_val;
634     current_rra->par[RRA_dependent_rra_idx].u_cnt = hw_index;
635     rrd->rra_def[hw_index].par[RRA_dependent_rra_idx].u_cnt =
636         rrd->stat_head->rra_cnt;
637
638     /* create the CF_DEVSEASONAL RRA */
639     (rrd->stat_head->rra_cnt)++;
640     current_rra = &(rrd->rra_def[rrd->stat_head->rra_cnt]);
641     strcpy(current_rra->cf_nam, "DEVSEASONAL");
642     current_rra->row_cnt = period;
643     current_rra->par[RRA_seasonal_smooth_idx].u_cnt = hashed_name % period;
644     current_rra->pdp_cnt = 1;
645     current_rra->par[RRA_seasonal_gamma].u_val =
646         rrd->rra_def[hw_index].par[RRA_hw_alpha].u_val;
647     current_rra->par[RRA_dependent_rra_idx].u_cnt = hw_index;
648
649     /* create the CF_DEVPREDICT RRA */
650     (rrd->stat_head->rra_cnt)++;
651     current_rra = &(rrd->rra_def[rrd->stat_head->rra_cnt]);
652     strcpy(current_rra->cf_nam, "DEVPREDICT");
653     current_rra->row_cnt = (rrd->rra_def[hw_index]).row_cnt;
654     current_rra->pdp_cnt = 1;
655     current_rra->par[RRA_dependent_rra_idx].u_cnt = hw_index + 2;   /* DEVSEASONAL */
656
657     /* create the CF_FAILURES RRA */
658     (rrd->stat_head->rra_cnt)++;
659     current_rra = &(rrd->rra_def[rrd->stat_head->rra_cnt]);
660     strcpy(current_rra->cf_nam, "FAILURES");
661     current_rra->row_cnt = period;
662     current_rra->pdp_cnt = 1;
663     current_rra->par[RRA_delta_pos].u_val = 2.0;
664     current_rra->par[RRA_delta_neg].u_val = 2.0;
665     current_rra->par[RRA_failure_threshold].u_cnt = 7;
666     current_rra->par[RRA_window_len].u_cnt = 9;
667     current_rra->par[RRA_dependent_rra_idx].u_cnt = hw_index + 2;   /* DEVSEASONAL */
668     return 0;
669 }
670
671 /* create and empty rrd file according to the specs given */
672
673 int rrd_create_fn(
674     const char *file_name,
675     rrd_t *rrd)
676 {
677     unsigned long i, ii;
678     int       rrd_file;
679     rrd_value_t *unknown;
680     int       unkn_cnt;
681     rrd_file_t *rrd_file_dn;
682     rrd_t     rrd_dn;
683     unsigned flags = O_WRONLY | O_CREAT | O_TRUNC;
684 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
685     flags |= O_BINARY;
686 #endif
687
688     if ((rrd_file = open(file_name, flags, 0666)) < 0) {
689         rrd_set_error("creating '%s': %s", file_name, rrd_strerror(errno));
690         free(rrd->stat_head);
691         free(rrd->live_head);
692         return (-1);
693     }
694
695     write(rrd_file, rrd->stat_head, sizeof(stat_head_t));
696
697     write(rrd_file, rrd->ds_def, sizeof(ds_def_t) * rrd->stat_head->ds_cnt);
698
699     write(rrd_file, rrd->rra_def,
700           sizeof(rra_def_t) * rrd->stat_head->rra_cnt);
701
702     write(rrd_file, rrd->live_head, sizeof(live_head_t));
703
704     if ((rrd->pdp_prep = calloc(1, sizeof(pdp_prep_t))) == NULL) {
705         rrd_set_error("allocating pdp_prep");
706         free(rrd->stat_head);
707         free(rrd->live_head);
708         close(rrd_file);
709         return (-1);
710     }
711
712     strcpy(rrd->pdp_prep->last_ds, "U");
713
714     rrd->pdp_prep->scratch[PDP_val].u_val = 0.0;
715     rrd->pdp_prep->scratch[PDP_unkn_sec_cnt].u_cnt =
716         rrd->live_head->last_up % rrd->stat_head->pdp_step;
717
718     for (i = 0; i < rrd->stat_head->ds_cnt; i++)
719         write(rrd_file, rrd->pdp_prep, sizeof(pdp_prep_t));
720
721     if ((rrd->cdp_prep = calloc(1, sizeof(cdp_prep_t))) == NULL) {
722         rrd_set_error("allocating cdp_prep");
723         free(rrd->stat_head);
724         free(rrd->live_head);
725         close(rrd_file);
726         return (-1);
727     }
728
729
730     for (i = 0; i < rrd->stat_head->rra_cnt; i++) {
731         switch (cf_conv(rrd->rra_def[i].cf_nam)) {
732         case CF_HWPREDICT:
733         case CF_MHWPREDICT:
734             init_hwpredict_cdp(rrd->cdp_prep);
735             break;
736         case CF_SEASONAL:
737         case CF_DEVSEASONAL:
738             init_seasonal_cdp(rrd->cdp_prep);
739             break;
740         case CF_FAILURES:
741             /* initialize violation history to 0 */
742             for (ii = 0; ii < MAX_CDP_PAR_EN; ii++) {
743                 /* We can zero everything out, by setting u_val to the
744                  * NULL address. Each array entry in scratch is 8 bytes
745                  * (a double), but u_cnt only accessed 4 bytes (long) */
746                 rrd->cdp_prep->scratch[ii].u_val = 0.0;
747             }
748             break;
749         default:
750             /* can not be zero because we don't know anything ... */
751             rrd->cdp_prep->scratch[CDP_val].u_val = DNAN;
752             /* startup missing pdp count */
753             rrd->cdp_prep->scratch[CDP_unkn_pdp_cnt].u_cnt =
754                 ((rrd->live_head->last_up -
755                   rrd->pdp_prep->scratch[PDP_unkn_sec_cnt].u_cnt)
756                  % (rrd->stat_head->pdp_step
757                     * rrd->rra_def[i].pdp_cnt)) / rrd->stat_head->pdp_step;
758             break;
759         }
760
761         for (ii = 0; ii < rrd->stat_head->ds_cnt; ii++) {
762             write(rrd_file, rrd->cdp_prep, sizeof(cdp_prep_t));
763         }
764     }
765
766     /* now, we must make sure that the rest of the rrd
767        struct is properly initialized */
768
769     if ((rrd->rra_ptr = calloc(1, sizeof(rra_ptr_t))) == NULL) {
770         rrd_set_error("allocating rra_ptr");
771         free(rrd->stat_head);
772         free(rrd->live_head);
773         close(rrd_file);
774         return (-1);
775     }
776
777     /* changed this initialization to be consistent with
778      * rrd_restore. With the old value (0), the first update
779      * would occur for cur_row = 1 because rrd_update increments
780      * the pointer a priori. */
781     for (i = 0; i < rrd->stat_head->rra_cnt; i++) {
782         rrd->rra_ptr->cur_row = rra_random_row(&rrd->rra_def[i]);
783         write(rrd_file, rrd->rra_ptr, sizeof(rra_ptr_t));
784     }
785
786     /* write the empty data area */
787     if ((unknown = (rrd_value_t *) malloc(512 * sizeof(rrd_value_t))) == NULL) {
788         rrd_set_error("allocating unknown");
789         free(rrd->stat_head);
790         free(rrd->live_head);
791         close(rrd_file);
792         return (-1);
793     }
794     for (i = 0; i < 512; ++i)
795         unknown[i] = DNAN;
796
797     unkn_cnt = 0;
798     for (i = 0; i < rrd->stat_head->rra_cnt; i++)
799         unkn_cnt += rrd->stat_head->ds_cnt * rrd->rra_def[i].row_cnt;
800
801     while (unkn_cnt > 0) {
802         write(rrd_file, unknown, sizeof(rrd_value_t) * min(unkn_cnt, 512));
803
804         unkn_cnt -= 512;
805     }
806     free(unknown);
807     fdatasync(rrd_file);
808     free(rrd->stat_head);
809     free(rrd->live_head);
810     if (close(rrd_file) == -1) {
811         rrd_set_error("creating rrd: %s", rrd_strerror(errno));
812         return -1;
813     }
814     /* flush all we don't need out of the cache */
815     rrd_file_dn = rrd_open(file_name, &rrd_dn, RRD_READONLY);
816     rrd_dontneed(rrd_file_dn, &rrd_dn);
817     rrd_free(&rrd_dn);
818     rrd_close(rrd_file_dn);
819     return (0);
820 }
821
822 static int rand_init = 0;
823
824 long int rra_random_row(
825     rra_def_t *rra)
826 {
827     if (!rand_init) {
828         srandom((unsigned int) time(NULL) + (unsigned int) getpid());
829         rand_init++;
830     }
831
832     return random() % rra->row_cnt;
833 }