edb6c9570c79a793b09eee931fc659b6342fc84a
[collectd.git] / src / utils_rrdcreate.c
1 /**
2  * collectd - src/utils_rrdcreate.c
3  * Copyright (C) 2006-2013  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  **/
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "utils_rrdcreate.h"
31
32 #include <pthread.h>
33 #include <rrd.h>
34
35 struct srrd_create_args_s
36 {
37   char *filename;
38   unsigned long pdp_step;
39   time_t last_up;
40   int argc;
41   char **argv;
42 };
43 typedef struct srrd_create_args_s srrd_create_args_t;
44
45 struct async_create_file_s;
46 typedef struct async_create_file_s async_create_file_t;
47 struct async_create_file_s
48 {
49   char *filename;
50   async_create_file_t *next;
51 };
52
53 /*
54  * Private variables
55  */
56 static int rra_timespans[] =
57 {
58   3600,
59   86400,
60   604800,
61   2678400,
62   31622400
63 };
64 static int rra_timespans_num = STATIC_ARRAY_SIZE (rra_timespans);
65
66 static const char *const rra_types[] =
67 {
68   "AVERAGE",
69   "MIN",
70   "MAX"
71 };
72 static int rra_types_num = STATIC_ARRAY_SIZE (rra_types);
73
74 #if !defined(HAVE_THREADSAFE_LIBRRD)
75 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
76 #endif
77
78 static async_create_file_t *async_creation_list = NULL;
79 static pthread_mutex_t async_creation_lock = PTHREAD_MUTEX_INITIALIZER;
80
81 /*
82  * Private functions
83  */
84 static void rra_free (int rra_num, char **rra_def) /* {{{ */
85 {
86   int i;
87
88   for (i = 0; i < rra_num; i++)
89   {
90     sfree (rra_def[i]);
91   }
92   sfree (rra_def);
93 } /* }}} void rra_free */
94
95 static void srrd_create_args_destroy (srrd_create_args_t *args)
96 {
97   if (args == NULL)
98     return;
99
100   sfree (args->filename);
101   if (args->argv != NULL)
102   {
103     int i;
104     for (i = 0; i < args->argc; i++)
105       sfree (args->argv[i]);
106     sfree (args->argv);
107   }
108   sfree (args);
109 } /* void srrd_create_args_destroy */
110
111 static srrd_create_args_t *srrd_create_args_create (const char *filename,
112     unsigned long pdp_step, time_t last_up,
113     int argc, const char **argv)
114 {
115   srrd_create_args_t *args;
116
117   args = calloc (1, sizeof (*args));
118   if (args == NULL)
119   {
120     ERROR ("srrd_create_args_create: calloc failed.");
121     return (NULL);
122   }
123   args->filename = NULL;
124   args->pdp_step = pdp_step;
125   args->last_up = last_up;
126   args->argv = NULL;
127
128   args->filename = strdup (filename);
129   if (args->filename == NULL)
130   {
131     ERROR ("srrd_create_args_create: strdup failed.");
132     srrd_create_args_destroy (args);
133     return (NULL);
134   }
135
136   args->argv = calloc ((size_t) (argc + 1), sizeof (*args->argv));
137   if (args->argv == NULL)
138   {
139     ERROR ("srrd_create_args_create: calloc failed.");
140     srrd_create_args_destroy (args);
141     return (NULL);
142   }
143
144   for (args->argc = 0; args->argc < argc; args->argc++)
145   {
146     args->argv[args->argc] = strdup (argv[args->argc]);
147     if (args->argv[args->argc] == NULL)
148     {
149       ERROR ("srrd_create_args_create: strdup failed.");
150       srrd_create_args_destroy (args);
151       return (NULL);
152     }
153   }
154   assert (args->argc == argc);
155   args->argv[args->argc] = NULL;
156
157   return (args);
158 } /* srrd_create_args_t *srrd_create_args_create */
159
160 /* * * * * * * * * *
161  * WARNING:  Magic *
162  * * * * * * * * * */
163 static int rra_get (char ***ret, const value_list_t *vl, /* {{{ */
164     const rrdcreate_config_t *cfg)
165 {
166   char **rra_def;
167   int rra_num;
168
169   int *rts;
170   int  rts_num;
171
172   int rra_max;
173
174   int cdp_num;
175   int cdp_len;
176   int i, j;
177
178   /* The stepsize we use here: If it is user-set, use it. If not, use the
179    * interval of the value-list. */
180   int ss;
181
182   if (cfg->rrarows <= 0)
183   {
184     *ret = NULL;
185     return (-1);
186   }
187
188   if ((cfg->xff < 0) || (cfg->xff >= 1.0))
189   {
190     *ret = NULL;
191     return (-1);
192   }
193
194   if (cfg->stepsize > 0)
195     ss = cfg->stepsize;
196   else
197     ss = (int) CDTIME_T_TO_TIME_T (vl->interval);
198   if (ss <= 0)
199   {
200     *ret = NULL;
201     return (-1);
202   }
203
204   /* Use the configured timespans or fall back to the built-in defaults */
205   if (cfg->timespans_num != 0)
206   {
207     rts = cfg->timespans;
208     rts_num = cfg->timespans_num;
209   }
210   else
211   {
212     rts = rra_timespans;
213     rts_num = rra_timespans_num;
214   }
215
216   rra_max = rts_num * rra_types_num;
217   assert (rra_max > 0);
218
219   if ((rra_def = calloc (rra_max + 1, sizeof (*rra_def))) == NULL)
220     return (-1);
221   rra_num = 0;
222
223   cdp_len = 0;
224   for (i = 0; i < rts_num; i++)
225   {
226     int span = rts[i];
227
228     if ((span / ss) < cfg->rrarows)
229       span = ss * cfg->rrarows;
230
231     if (cdp_len == 0)
232       cdp_len = 1;
233     else
234       cdp_len = (int) floor (((double) span)
235           / ((double) (cfg->rrarows * ss)));
236
237     cdp_num = (int) ceil (((double) span)
238         / ((double) (cdp_len * ss)));
239
240     for (j = 0; j < rra_types_num; j++)
241     {
242       char buffer[128];
243       int status;
244
245       if (rra_num >= rra_max)
246         break;
247
248       status = ssnprintf (buffer, sizeof (buffer), "RRA:%s:%.10f:%u:%u",
249           rra_types[j], cfg->xff, cdp_len, cdp_num);
250
251       if ((status < 0) || ((size_t) status >= sizeof (buffer)))
252       {
253         ERROR ("rra_get: Buffer would have been truncated.");
254         continue;
255       }
256
257       rra_def[rra_num++] = sstrdup (buffer);
258     }
259   }
260
261   if (rra_num <= 0)
262   {
263     sfree (rra_def);
264     return (0);
265   }
266
267   *ret = rra_def;
268   return (rra_num);
269 } /* }}} int rra_get */
270
271 static void ds_free (int ds_num, char **ds_def) /* {{{ */
272 {
273   int i;
274
275   for (i = 0; i < ds_num; i++)
276     if (ds_def[i] != NULL)
277       free (ds_def[i]);
278   free (ds_def);
279 } /* }}} void ds_free */
280
281 static int ds_get (char ***ret, /* {{{ */
282     const data_set_t *ds, const value_list_t *vl,
283     const rrdcreate_config_t *cfg)
284 {
285   char **ds_def;
286   size_t ds_num;
287
288   char min[32];
289   char max[32];
290   char buffer[128];
291
292   assert (ds->ds_num > 0);
293
294   ds_def = calloc (ds->ds_num, sizeof (*ds_def));
295   if (ds_def == NULL)
296   {
297     char errbuf[1024];
298     ERROR ("rrdtool plugin: calloc failed: %s",
299         sstrerror (errno, errbuf, sizeof (errbuf)));
300     return (-1);
301   }
302
303   for (ds_num = 0; ds_num < ds->ds_num; ds_num++)
304   {
305     data_source_t *d = ds->ds + ds_num;
306     const char *type;
307     int status;
308
309     ds_def[ds_num] = NULL;
310
311     if (d->type == DS_TYPE_COUNTER)
312       type = "COUNTER";
313     else if (d->type == DS_TYPE_GAUGE)
314       type = "GAUGE";
315     else if (d->type == DS_TYPE_DERIVE)
316       type = "DERIVE";
317     else if (d->type == DS_TYPE_ABSOLUTE)
318       type = "ABSOLUTE";
319     else
320     {
321       ERROR ("rrdtool plugin: Unknown DS type: %i",
322           d->type);
323       break;
324     }
325
326     if (isnan (d->min))
327     {
328       sstrncpy (min, "U", sizeof (min));
329     }
330     else
331       ssnprintf (min, sizeof (min), "%f", d->min);
332
333     if (isnan (d->max))
334     {
335       sstrncpy (max, "U", sizeof (max));
336     }
337     else
338       ssnprintf (max, sizeof (max), "%f", d->max);
339
340     status = ssnprintf (buffer, sizeof (buffer),
341         "DS:%s:%s:%i:%s:%s",
342         d->name, type,
343         (cfg->heartbeat > 0)
344         ? cfg->heartbeat
345         : (int) CDTIME_T_TO_TIME_T (2 * vl->interval),
346         min, max);
347     if ((status < 1) || ((size_t) status >= sizeof (buffer)))
348       break;
349
350     ds_def[ds_num] = sstrdup (buffer);
351   } /* for ds_num = 0 .. ds->ds_num */
352
353   if (ds_num != ds->ds_num)
354   {
355     ds_free (ds_num, ds_def);
356     return (-1);
357   }
358
359   if (ds_num == 0)
360   {
361     sfree (ds_def);
362     return (0);
363   }
364
365   *ret = ds_def;
366   return (ds_num);
367 } /* }}} int ds_get */
368
369 #if HAVE_THREADSAFE_LIBRRD
370 static int srrd_create (const char *filename, /* {{{ */
371     unsigned long pdp_step, time_t last_up,
372     int argc, const char **argv)
373 {
374   int status;
375   char *filename_copy;
376
377   if ((filename == NULL) || (argv == NULL))
378     return (-EINVAL);
379
380   /* Some versions of librrd don't have the `const' qualifier for the first
381    * argument, so we have to copy the pointer here to avoid warnings. It sucks,
382    * but what else can we do? :(  -octo */
383   filename_copy = strdup (filename);
384   if (filename_copy == NULL)
385   {
386     ERROR ("srrd_create: strdup failed.");
387     return (-ENOMEM);
388   }
389
390   optind = 0; /* bug in librrd? */
391   rrd_clear_error ();
392
393   status = rrd_create_r (filename_copy, pdp_step, last_up,
394       argc, (void *) argv);
395
396   if (status != 0)
397   {
398     WARNING ("rrdtool plugin: rrd_create_r (%s) failed: %s",
399         filename, rrd_get_error ());
400   }
401
402   sfree (filename_copy);
403
404   return (status);
405 } /* }}} int srrd_create */
406 /* #endif HAVE_THREADSAFE_LIBRRD */
407
408 #else /* !HAVE_THREADSAFE_LIBRRD */
409 static int srrd_create (const char *filename, /* {{{ */
410     unsigned long pdp_step, time_t last_up,
411     int argc, const char **argv)
412 {
413   int status;
414
415   int new_argc;
416   char **new_argv;
417
418   char pdp_step_str[16];
419   char last_up_str[16];
420
421   new_argc = 6 + argc;
422   new_argv = malloc ((new_argc + 1) * sizeof (*new_argv));
423   if (new_argv == NULL)
424   {
425     ERROR ("rrdtool plugin: malloc failed.");
426     return (-1);
427   }
428
429   if (last_up == 0)
430     last_up = time (NULL) - 10;
431
432   ssnprintf (pdp_step_str, sizeof (pdp_step_str), "%lu", pdp_step);
433   ssnprintf (last_up_str, sizeof (last_up_str), "%lu", (unsigned long) last_up);
434
435   new_argv[0] = "create";
436   new_argv[1] = (void *) filename;
437   new_argv[2] = "-s";
438   new_argv[3] = pdp_step_str;
439   new_argv[4] = "-b";
440   new_argv[5] = last_up_str;
441
442   memcpy (new_argv + 6, argv, argc * sizeof (char *));
443   new_argv[new_argc] = NULL;
444
445   pthread_mutex_lock (&librrd_lock);
446   optind = 0; /* bug in librrd? */
447   rrd_clear_error ();
448
449   status = rrd_create (new_argc, new_argv);
450   pthread_mutex_unlock (&librrd_lock);
451
452   if (status != 0)
453   {
454     WARNING ("rrdtool plugin: rrd_create (%s) failed: %s",
455         filename, rrd_get_error ());
456   }
457
458   sfree (new_argv);
459
460   return (status);
461 } /* }}} int srrd_create */
462 #endif /* !HAVE_THREADSAFE_LIBRRD */
463
464 static int lock_file (char const *filename) /* {{{ */
465 {
466   async_create_file_t *ptr;
467   struct stat sb;
468   int status;
469
470   pthread_mutex_lock (&async_creation_lock);
471
472   for (ptr = async_creation_list; ptr != NULL; ptr = ptr->next)
473     if (strcmp (filename, ptr->filename) == 0)
474       break;
475
476   if (ptr != NULL)
477   {
478     pthread_mutex_unlock (&async_creation_lock);
479     return (EEXIST);
480   }
481
482   status = stat (filename, &sb);
483   if ((status == 0) || (errno != ENOENT))
484   {
485     pthread_mutex_unlock (&async_creation_lock);
486     return (EEXIST);
487   }
488
489   ptr = malloc (sizeof (*ptr));
490   if (ptr == NULL)
491   {
492     pthread_mutex_unlock (&async_creation_lock);
493     return (ENOMEM);
494   }
495
496   ptr->filename = strdup (filename);
497   if (ptr->filename == NULL)
498   {
499     pthread_mutex_unlock (&async_creation_lock);
500     sfree (ptr);
501     return (ENOMEM);
502   }
503
504   ptr->next = async_creation_list;
505   async_creation_list = ptr;
506
507   pthread_mutex_unlock (&async_creation_lock);
508
509   return (0);
510 } /* }}} int lock_file */
511
512 static int unlock_file (char const *filename) /* {{{ */
513 {
514   async_create_file_t *this;
515   async_create_file_t *prev;
516
517
518   pthread_mutex_lock (&async_creation_lock);
519
520   prev = NULL;
521   for (this = async_creation_list; this != NULL; this = this->next)
522   {
523     if (strcmp (filename, this->filename) == 0)
524       break;
525     prev = this;
526   }
527
528   if (this == NULL)
529   {
530     pthread_mutex_unlock (&async_creation_lock);
531     return (ENOENT);
532   }
533
534   if (prev == NULL)
535   {
536     assert (this == async_creation_list);
537     async_creation_list = this->next;
538   }
539   else
540   {
541     assert (this == prev->next);
542     prev->next = this->next;
543   }
544   this->next = NULL;
545
546   pthread_mutex_unlock (&async_creation_lock);
547
548   sfree (this->filename);
549   sfree (this);
550
551   return (0);
552 } /* }}} int unlock_file */
553
554 static void *srrd_create_thread (void *targs) /* {{{ */
555 {
556   srrd_create_args_t *args = targs;
557   char tmpfile[PATH_MAX];
558   int status;
559
560   status = lock_file (args->filename);
561   if (status != 0)
562   {
563     if (status == EEXIST)
564       NOTICE ("srrd_create_thread: File \"%s\" is already being created.",
565           args->filename);
566     else
567       ERROR ("srrd_create_thread: Unable to lock file \"%s\".",
568           args->filename);
569     srrd_create_args_destroy (args);
570     return (0);
571   }
572
573   ssnprintf (tmpfile, sizeof (tmpfile), "%s.async", args->filename);
574
575   status = srrd_create (tmpfile, args->pdp_step, args->last_up,
576       args->argc, (void *) args->argv);
577   if (status != 0)
578   {
579     WARNING ("srrd_create_thread: srrd_create (%s) returned status %i.",
580         args->filename, status);
581     unlink (tmpfile);
582     unlock_file (args->filename);
583     srrd_create_args_destroy (args);
584     return (0);
585   }
586
587   status = rename (tmpfile, args->filename);
588   if (status != 0)
589   {
590     char errbuf[1024];
591     ERROR ("srrd_create_thread: rename (\"%s\", \"%s\") failed: %s",
592         tmpfile, args->filename,
593         sstrerror (errno, errbuf, sizeof (errbuf)));
594     unlink (tmpfile);
595     unlock_file (args->filename);
596     srrd_create_args_destroy (args);
597     return (0);
598   }
599
600   DEBUG ("srrd_create_thread: Successfully created RRD file \"%s\".",
601       args->filename);
602
603   unlock_file (args->filename);
604   srrd_create_args_destroy (args);
605
606   return (0);
607 } /* }}} void *srrd_create_thread */
608
609 static int srrd_create_async (const char *filename, /* {{{ */
610     unsigned long pdp_step, time_t last_up,
611     int argc, const char **argv)
612 {
613   srrd_create_args_t *args;
614   pthread_t thread;
615   pthread_attr_t attr;
616   int status;
617
618   DEBUG ("srrd_create_async: Creating \"%s\" in the background.", filename);
619
620   args = srrd_create_args_create (filename, pdp_step, last_up, argc, argv);
621   if (args == NULL)
622     return (-1);
623
624   status = pthread_attr_init (&attr);
625   if (status != 0)
626   {
627     srrd_create_args_destroy (args);
628     return (-1);
629   }
630
631   status = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
632   if (status != 0)
633   {
634     pthread_attr_destroy (&attr);
635     srrd_create_args_destroy (args);
636     return (-1);
637   }
638
639   status = pthread_create (&thread, &attr, srrd_create_thread, args);
640   if (status != 0)
641   {
642     char errbuf[1024];
643     ERROR ("srrd_create_async: pthread_create failed: %s",
644         sstrerror (status, errbuf, sizeof (errbuf)));
645     pthread_attr_destroy (&attr);
646     srrd_create_args_destroy (args);
647     return (status);
648   }
649
650   pthread_attr_destroy (&attr);
651   /* args is freed in srrd_create_thread(). */
652   return (0);
653 } /* }}} int srrd_create_async */
654
655 /*
656  * Public functions
657  */
658 int cu_rrd_create_file (const char *filename, /* {{{ */
659     const data_set_t *ds, const value_list_t *vl,
660     const rrdcreate_config_t *cfg)
661 {
662   char **argv;
663   int argc;
664   char **rra_def = NULL;
665   int rra_num;
666   char **ds_def = NULL;
667   int ds_num;
668   int status = 0;
669   time_t last_up;
670   unsigned long stepsize;
671
672   if (check_create_dir (filename))
673     return (-1);
674
675   if ((rra_num = rra_get (&rra_def, vl, cfg)) < 1)
676   {
677     ERROR ("cu_rrd_create_file failed: Could not calculate RRAs");
678     return (-1);
679   }
680
681   if ((ds_num = ds_get (&ds_def, ds, vl, cfg)) < 1)
682   {
683     ERROR ("cu_rrd_create_file failed: Could not calculate DSes");
684     rra_free (rra_num, rra_def);
685     return (-1);
686   }
687
688   argc = ds_num + rra_num;
689
690   if ((argv = malloc (sizeof (*argv) * (argc + 1))) == NULL)
691   {
692     char errbuf[1024];
693     ERROR ("cu_rrd_create_file failed: %s",
694         sstrerror (errno, errbuf, sizeof (errbuf)));
695     rra_free (rra_num, rra_def);
696     ds_free (ds_num, ds_def);
697     return (-1);
698   }
699
700   memcpy (argv, ds_def, ds_num * sizeof (char *));
701   memcpy (argv + ds_num, rra_def, rra_num * sizeof (char *));
702   argv[ds_num + rra_num] = NULL;
703
704   last_up = CDTIME_T_TO_TIME_T (vl->time);
705   if (last_up <= 0)
706     last_up = time (NULL);
707   last_up -= 1;
708
709   if (cfg->stepsize > 0)
710     stepsize = cfg->stepsize;
711   else
712     stepsize = (unsigned long) CDTIME_T_TO_TIME_T (vl->interval);
713
714   if (cfg->async)
715   {
716     status = srrd_create_async (filename, stepsize, last_up,
717         argc, (const char **) argv);
718     if (status != 0)
719       WARNING ("cu_rrd_create_file: srrd_create_async (%s) "
720           "returned status %i.",
721           filename, status);
722   }
723   else /* synchronous */
724   {
725     status = lock_file (filename);
726     if (status != 0)
727     {
728       if (status == EEXIST)
729         NOTICE ("cu_rrd_create_file: File \"%s\" is already being created.",
730             filename);
731       else
732         ERROR ("cu_rrd_create_file: Unable to lock file \"%s\".",
733             filename);
734     }
735     else
736     {
737       status = srrd_create (filename, stepsize, last_up,
738           argc, (const char **) argv);
739
740       if (status != 0)
741       {
742         WARNING ("cu_rrd_create_file: srrd_create (%s) returned status %i.",
743             filename, status);
744       }
745       else
746       {
747         DEBUG ("cu_rrd_create_file: Successfully created RRD file \"%s\".",
748             filename);
749       }
750       unlock_file (filename);
751     }
752   }
753
754   free (argv);
755   ds_free (ds_num, ds_def);
756   rra_free (rra_num, rra_def);
757
758   return (status);
759 } /* }}} int cu_rrd_create_file */
760
761 /* vim: set sw=2 sts=2 et fdm=marker : */