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