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