Merge branch 'collectd-4.0' into collectd-4.1
[collectd.git] / src / rrdtool.c
1 /**
2  * collectd - src/rrdtool.c
3  * Copyright (C) 2006,2007  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "collectd.h"
23 #include "plugin.h"
24 #include "common.h"
25 #include "utils_avltree.h"
26
27 #if HAVE_PTHREAD_H
28 # include <pthread.h>
29 #endif
30
31 /*
32  * Private types
33  */
34 struct rrd_cache_s
35 {
36         int    values_num;
37         char **values;
38         time_t first_value;
39         time_t last_value;
40         enum
41         {
42                 FLAG_NONE   = 0x00,
43                 FLAG_QUEUED = 0x01
44         } flags;
45 };
46 typedef struct rrd_cache_s rrd_cache_t;
47
48 struct rrd_queue_s
49 {
50         char *filename;
51         struct rrd_queue_s *next;
52 };
53 typedef struct rrd_queue_s rrd_queue_t;
54
55 /*
56  * Private variables
57  */
58 static int rra_timespans[] =
59 {
60         3600,
61         86400,
62         604800,
63         2678400,
64         31622400
65 };
66 static int rra_timespans_num = STATIC_ARRAY_SIZE (rra_timespans);
67
68 static int *rra_timespans_custom = NULL;
69 static int rra_timespans_custom_num = 0;
70
71 static char *rra_types[] =
72 {
73         "AVERAGE",
74         "MIN",
75         "MAX"
76 };
77 static int rra_types_num = STATIC_ARRAY_SIZE (rra_types);
78
79 static const char *config_keys[] =
80 {
81         "CacheTimeout",
82         "CacheFlush",
83         "DataDir",
84         "StepSize",
85         "HeartBeat",
86         "RRARows",
87         "RRATimespan",
88         "XFF"
89 };
90 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
91
92 /* If datadir is zero, the daemon's basedir is used. If stepsize or heartbeat
93  * is zero a default, depending on the `interval' member of the value list is
94  * being used. */
95 static char   *datadir   = NULL;
96 static int     stepsize  = 0;
97 static int     heartbeat = 0;
98 static int     rrarows   = 1200;
99 static double  xff       = 0.1;
100
101 /* XXX: If you need to lock both, cache_lock and queue_lock, at the same time,
102  * ALWAYS lock `cache_lock' first! */
103 static int         cache_timeout = 0;
104 static int         cache_flush_timeout = 0;
105 static time_t      cache_flush_last;
106 static avl_tree_t *cache = NULL;
107 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
108
109 static rrd_queue_t    *queue_head = NULL;
110 static rrd_queue_t    *queue_tail = NULL;
111 static pthread_t       queue_thread = 0;
112 static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER;
113 static pthread_cond_t  queue_cond = PTHREAD_COND_INITIALIZER;
114
115 #if !HAVE_THREADSAFE_LIBRRD
116 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
117 #endif
118
119 static int do_shutdown = 0;
120
121 /* * * * * * * * * *
122  * WARNING:  Magic *
123  * * * * * * * * * */
124
125 static void rra_free (int rra_num, char **rra_def)
126 {
127         int i;
128
129         for (i = 0; i < rra_num; i++)
130         {
131                 sfree (rra_def[i]);
132         }
133         sfree (rra_def);
134 } /* void rra_free */
135
136 static int rra_get (char ***ret, const value_list_t *vl)
137 {
138         char **rra_def;
139         int rra_num;
140
141         int *rts;
142         int  rts_num;
143
144         int rra_max;
145
146         int span;
147
148         int cdp_num;
149         int cdp_len;
150         int i, j;
151
152         char buffer[64];
153
154         /* The stepsize we use here: If it is user-set, use it. If not, use the
155          * interval of the value-list. */
156         int ss;
157
158         if (rrarows <= 0)
159         {
160                 *ret = NULL;
161                 return (-1);
162         }
163
164         ss = (stepsize > 0) ? stepsize : vl->interval;
165         if (ss <= 0)
166         {
167                 *ret = NULL;
168                 return (-1);
169         }
170
171         /* Use the configured timespans or fall back to the built-in defaults */
172         if (rra_timespans_custom_num != 0)
173         {
174                 rts = rra_timespans_custom;
175                 rts_num = rra_timespans_custom_num;
176         }
177         else
178         {
179                 rts = rra_timespans;
180                 rts_num = rra_timespans_num;
181         }
182
183         rra_max = rts_num * rra_types_num;
184
185         if ((rra_def = (char **) malloc ((rra_max + 1) * sizeof (char *))) == NULL)
186                 return (-1);
187         memset (rra_def, '\0', (rra_max + 1) * sizeof (char *));
188         rra_num = 0;
189
190         cdp_len = 0;
191         for (i = 0; i < rts_num; i++)
192         {
193                 span = rts[i];
194
195                 if ((span / ss) < rrarows)
196                         continue;
197
198                 if (cdp_len == 0)
199                         cdp_len = 1;
200                 else
201                         cdp_len = (int) floor (((double) span)
202                                         / ((double) (rrarows * ss)));
203
204                 cdp_num = (int) ceil (((double) span)
205                                 / ((double) (cdp_len * ss)));
206
207                 for (j = 0; j < rra_types_num; j++)
208                 {
209                         if (rra_num >= rra_max)
210                                 break;
211
212                         if (snprintf (buffer, sizeof (buffer), "RRA:%s:%3.1f:%u:%u",
213                                                 rra_types[j], xff,
214                                                 cdp_len, cdp_num) >= sizeof (buffer))
215                         {
216                                 ERROR ("rra_get: Buffer would have been truncated.");
217                                 continue;
218                         }
219
220                         rra_def[rra_num++] = sstrdup (buffer);
221                 }
222         }
223
224 #if COLLECT_DEBUG
225         DEBUG ("rra_num = %i", rra_num);
226         for (i = 0; i < rra_num; i++)
227                 DEBUG ("  %s", rra_def[i]);
228 #endif
229
230         *ret = rra_def;
231         return (rra_num);
232 } /* int rra_get */
233
234 static void ds_free (int ds_num, char **ds_def)
235 {
236         int i;
237
238         for (i = 0; i < ds_num; i++)
239                 if (ds_def[i] != NULL)
240                         free (ds_def[i]);
241         free (ds_def);
242 }
243
244 static int ds_get (char ***ret, const data_set_t *ds, const value_list_t *vl)
245 {
246         char **ds_def;
247         int ds_num;
248
249         char min[32];
250         char max[32];
251         char buffer[128];
252
253         DEBUG ("ds->ds_num = %i", ds->ds_num);
254
255         ds_def = (char **) malloc (ds->ds_num * sizeof (char *));
256         if (ds_def == NULL)
257         {
258                 char errbuf[1024];
259                 ERROR ("rrdtool plugin: malloc failed: %s",
260                                 sstrerror (errno, errbuf, sizeof (errbuf)));
261                 return (-1);
262         }
263         memset (ds_def, '\0', ds->ds_num * sizeof (char *));
264
265         for (ds_num = 0; ds_num < ds->ds_num; ds_num++)
266         {
267                 data_source_t *d = ds->ds + ds_num;
268                 char *type;
269                 int status;
270
271                 ds_def[ds_num] = NULL;
272
273                 if (d->type == DS_TYPE_COUNTER)
274                         type = "COUNTER";
275                 else if (d->type == DS_TYPE_GAUGE)
276                         type = "GAUGE";
277                 else
278                 {
279                         ERROR ("rrdtool plugin: Unknown DS type: %i",
280                                         d->type);
281                         break;
282                 }
283
284                 if (isnan (d->min))
285                 {
286                         strcpy (min, "U");
287                 }
288                 else
289                 {
290                         snprintf (min, sizeof (min), "%lf", d->min);
291                         min[sizeof (min) - 1] = '\0';
292                 }
293
294                 if (isnan (d->max))
295                 {
296                         strcpy (max, "U");
297                 }
298                 else
299                 {
300                         snprintf (max, sizeof (max), "%lf", d->max);
301                         max[sizeof (max) - 1] = '\0';
302                 }
303
304                 status = snprintf (buffer, sizeof (buffer),
305                                 "DS:%s:%s:%i:%s:%s",
306                                 d->name, type,
307                                 (heartbeat > 0) ? heartbeat : (2 * vl->interval),
308                                 min, max);
309                 if ((status < 1) || (status >= sizeof (buffer)))
310                         break;
311
312                 ds_def[ds_num] = sstrdup (buffer);
313         } /* for ds_num = 0 .. ds->ds_num */
314
315 #if COLLECT_DEBUG
316 {
317         int i;
318         DEBUG ("ds_num = %i", ds_num);
319         for (i = 0; i < ds_num; i++)
320                 DEBUG ("  %s", ds_def[i]);
321 }
322 #endif
323
324         if (ds_num != ds->ds_num)
325         {
326                 ds_free (ds_num, ds_def);
327                 return (-1);
328         }
329
330         *ret = ds_def;
331         return (ds_num);
332 }
333
334 #if HAVE_THREADSAFE_LIBRRD
335 static int srrd_create (char *filename, unsigned long pdp_step, time_t last_up,
336                 int argc, char **argv)
337 {
338         int status;
339
340         optind = 0; /* bug in librrd? */
341         rrd_clear_error ();
342
343         status = rrd_create_r (filename, pdp_step, last_up, argc, argv);
344
345         if (status != 0)
346         {
347                 WARNING ("rrdtool plugin: rrd_create_r (%s) failed: %s",
348                                 filename, rrd_get_error ());
349         }
350
351         return (status);
352 } /* int srrd_create */
353
354 static int srrd_update (char *filename, char *template, int argc, char **argv)
355 {
356         int status;
357
358         optind = 0; /* bug in librrd? */
359         rrd_clear_error ();
360
361         status = rrd_update_r (filename, template, argc, argv);
362
363         if (status != 0)
364         {
365                 WARNING ("rrdtool plugin: rrd_update_r (%s) failed: %s",
366                                 filename, rrd_get_error ());
367         }
368
369         return (status);
370 } /* int srrd_update */
371 /* #endif HAVE_THREADSAFE_LIBRRD */
372
373 #else /* !HAVE_THREADSAFE_LIBRRD */
374 static int srrd_create (char *filename, unsigned long pdp_step, time_t last_up,
375                 int argc, char **argv)
376 {
377         int status;
378
379         int new_argc;
380         char **new_argv;
381
382         char pdp_step_str[16];
383         char last_up_str[16];
384
385         new_argc = 6 + argc;
386         new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
387         if (new_argv == NULL)
388         {
389                 ERROR ("rrdtool plugin: malloc failed.");
390                 return (-1);
391         }
392
393         if (last_up == 0)
394                 last_up = time (NULL) - 10;
395
396         snprintf (pdp_step_str, sizeof (pdp_step_str), "%lu", pdp_step);
397         pdp_step_str[sizeof (pdp_step_str) - 1] = '\0';
398         snprintf (last_up_str, sizeof (last_up_str), "%u", (unsigned int) last_up);
399         last_up_str[sizeof (last_up_str) - 1] = '\0';
400
401         new_argv[0] = "create";
402         new_argv[1] = filename;
403         new_argv[2] = "-s";
404         new_argv[3] = pdp_step_str;
405         new_argv[4] = "-b";
406         new_argv[5] = last_up_str;
407
408         memcpy (new_argv + 6, argv, argc * sizeof (char *));
409         new_argv[new_argc] = NULL;
410         
411         pthread_mutex_lock (&librrd_lock);
412         optind = 0; /* bug in librrd? */
413         rrd_clear_error ();
414
415         status = rrd_create (new_argc, new_argv);
416         pthread_mutex_unlock (&librrd_lock);
417
418         if (status != 0)
419         {
420                 WARNING ("rrdtool plugin: rrd_create (%s) failed: %s",
421                                 filename, rrd_get_error ());
422         }
423
424         sfree (new_argv);
425
426         return (status);
427 } /* int srrd_create */
428
429 static int srrd_update (char *filename, char *template, int argc, char **argv)
430 {
431         int status;
432
433         int new_argc;
434         char **new_argv;
435
436         assert (template == NULL);
437
438         new_argc = 2 + argc;
439         new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
440         if (new_argv == NULL)
441         {
442                 ERROR ("rrdtool plugin: malloc failed.");
443                 return (-1);
444         }
445
446         new_argv[0] = "update";
447         new_argv[1] = filename;
448
449         memcpy (new_argv + 2, argv, argc * sizeof (char *));
450         new_argv[new_argc] = NULL;
451
452         pthread_mutex_lock (&librrd_lock);
453         optind = 0; /* bug in librrd? */
454         rrd_clear_error ();
455
456         status = rrd_update (new_argc, new_argv);
457         pthread_mutex_unlock (&librrd_lock);
458
459         if (status != 0)
460         {
461                 WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
462                                 argv[1], rrd_get_error ());
463         }
464
465         sfree (new_argv);
466
467         return (status);
468 } /* int srrd_update */
469 #endif /* !HAVE_THREADSAFE_LIBRRD */
470
471 static int rrd_create_file (char *filename, const data_set_t *ds, const value_list_t *vl)
472 {
473         char **argv;
474         int argc;
475         char **rra_def;
476         int rra_num;
477         char **ds_def;
478         int ds_num;
479         int status = 0;
480
481         if (check_create_dir (filename))
482                 return (-1);
483
484         if ((rra_num = rra_get (&rra_def, vl)) < 1)
485         {
486                 ERROR ("rrd_create_file failed: Could not calculate RRAs");
487                 return (-1);
488         }
489
490         if ((ds_num = ds_get (&ds_def, ds, vl)) < 1)
491         {
492                 ERROR ("rrd_create_file failed: Could not calculate DSes");
493                 return (-1);
494         }
495
496         argc = ds_num + rra_num;
497
498         if ((argv = (char **) malloc (sizeof (char *) * (argc + 1))) == NULL)
499         {
500                 char errbuf[1024];
501                 ERROR ("rrd_create failed: %s",
502                                 sstrerror (errno, errbuf, sizeof (errbuf)));
503                 return (-1);
504         }
505
506         memcpy (argv, ds_def, ds_num * sizeof (char *));
507         memcpy (argv + ds_num, rra_def, rra_num * sizeof (char *));
508         argv[ds_num + rra_num] = NULL;
509
510         assert (vl->time > 10);
511         status = srrd_create (filename,
512                         (stepsize > 0) ? stepsize : vl->interval,
513                         vl->time - 10,
514                         argc, argv);
515
516         free (argv);
517         ds_free (ds_num, ds_def);
518         rra_free (rra_num, rra_def);
519
520         return (status);
521 }
522
523 static int value_list_to_string (char *buffer, int buffer_len,
524                 const data_set_t *ds, const value_list_t *vl)
525 {
526         int offset;
527         int status;
528         int i;
529
530         memset (buffer, '\0', buffer_len);
531
532         status = snprintf (buffer, buffer_len, "%u", (unsigned int) vl->time);
533         if ((status < 1) || (status >= buffer_len))
534                 return (-1);
535         offset = status;
536
537         for (i = 0; i < ds->ds_num; i++)
538         {
539                 if ((ds->ds[i].type != DS_TYPE_COUNTER)
540                                 && (ds->ds[i].type != DS_TYPE_GAUGE))
541                         return (-1);
542
543                 if (ds->ds[i].type == DS_TYPE_COUNTER)
544                         status = snprintf (buffer + offset, buffer_len - offset,
545                                         ":%llu", vl->values[i].counter);
546                 else
547                         status = snprintf (buffer + offset, buffer_len - offset,
548                                         ":%lf", vl->values[i].gauge);
549
550                 if ((status < 1) || (status >= (buffer_len - offset)))
551                         return (-1);
552
553                 offset += status;
554         } /* for ds->ds_num */
555
556         return (0);
557 } /* int value_list_to_string */
558
559 static int value_list_to_filename (char *buffer, int buffer_len,
560                 const data_set_t *ds, const value_list_t *vl)
561 {
562         int offset = 0;
563         int status;
564
565         if (datadir != NULL)
566         {
567                 status = snprintf (buffer + offset, buffer_len - offset,
568                                 "%s/", datadir);
569                 if ((status < 1) || (status >= buffer_len - offset))
570                         return (-1);
571                 offset += status;
572         }
573
574         status = snprintf (buffer + offset, buffer_len - offset,
575                         "%s/", vl->host);
576         if ((status < 1) || (status >= buffer_len - offset))
577                 return (-1);
578         offset += status;
579
580         if (strlen (vl->plugin_instance) > 0)
581                 status = snprintf (buffer + offset, buffer_len - offset,
582                                 "%s-%s/", vl->plugin, vl->plugin_instance);
583         else
584                 status = snprintf (buffer + offset, buffer_len - offset,
585                                 "%s/", vl->plugin);
586         if ((status < 1) || (status >= buffer_len - offset))
587                 return (-1);
588         offset += status;
589
590         if (strlen (vl->type_instance) > 0)
591                 status = snprintf (buffer + offset, buffer_len - offset,
592                                 "%s-%s.rrd", ds->type, vl->type_instance);
593         else
594                 status = snprintf (buffer + offset, buffer_len - offset,
595                                 "%s.rrd", ds->type);
596         if ((status < 1) || (status >= buffer_len - offset))
597                 return (-1);
598         offset += status;
599
600         return (0);
601 } /* int value_list_to_filename */
602
603 static void *rrd_queue_thread (void *data)
604 {
605         while (42)
606         {
607                 rrd_queue_t *queue_entry;
608                 rrd_cache_t *cache_entry;
609                 char **values;
610                 int    values_num;
611                 int    i;
612
613                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
614                  * the same time, ALWAYS lock `cache_lock' first! */
615
616                 /* wait until an entry is available */
617                 pthread_mutex_lock (&queue_lock);
618                 while ((queue_head == NULL) && (do_shutdown == 0))
619                         pthread_cond_wait (&queue_cond, &queue_lock);
620
621                 /* We're in the shutdown phase */
622                 if (queue_head == NULL)
623                 {
624                         pthread_mutex_unlock (&queue_lock);
625                         break;
626                 }
627
628                 /* Dequeue the first entry */
629                 queue_entry = queue_head;
630                 if (queue_head == queue_tail)
631                         queue_head = queue_tail = NULL;
632                 else
633                         queue_head = queue_head->next;
634
635                 /* Unlock the queue again */
636                 pthread_mutex_unlock (&queue_lock);
637
638                 /* We now need the cache lock so the entry isn't updated while
639                  * we make a copy of it's values */
640                 pthread_mutex_lock (&cache_lock);
641
642                 avl_get (cache, queue_entry->filename, (void *) &cache_entry);
643
644                 values = cache_entry->values;
645                 values_num = cache_entry->values_num;
646
647                 cache_entry->values = NULL;
648                 cache_entry->values_num = 0;
649                 cache_entry->flags = FLAG_NONE;
650
651                 pthread_mutex_unlock (&cache_lock);
652
653                 /* Write the values to the RRD-file */
654                 srrd_update (queue_entry->filename, NULL, values_num, values);
655
656                 for (i = 0; i < values_num; i++)
657                 {
658                         sfree (values[i]);
659                 }
660                 sfree (values);
661                 sfree (queue_entry->filename);
662                 sfree (queue_entry);
663         } /* while (42) */
664
665         pthread_mutex_lock (&cache_lock);
666         avl_destroy (cache);
667         cache = NULL;
668         pthread_mutex_unlock (&cache_lock);
669
670         pthread_exit ((void *) 0);
671         return ((void *) 0);
672 } /* void *rrd_queue_thread */
673
674 static int rrd_queue_cache_entry (const char *filename)
675 {
676         rrd_queue_t *queue_entry;
677
678         queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
679         if (queue_entry == NULL)
680                 return (-1);
681
682         queue_entry->filename = strdup (filename);
683         if (queue_entry->filename == NULL)
684         {
685                 free (queue_entry);
686                 return (-1);
687         }
688
689         queue_entry->next = NULL;
690
691         pthread_mutex_lock (&queue_lock);
692         if (queue_tail == NULL)
693                 queue_head = queue_entry;
694         else
695                 queue_tail->next = queue_entry;
696         queue_tail = queue_entry;
697         pthread_cond_signal (&queue_cond);
698         pthread_mutex_unlock (&queue_lock);
699
700         DEBUG ("rrdtool plugin: Put `%s' into the update queue", filename);
701
702         return (0);
703 } /* int rrd_queue_cache_entry */
704
705 static void rrd_cache_flush (int timeout)
706 {
707         rrd_cache_t *rc;
708         time_t       now;
709
710         char **keys = NULL;
711         int    keys_num = 0;
712
713         char *key;
714         avl_iterator_t *iter;
715         int i;
716
717         DEBUG ("rrdtool plugin: Flushing cache, timeout = %i", timeout);
718
719         now = time (NULL);
720
721         /* Build a list of entries to be flushed */
722         iter = avl_get_iterator (cache);
723         while (avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
724         {
725                 DEBUG ("key = %s; age = %i;", key, now - rc->first_value);
726
727                 if (rc->flags == FLAG_QUEUED)
728                         continue;
729                 else if ((now - rc->first_value) < timeout)
730                         continue;
731                 else if (rc->values_num > 0)
732                 {
733                         if (rrd_queue_cache_entry (key) == 0)
734                                 rc->flags = FLAG_QUEUED;
735                 }
736                 else /* ancient and no values -> waste of memory */
737                 {
738                         keys = (char **) realloc ((void *) keys,
739                                         (keys_num + 1) * sizeof (char *));
740                         if (keys == NULL)
741                         {
742                                 char errbuf[1024];
743                                 ERROR ("rrdtool plugin: "
744                                                 "realloc failed: %s",
745                                                 sstrerror (errno, errbuf,
746                                                         sizeof (errbuf)));
747                                 avl_iterator_destroy (iter);
748                                 return;
749                         }
750                         keys[keys_num] = key;
751                         keys_num++;
752                 }
753         } /* while (avl_iterator_next) */
754         avl_iterator_destroy (iter);
755         
756         for (i = 0; i < keys_num; i++)
757         {
758                 if (avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
759                 {
760                         DEBUG ("rrdtool plugin: avl_remove (%s) failed.", keys[i]);
761                         continue;
762                 }
763
764                 assert (rc->values == NULL);
765                 assert (rc->values_num == 0);
766
767                 sfree (rc);
768                 sfree (key);
769                 keys[i] = NULL;
770         } /* for (i = 0..keys_num) */
771
772         free (keys);
773
774         cache_flush_last = now;
775 } /* void rrd_cache_flush */
776
777 static int rrd_cache_insert (const char *filename,
778                 const char *value, time_t value_time)
779 {
780         rrd_cache_t *rc = NULL;
781         int new_rc = 0;
782         char **values_new;
783
784         pthread_mutex_lock (&cache_lock);
785
786         avl_get (cache, filename, (void *) &rc);
787
788         if (rc == NULL)
789         {
790                 rc = (rrd_cache_t *) malloc (sizeof (rrd_cache_t));
791                 if (rc == NULL)
792                         return (-1);
793                 rc->values_num = 0;
794                 rc->values = NULL;
795                 rc->first_value = 0;
796                 rc->last_value = 0;
797                 rc->flags = FLAG_NONE;
798                 new_rc = 1;
799         }
800
801         if (rc->last_value >= value_time)
802         {
803                 pthread_mutex_unlock (&cache_lock);
804                 WARNING ("rrdtool plugin: (rc->last_value = %u) >= (value_time = %u)",
805                                 (unsigned int) rc->last_value,
806                                 (unsigned int) value_time);
807                 return (-1);
808         }
809
810         values_new = (char **) realloc ((void *) rc->values,
811                         (rc->values_num + 1) * sizeof (char *));
812         if (values_new == NULL)
813         {
814                 char errbuf[1024];
815                 void *cache_key = NULL;
816
817                 sstrerror (errno, errbuf, sizeof (errbuf));
818
819                 avl_remove (cache, filename, &cache_key, NULL);
820                 pthread_mutex_unlock (&cache_lock);
821
822                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
823
824                 sfree (cache_key);
825                 sfree (rc->values);
826                 sfree (rc);
827                 return (-1);
828         }
829         rc->values = values_new;
830
831         rc->values[rc->values_num] = strdup (value);
832         if (rc->values[rc->values_num] != NULL)
833                 rc->values_num++;
834
835         if (rc->values_num == 1)
836                 rc->first_value = value_time;
837         rc->last_value = value_time;
838
839         /* Insert if this is the first value */
840         if (new_rc == 1)
841         {
842                 void *cache_key = strdup (filename);
843
844                 if (cache_key == NULL)
845                 {
846                         char errbuf[1024];
847                         sstrerror (errno, errbuf, sizeof (errbuf));
848
849                         pthread_mutex_unlock (&cache_lock);
850
851                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
852
853                         sfree (rc->values[0]);
854                         sfree (rc->values);
855                         sfree (rc);
856                         return (-1);
857                 }
858
859                 avl_insert (cache, cache_key, rc);
860         }
861
862         DEBUG ("rrd_cache_insert (%s, %s, %u) = %p", filename, value,
863                         (unsigned int) value_time, (void *) rc);
864
865         if ((rc->last_value - rc->first_value) >= cache_timeout)
866         {
867                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
868                  * the same time, ALWAYS lock `cache_lock' first! */
869                 if (rc->flags != FLAG_QUEUED)
870                 {
871                         if (rrd_queue_cache_entry (filename) == 0)
872                                 rc->flags = FLAG_QUEUED;
873                 }
874                 else
875                 {
876                         DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
877                 }
878         }
879
880         if ((cache_timeout > 0) &&
881                         ((time (NULL) - cache_flush_last) > cache_flush_timeout))
882                 rrd_cache_flush (cache_flush_timeout);
883
884
885         pthread_mutex_unlock (&cache_lock);
886
887         return (0);
888 } /* int rrd_cache_insert */
889
890 static int rrd_write (const data_set_t *ds, const value_list_t *vl)
891 {
892         struct stat  statbuf;
893         char         filename[512];
894         char         values[512];
895         int          status;
896
897         if (value_list_to_filename (filename, sizeof (filename), ds, vl) != 0)
898                 return (-1);
899
900         if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
901                 return (-1);
902
903         if (stat (filename, &statbuf) == -1)
904         {
905                 if (errno == ENOENT)
906                 {
907                         if (rrd_create_file (filename, ds, vl))
908                                 return (-1);
909                 }
910                 else
911                 {
912                         char errbuf[1024];
913                         ERROR ("stat(%s) failed: %s", filename,
914                                         sstrerror (errno, errbuf,
915                                                 sizeof (errbuf)));
916                         return (-1);
917                 }
918         }
919         else if (!S_ISREG (statbuf.st_mode))
920         {
921                 ERROR ("stat(%s): Not a regular file!",
922                                 filename);
923                 return (-1);
924         }
925
926         status = rrd_cache_insert (filename, values, vl->time);
927
928         return (status);
929 } /* int rrd_write */
930
931 static int rrd_config (const char *key, const char *value)
932 {
933         if (strcasecmp ("CacheTimeout", key) == 0)
934         {
935                 int tmp = atoi (value);
936                 if (tmp < 0)
937                 {
938                         fprintf (stderr, "rrdtool: `CacheTimeout' must "
939                                         "be greater than 0.\n");
940                         return (1);
941                 }
942                 cache_timeout = tmp;
943         }
944         else if (strcasecmp ("CacheFlush", key) == 0)
945         {
946                 int tmp = atoi (value);
947                 if (tmp < 0)
948                 {
949                         fprintf (stderr, "rrdtool: `CacheFlush' must "
950                                         "be greater than 0.\n");
951                         return (1);
952                 }
953                 cache_flush_timeout = tmp;
954         }
955         else if (strcasecmp ("DataDir", key) == 0)
956         {
957                 if (datadir != NULL)
958                         free (datadir);
959                 datadir = strdup (value);
960                 if (datadir != NULL)
961                 {
962                         int len = strlen (datadir);
963                         while ((len > 0) && (datadir[len - 1] == '/'))
964                         {
965                                 len--;
966                                 datadir[len] = '\0';
967                         }
968                         if (len <= 0)
969                         {
970                                 free (datadir);
971                                 datadir = NULL;
972                         }
973                 }
974         }
975         else if (strcasecmp ("StepSize", key) == 0)
976         {
977                 stepsize = atoi (value);
978                 if (stepsize < 0)
979                         stepsize = 0;
980         }
981         else if (strcasecmp ("HeartBeat", key) == 0)
982         {
983                 heartbeat = atoi (value);
984                 if (heartbeat < 0)
985                         heartbeat = 0;
986         }
987         else if (strcasecmp ("RRARows", key) == 0)
988         {
989                 int tmp = atoi (value);
990                 if (tmp <= 0)
991                 {
992                         fprintf (stderr, "rrdtool: `RRARows' must "
993                                         "be greater than 0.\n");
994                         return (1);
995                 }
996                 rrarows = tmp;
997         }
998         else if (strcasecmp ("RRATimespan", key) == 0)
999         {
1000                 char *saveptr = NULL;
1001                 char *dummy;
1002                 char *ptr;
1003                 char *value_copy;
1004                 int *tmp_alloc;
1005
1006                 value_copy = strdup (value);
1007                 if (value_copy == NULL)
1008                         return (1);
1009
1010                 dummy = value_copy;
1011                 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
1012                 {
1013                         dummy = NULL;
1014                         
1015                         tmp_alloc = realloc (rra_timespans_custom,
1016                                         sizeof (int) * (rra_timespans_custom_num + 1));
1017                         if (tmp_alloc == NULL)
1018                         {
1019                                 fprintf (stderr, "rrdtool: realloc failed.\n");
1020                                 free (value_copy);
1021                                 return (1);
1022                         }
1023                         rra_timespans_custom = tmp_alloc;
1024                         rra_timespans_custom[rra_timespans_custom_num] = atoi (ptr);
1025                         if (rra_timespans_custom[rra_timespans_custom_num] != 0)
1026                                 rra_timespans_custom_num++;
1027                 } /* while (strtok_r) */
1028                 free (value_copy);
1029         }
1030         else if (strcasecmp ("XFF", key) == 0)
1031         {
1032                 double tmp = atof (value);
1033                 if ((tmp < 0.0) || (tmp >= 1.0))
1034                 {
1035                         fprintf (stderr, "rrdtool: `XFF' must "
1036                                         "be in the range 0 to 1 (exclusive).");
1037                         return (1);
1038                 }
1039                 xff = tmp;
1040         }
1041         else
1042         {
1043                 return (-1);
1044         }
1045         return (0);
1046 } /* int rrd_config */
1047
1048 static int rrd_shutdown (void)
1049 {
1050         pthread_mutex_lock (&cache_lock);
1051         rrd_cache_flush (-1);
1052         pthread_mutex_unlock (&cache_lock);
1053
1054         /* Wait for all the values to be written to disk before returning. */
1055         if (queue_thread != 0)
1056         {
1057                 pthread_join (queue_thread, NULL);
1058                 queue_thread = 0;
1059                 DEBUG ("rrdtool plugin: queue_thread exited.");
1060         }
1061
1062         pthread_mutex_lock (&queue_lock);
1063         do_shutdown = 1;
1064         pthread_cond_signal (&queue_cond);
1065         pthread_mutex_unlock (&queue_lock);
1066
1067         return (0);
1068 } /* int rrd_shutdown */
1069
1070 static int rrd_init (void)
1071 {
1072         int status;
1073
1074         if (stepsize < 0)
1075                 stepsize = 0;
1076         if (heartbeat <= 0)
1077         {
1078                 if (stepsize > 0)
1079                         heartbeat = 2 * stepsize;
1080                 else
1081                         heartbeat = 0;
1082         }
1083
1084         if ((heartbeat > 0) && (heartbeat < interval_g))
1085                 WARNING ("rrdtool plugin: Your `heartbeat' is "
1086                                 "smaller than your `interval'. This will "
1087                                 "likely cause problems.");
1088         else if ((stepsize > 0) && (stepsize < interval_g))
1089                 WARNING ("rrdtool plugin: Your `stepsize' is "
1090                                 "smaller than your `interval'. This will "
1091                                 "create needlessly big RRD-files.");
1092
1093         /* Set the cache up */
1094         pthread_mutex_lock (&cache_lock);
1095
1096         cache = avl_create ((int (*) (const void *, const void *)) strcmp);
1097         if (cache == NULL)
1098         {
1099                 ERROR ("rrdtool plugin: avl_create failed.");
1100                 return (-1);
1101         }
1102
1103         cache_flush_last = time (NULL);
1104         if (cache_timeout < 2)
1105         {
1106                 cache_timeout = 0;
1107                 cache_flush_timeout = 0;
1108         }
1109         else if (cache_flush_timeout < cache_timeout)
1110                 cache_flush_timeout = 10 * cache_timeout;
1111
1112         pthread_mutex_unlock (&cache_lock);
1113
1114         status = pthread_create (&queue_thread, NULL, rrd_queue_thread, NULL);
1115         if (status != 0)
1116         {
1117                 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1118                 return (-1);
1119         }
1120
1121         DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %i;"
1122                         " heartbeat = %i; rrarows = %i; xff = %lf;",
1123                         (datadir == NULL) ? "(null)" : datadir,
1124                         stepsize, heartbeat, rrarows, xff);
1125
1126         return (0);
1127 } /* int rrd_init */
1128
1129 void module_register (void)
1130 {
1131         plugin_register_config ("rrdtool", rrd_config,
1132                         config_keys, config_keys_num);
1133         plugin_register_init ("rrdtool", rrd_init);
1134         plugin_register_write ("rrdtool", rrd_write);
1135         plugin_register_shutdown ("rrdtool", rrd_shutdown);
1136 }