rrdtool plugin: Beatify a debugging message.
[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    i;
284
285                 pthread_mutex_lock (&queue_lock);
286                 /* Wait for values to arrive */
287                 while (true)
288                 {
289                   struct timespec ts_wait;
290                   int status;
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                 c_avl_get (cache, queue_entry->filename, (void *) &cache_entry);
366
367                 values = cache_entry->values;
368                 values_num = cache_entry->values_num;
369
370                 cache_entry->values = NULL;
371                 cache_entry->values_num = 0;
372                 cache_entry->flags = FLAG_NONE;
373
374                 pthread_mutex_unlock (&cache_lock);
375
376                 /* Update `tv_next_update' */
377                 if (write_rate > 0.0) 
378                 {
379                   gettimeofday (&tv_now, /* timezone = */ NULL);
380                   tv_next_update.tv_sec = tv_now.tv_sec;
381                   tv_next_update.tv_usec = tv_now.tv_usec
382                     + ((suseconds_t) (1000000 * write_rate));
383                   while (tv_next_update.tv_usec > 1000000)
384                   {
385                     tv_next_update.tv_sec++;
386                     tv_next_update.tv_usec -= 1000000;
387                   }
388                 }
389
390                 /* Write the values to the RRD-file */
391                 srrd_update (queue_entry->filename, NULL,
392                                 values_num, (const char **)values);
393                 DEBUG ("rrdtool plugin: queue thread: Wrote %i value%s to %s",
394                                 values_num, (values_num == 1) ? "" : "s",
395                                 queue_entry->filename);
396
397                 for (i = 0; i < values_num; i++)
398                 {
399                         sfree (values[i]);
400                 }
401                 sfree (values);
402                 sfree (queue_entry->filename);
403                 sfree (queue_entry);
404         } /* while (42) */
405
406         pthread_mutex_lock (&cache_lock);
407         c_avl_destroy (cache);
408         cache = NULL;
409         pthread_mutex_unlock (&cache_lock);
410
411         pthread_exit ((void *) 0);
412         return ((void *) 0);
413 } /* void *rrd_queue_thread */
414
415 static int rrd_queue_enqueue (const char *filename,
416     rrd_queue_t **head, rrd_queue_t **tail)
417 {
418   rrd_queue_t *queue_entry;
419
420   queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
421   if (queue_entry == NULL)
422     return (-1);
423
424   queue_entry->filename = strdup (filename);
425   if (queue_entry->filename == NULL)
426   {
427     free (queue_entry);
428     return (-1);
429   }
430
431   queue_entry->next = NULL;
432
433   pthread_mutex_lock (&queue_lock);
434
435   if (*tail == NULL)
436     *head = queue_entry;
437   else
438     (*tail)->next = queue_entry;
439   *tail = queue_entry;
440
441   pthread_cond_signal (&queue_cond);
442   pthread_mutex_unlock (&queue_lock);
443
444   return (0);
445 } /* int rrd_queue_enqueue */
446
447 static int rrd_queue_dequeue (const char *filename,
448     rrd_queue_t **head, rrd_queue_t **tail)
449 {
450   rrd_queue_t *this;
451   rrd_queue_t *prev;
452
453   pthread_mutex_lock (&queue_lock);
454
455   prev = NULL;
456   this = *head;
457
458   while (this != NULL)
459   {
460     if (strcmp (this->filename, filename) == 0)
461       break;
462     
463     prev = this;
464     this = this->next;
465   }
466
467   if (this == NULL)
468   {
469     pthread_mutex_unlock (&queue_lock);
470     return (-1);
471   }
472
473   if (prev == NULL)
474     *head = this->next;
475   else
476     prev->next = this->next;
477
478   if (this->next == NULL)
479     *tail = prev;
480
481   pthread_mutex_unlock (&queue_lock);
482
483   sfree (this->filename);
484   sfree (this);
485
486   return (0);
487 } /* int rrd_queue_dequeue */
488
489 static void rrd_cache_flush (int timeout)
490 {
491         rrd_cache_t *rc;
492         time_t       now;
493
494         char **keys = NULL;
495         int    keys_num = 0;
496
497         char *key;
498         c_avl_iterator_t *iter;
499         int i;
500
501         DEBUG ("rrdtool plugin: Flushing cache, timeout = %i", timeout);
502
503         now = time (NULL);
504
505         /* Build a list of entries to be flushed */
506         iter = c_avl_get_iterator (cache);
507         while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
508         {
509                 if (rc->flags != FLAG_NONE)
510                         continue;
511                 else if ((now - rc->first_value) < timeout)
512                         continue;
513                 else if (rc->values_num > 0)
514                 {
515                         int status;
516
517                         status = rrd_queue_enqueue (key, &queue_head,  &queue_tail);
518                         if (status == 0)
519                                 rc->flags = FLAG_QUEUED;
520                 }
521                 else /* ancient and no values -> waste of memory */
522                 {
523                         char **tmp = (char **) realloc ((void *) keys,
524                                         (keys_num + 1) * sizeof (char *));
525                         if (tmp == NULL)
526                         {
527                                 char errbuf[1024];
528                                 ERROR ("rrdtool plugin: "
529                                                 "realloc failed: %s",
530                                                 sstrerror (errno, errbuf,
531                                                         sizeof (errbuf)));
532                                 c_avl_iterator_destroy (iter);
533                                 sfree (keys);
534                                 return;
535                         }
536                         keys = tmp;
537                         keys[keys_num] = key;
538                         keys_num++;
539                 }
540         } /* while (c_avl_iterator_next) */
541         c_avl_iterator_destroy (iter);
542         
543         for (i = 0; i < keys_num; i++)
544         {
545                 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
546                 {
547                         DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
548                         continue;
549                 }
550
551                 assert (rc->values == NULL);
552                 assert (rc->values_num == 0);
553
554                 sfree (rc);
555                 sfree (key);
556                 keys[i] = NULL;
557         } /* for (i = 0..keys_num) */
558
559         sfree (keys);
560
561         cache_flush_last = now;
562 } /* void rrd_cache_flush */
563
564 static int rrd_cache_flush_identifier (int timeout, const char *identifier)
565 {
566   rrd_cache_t *rc;
567   time_t now;
568   int status;
569   char key[2048];
570
571   if (identifier == NULL)
572   {
573     rrd_cache_flush (timeout);
574     return (0);
575   }
576
577   now = time (NULL);
578
579   if (datadir == NULL)
580     snprintf (key, sizeof (key), "%s.rrd",
581         identifier);
582   else
583     snprintf (key, sizeof (key), "%s/%s.rrd",
584         datadir, identifier);
585   key[sizeof (key) - 1] = 0;
586
587   status = c_avl_get (cache, key, (void *) &rc);
588   if (status != 0)
589   {
590     WARNING ("rrdtool plugin: rrd_cache_flush_identifier: "
591         "c_avl_get (%s) failed. Does that file really exist?",
592         key);
593     return (status);
594   }
595
596   if (rc->flags == FLAG_FLUSHQ)
597   {
598     status = 0;
599   }
600   else if (rc->flags == FLAG_QUEUED)
601   {
602     rrd_queue_dequeue (key, &queue_head, &queue_tail);
603     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
604     if (status == 0)
605       rc->flags = FLAG_FLUSHQ;
606   }
607   else if ((now - rc->first_value) < timeout)
608   {
609     status = 0;
610   }
611   else if (rc->values_num > 0)
612   {
613     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
614     if (status == 0)
615       rc->flags = FLAG_FLUSHQ;
616   }
617
618   return (status);
619 } /* int rrd_cache_flush_identifier */
620
621 static int rrd_cache_insert (const char *filename,
622                 const char *value, time_t value_time)
623 {
624         rrd_cache_t *rc = NULL;
625         int new_rc = 0;
626         char **values_new;
627
628         pthread_mutex_lock (&cache_lock);
629
630         c_avl_get (cache, filename, (void *) &rc);
631
632         if (rc == NULL)
633         {
634                 rc = (rrd_cache_t *) malloc (sizeof (rrd_cache_t));
635                 if (rc == NULL)
636                         return (-1);
637                 rc->values_num = 0;
638                 rc->values = NULL;
639                 rc->first_value = 0;
640                 rc->last_value = 0;
641                 rc->flags = FLAG_NONE;
642                 new_rc = 1;
643         }
644
645         if (rc->last_value >= value_time)
646         {
647                 pthread_mutex_unlock (&cache_lock);
648                 WARNING ("rrdtool plugin: (rc->last_value = %u) >= (value_time = %u)",
649                                 (unsigned int) rc->last_value,
650                                 (unsigned int) value_time);
651                 return (-1);
652         }
653
654         values_new = (char **) realloc ((void *) rc->values,
655                         (rc->values_num + 1) * sizeof (char *));
656         if (values_new == NULL)
657         {
658                 char errbuf[1024];
659                 void *cache_key = NULL;
660
661                 sstrerror (errno, errbuf, sizeof (errbuf));
662
663                 c_avl_remove (cache, filename, &cache_key, NULL);
664                 pthread_mutex_unlock (&cache_lock);
665
666                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
667
668                 sfree (cache_key);
669                 sfree (rc->values);
670                 sfree (rc);
671                 return (-1);
672         }
673         rc->values = values_new;
674
675         rc->values[rc->values_num] = strdup (value);
676         if (rc->values[rc->values_num] != NULL)
677                 rc->values_num++;
678
679         if (rc->values_num == 1)
680                 rc->first_value = value_time;
681         rc->last_value = value_time;
682
683         /* Insert if this is the first value */
684         if (new_rc == 1)
685         {
686                 void *cache_key = strdup (filename);
687
688                 if (cache_key == NULL)
689                 {
690                         char errbuf[1024];
691                         sstrerror (errno, errbuf, sizeof (errbuf));
692
693                         pthread_mutex_unlock (&cache_lock);
694
695                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
696
697                         sfree (rc->values[0]);
698                         sfree (rc->values);
699                         sfree (rc);
700                         return (-1);
701                 }
702
703                 c_avl_insert (cache, cache_key, rc);
704         }
705
706         DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
707                         "values_num = %i; age = %lu;",
708                         filename, rc->values_num,
709                         (unsigned long)(rc->last_value - rc->first_value));
710
711         if ((rc->last_value - rc->first_value) >= cache_timeout)
712         {
713                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
714                  * the same time, ALWAYS lock `cache_lock' first! */
715                 if (rc->flags == FLAG_NONE)
716                 {
717                         int status;
718
719                         status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
720                         if (status == 0)
721                                 rc->flags = FLAG_QUEUED;
722                 }
723                 else
724                 {
725                         DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
726                 }
727         }
728
729         if ((cache_timeout > 0) &&
730                         ((time (NULL) - cache_flush_last) > cache_flush_timeout))
731                 rrd_cache_flush (cache_flush_timeout);
732
733         pthread_mutex_unlock (&cache_lock);
734
735         return (0);
736 } /* int rrd_cache_insert */
737
738 static int rrd_compare_numeric (const void *a_ptr, const void *b_ptr)
739 {
740         int a = *((int *) a_ptr);
741         int b = *((int *) b_ptr);
742
743         if (a < b)
744                 return (-1);
745         else if (a > b)
746                 return (1);
747         else
748                 return (0);
749 } /* int rrd_compare_numeric */
750
751 static int rrd_write (const data_set_t *ds, const value_list_t *vl,
752                 user_data_t __attribute__((unused)) *user_data)
753 {
754         struct stat  statbuf;
755         char         filename[512];
756         char         values[512];
757         int          status;
758
759         if (0 != strcmp (ds->type, vl->type)) {
760                 ERROR ("rrdtool plugin: DS type does not match value list type");
761                 return -1;
762         }
763
764         if (value_list_to_filename (filename, sizeof (filename), ds, vl) != 0)
765                 return (-1);
766
767         if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
768                 return (-1);
769
770         if (stat (filename, &statbuf) == -1)
771         {
772                 if (errno == ENOENT)
773                 {
774                         status = cu_rrd_create_file (filename,
775                                         ds, vl, &rrdcreate_config);
776                         if (status != 0)
777                                 return (-1);
778                 }
779                 else
780                 {
781                         char errbuf[1024];
782                         ERROR ("stat(%s) failed: %s", filename,
783                                         sstrerror (errno, errbuf,
784                                                 sizeof (errbuf)));
785                         return (-1);
786                 }
787         }
788         else if (!S_ISREG (statbuf.st_mode))
789         {
790                 ERROR ("stat(%s): Not a regular file!",
791                                 filename);
792                 return (-1);
793         }
794
795         status = rrd_cache_insert (filename, values, vl->time);
796
797         return (status);
798 } /* int rrd_write */
799
800 static int rrd_flush (int timeout, const char *identifier,
801                 user_data_t __attribute__((unused)) *user_data)
802 {
803         pthread_mutex_lock (&cache_lock);
804
805         if (cache == NULL) {
806                 pthread_mutex_unlock (&cache_lock);
807                 return (0);
808         }
809
810         rrd_cache_flush_identifier (timeout, identifier);
811
812         pthread_mutex_unlock (&cache_lock);
813         return (0);
814 } /* int rrd_flush */
815
816 static int rrd_config (const char *key, const char *value)
817 {
818         if (strcasecmp ("CacheTimeout", key) == 0)
819         {
820                 int tmp = atoi (value);
821                 if (tmp < 0)
822                 {
823                         fprintf (stderr, "rrdtool: `CacheTimeout' must "
824                                         "be greater than 0.\n");
825                         ERROR ("rrdtool: `CacheTimeout' must "
826                                         "be greater than 0.\n");
827                         return (1);
828                 }
829                 cache_timeout = tmp;
830         }
831         else if (strcasecmp ("CacheFlush", key) == 0)
832         {
833                 int tmp = atoi (value);
834                 if (tmp < 0)
835                 {
836                         fprintf (stderr, "rrdtool: `CacheFlush' must "
837                                         "be greater than 0.\n");
838                         ERROR ("rrdtool: `CacheFlush' must "
839                                         "be greater than 0.\n");
840                         return (1);
841                 }
842                 cache_flush_timeout = tmp;
843         }
844         else if (strcasecmp ("DataDir", key) == 0)
845         {
846                 if (datadir != NULL)
847                         free (datadir);
848                 datadir = strdup (value);
849                 if (datadir != NULL)
850                 {
851                         int len = strlen (datadir);
852                         while ((len > 0) && (datadir[len - 1] == '/'))
853                         {
854                                 len--;
855                                 datadir[len] = '\0';
856                         }
857                         if (len <= 0)
858                         {
859                                 free (datadir);
860                                 datadir = NULL;
861                         }
862                 }
863         }
864         else if (strcasecmp ("StepSize", key) == 0)
865         {
866                 int temp = atoi (value);
867                 if (temp > 0)
868                         rrdcreate_config.stepsize = temp;
869         }
870         else if (strcasecmp ("HeartBeat", key) == 0)
871         {
872                 int temp = atoi (value);
873                 if (temp > 0)
874                         rrdcreate_config.heartbeat = temp;
875         }
876         else if (strcasecmp ("RRARows", key) == 0)
877         {
878                 int tmp = atoi (value);
879                 if (tmp <= 0)
880                 {
881                         fprintf (stderr, "rrdtool: `RRARows' must "
882                                         "be greater than 0.\n");
883                         ERROR ("rrdtool: `RRARows' must "
884                                         "be greater than 0.\n");
885                         return (1);
886                 }
887                 rrdcreate_config.rrarows = tmp;
888         }
889         else if (strcasecmp ("RRATimespan", key) == 0)
890         {
891                 char *saveptr = NULL;
892                 char *dummy;
893                 char *ptr;
894                 char *value_copy;
895                 int *tmp_alloc;
896
897                 value_copy = strdup (value);
898                 if (value_copy == NULL)
899                         return (1);
900
901                 dummy = value_copy;
902                 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
903                 {
904                         dummy = NULL;
905                         
906                         tmp_alloc = realloc (rrdcreate_config.timespans,
907                                         sizeof (int) * (rrdcreate_config.timespans_num + 1));
908                         if (tmp_alloc == NULL)
909                         {
910                                 fprintf (stderr, "rrdtool: realloc failed.\n");
911                                 ERROR ("rrdtool: realloc failed.\n");
912                                 free (value_copy);
913                                 return (1);
914                         }
915                         rrdcreate_config.timespans = tmp_alloc;
916                         rrdcreate_config.timespans[rrdcreate_config.timespans_num] = atoi (ptr);
917                         if (rrdcreate_config.timespans[rrdcreate_config.timespans_num] != 0)
918                                 rrdcreate_config.timespans_num++;
919                 } /* while (strtok_r) */
920
921                 qsort (/* base = */ rrdcreate_config.timespans,
922                                 /* nmemb  = */ rrdcreate_config.timespans_num,
923                                 /* size   = */ sizeof (rrdcreate_config.timespans[0]),
924                                 /* compar = */ rrd_compare_numeric);
925
926                 free (value_copy);
927         }
928         else if (strcasecmp ("XFF", key) == 0)
929         {
930                 double tmp = atof (value);
931                 if ((tmp < 0.0) || (tmp >= 1.0))
932                 {
933                         fprintf (stderr, "rrdtool: `XFF' must "
934                                         "be in the range 0 to 1 (exclusive).");
935                         ERROR ("rrdtool: `XFF' must "
936                                         "be in the range 0 to 1 (exclusive).");
937                         return (1);
938                 }
939                 rrdcreate_config.xff = tmp;
940         }
941         else if (strcasecmp ("WritesPerSecond", key) == 0)
942         {
943                 double wps = atof (value);
944
945                 if (wps < 0.0)
946                 {
947                         fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
948                                         "greater than or equal to zero.");
949                         return (1);
950                 }
951                 else if (wps == 0.0)
952                 {
953                         write_rate = 0.0;
954                 }
955                 else
956                 {
957                         write_rate = 1.0 / wps;
958                 }
959         }
960         else
961         {
962                 return (-1);
963         }
964         return (0);
965 } /* int rrd_config */
966
967 static int rrd_shutdown (void)
968 {
969         pthread_mutex_lock (&cache_lock);
970         rrd_cache_flush (-1);
971         pthread_mutex_unlock (&cache_lock);
972
973         pthread_mutex_lock (&queue_lock);
974         do_shutdown = 1;
975         pthread_cond_signal (&queue_cond);
976         pthread_mutex_unlock (&queue_lock);
977
978         if ((queue_thread_running != 0)
979                         && ((queue_head != NULL) || (flushq_head != NULL)))
980         {
981                 INFO ("rrdtool plugin: Shutting down the queue thread. "
982                                 "This may take a while.");
983         }
984         else if (queue_thread_running != 0)
985         {
986                 INFO ("rrdtool plugin: Shutting down the queue thread.");
987         }
988
989         /* Wait for all the values to be written to disk before returning. */
990         if (queue_thread_running != 0)
991         {
992                 pthread_join (queue_thread, NULL);
993                 memset (&queue_thread, 0, sizeof (queue_thread));
994                 queue_thread_running = 0;
995                 DEBUG ("rrdtool plugin: queue_thread exited.");
996         }
997
998         /* TODO: Maybe it'd be a good idea to free the cache here.. */
999
1000         return (0);
1001 } /* int rrd_shutdown */
1002
1003 static int rrd_init (void)
1004 {
1005         int status;
1006
1007         if (rrdcreate_config.stepsize < 0)
1008                 rrdcreate_config.stepsize = 0;
1009         if (rrdcreate_config.heartbeat <= 0)
1010                 rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
1011
1012         if ((rrdcreate_config.heartbeat > 0)
1013                         && (rrdcreate_config.heartbeat < interval_g))
1014                 WARNING ("rrdtool plugin: Your `heartbeat' is "
1015                                 "smaller than your `interval'. This will "
1016                                 "likely cause problems.");
1017         else if ((rrdcreate_config.stepsize > 0)
1018                         && (rrdcreate_config.stepsize < interval_g))
1019                 WARNING ("rrdtool plugin: Your `stepsize' is "
1020                                 "smaller than your `interval'. This will "
1021                                 "create needlessly big RRD-files.");
1022
1023         /* Set the cache up */
1024         pthread_mutex_lock (&cache_lock);
1025
1026         cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1027         if (cache == NULL)
1028         {
1029                 ERROR ("rrdtool plugin: c_avl_create failed.");
1030                 return (-1);
1031         }
1032
1033         cache_flush_last = time (NULL);
1034         if (cache_timeout < 2)
1035         {
1036                 cache_timeout = 0;
1037                 cache_flush_timeout = 0;
1038         }
1039         else if (cache_flush_timeout < cache_timeout)
1040                 cache_flush_timeout = 10 * cache_timeout;
1041
1042         pthread_mutex_unlock (&cache_lock);
1043
1044         status = pthread_create (&queue_thread, /* attr = */ NULL,
1045                         rrd_queue_thread, /* args = */ NULL);
1046         if (status != 0)
1047         {
1048                 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1049                 return (-1);
1050         }
1051         queue_thread_running = 1;
1052
1053         DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %i;"
1054                         " heartbeat = %i; rrarows = %i; xff = %lf;",
1055                         (datadir == NULL) ? "(null)" : datadir,
1056                         rrdcreate_config.stepsize,
1057                         rrdcreate_config.heartbeat,
1058                         rrdcreate_config.rrarows,
1059                         rrdcreate_config.xff);
1060
1061         return (0);
1062 } /* int rrd_init */
1063
1064 void module_register (void)
1065 {
1066         plugin_register_config ("rrdtool", rrd_config,
1067                         config_keys, config_keys_num);
1068         plugin_register_init ("rrdtool", rrd_init);
1069         plugin_register_write ("rrdtool", rrd_write, /* user_data = */ NULL);
1070         plugin_register_flush ("rrdtool", rrd_flush, /* user_data = */ NULL);
1071         plugin_register_shutdown ("rrdtool", rrd_shutdown);
1072 }