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