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