Merge commit 'trenkel/st/python'
[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         time_t first_value;
46         time_t last_value;
47         int 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 int         cache_timeout = 0;
111 static int         cache_flush_timeout = 0;
112 static int         random_timeout = 1;
113 static time_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         int i;
203
204         memset (buffer, '\0', buffer_len);
205
206         status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) vl->time);
207         if ((status < 1) || (status >= buffer_len))
208                 return (-1);
209         offset = status;
210
211         for (i = 0; i < ds->ds_num; i++)
212         {
213                 if ((ds->ds[i].type != DS_TYPE_COUNTER)
214                                 && (ds->ds[i].type != DS_TYPE_GAUGE)
215                                 && (ds->ds[i].type != DS_TYPE_DERIVE)
216                                 && (ds->ds[i].type != DS_TYPE_ABSOLUTE))
217                         return (-1);
218
219                 if (ds->ds[i].type == DS_TYPE_COUNTER)
220                         status = ssnprintf (buffer + offset, buffer_len - offset,
221                                         ":%llu", vl->values[i].counter);
222                 else if (ds->ds[i].type == DS_TYPE_GAUGE)
223                         status = ssnprintf (buffer + offset, buffer_len - offset,
224                                         ":%lf", vl->values[i].gauge);
225                 else if (ds->ds[i].type == DS_TYPE_DERIVE)
226                         status = ssnprintf (buffer + offset, buffer_len - offset,
227                                         ":%"PRIi64, vl->values[i].derive);
228                 else /*if (ds->ds[i].type == DS_TYPE_ABSOLUTE) */
229                         status = ssnprintf (buffer + offset, buffer_len - offset,
230                                         ":%"PRIu64, vl->values[i].absolute);
231
232                 if ((status < 1) || (status >= (buffer_len - offset)))
233                         return (-1);
234
235                 offset += status;
236         } /* for ds->ds_num */
237
238         return (0);
239 } /* int value_list_to_string */
240
241 static int value_list_to_filename (char *buffer, int buffer_len,
242                 const data_set_t __attribute__((unused)) *ds, const value_list_t *vl)
243 {
244         int offset = 0;
245         int status;
246
247         if (datadir != NULL)
248         {
249                 status = ssnprintf (buffer + offset, buffer_len - offset,
250                                 "%s/", datadir);
251                 if ((status < 1) || (status >= buffer_len - offset))
252                         return (-1);
253                 offset += status;
254         }
255
256         status = ssnprintf (buffer + offset, buffer_len - offset,
257                         "%s/", vl->host);
258         if ((status < 1) || (status >= buffer_len - offset))
259                 return (-1);
260         offset += status;
261
262         if (strlen (vl->plugin_instance) > 0)
263                 status = ssnprintf (buffer + offset, buffer_len - offset,
264                                 "%s-%s/", vl->plugin, vl->plugin_instance);
265         else
266                 status = ssnprintf (buffer + offset, buffer_len - offset,
267                                 "%s/", vl->plugin);
268         if ((status < 1) || (status >= buffer_len - offset))
269                 return (-1);
270         offset += status;
271
272         if (strlen (vl->type_instance) > 0)
273                 status = ssnprintf (buffer + offset, buffer_len - offset,
274                                 "%s-%s.rrd", vl->type, vl->type_instance);
275         else
276                 status = ssnprintf (buffer + offset, buffer_len - offset,
277                                 "%s.rrd", vl->type);
278         if ((status < 1) || (status >= buffer_len - offset))
279                 return (-1);
280         offset += status;
281
282         return (0);
283 } /* int value_list_to_filename */
284
285 static void *rrd_queue_thread (void __attribute__((unused)) *data)
286 {
287         struct timeval tv_next_update;
288         struct timeval tv_now;
289
290         gettimeofday (&tv_next_update, /* timezone = */ NULL);
291
292         while (42)
293         {
294                 rrd_queue_t *queue_entry;
295                 rrd_cache_t *cache_entry;
296                 char **values;
297                 int    values_num;
298                 int    status;
299                 int    i;
300
301                 values = NULL;
302                 values_num = 0;
303
304                 pthread_mutex_lock (&queue_lock);
305                 /* Wait for values to arrive */
306                 while (true)
307                 {
308                   struct timespec ts_wait;
309
310                   while ((flushq_head == NULL) && (queue_head == NULL)
311                       && (do_shutdown == 0))
312                     pthread_cond_wait (&queue_cond, &queue_lock);
313
314                   if ((flushq_head == NULL) && (queue_head == NULL))
315                     break;
316
317                   /* Don't delay if there's something to flush */
318                   if (flushq_head != NULL)
319                     break;
320
321                   /* Don't delay if we're shutting down */
322                   if (do_shutdown != 0)
323                     break;
324
325                   /* Don't delay if no delay was configured. */
326                   if (write_rate <= 0.0)
327                     break;
328
329                   gettimeofday (&tv_now, /* timezone = */ NULL);
330                   status = timeval_cmp (tv_next_update, tv_now, NULL);
331                   /* We're good to go */
332                   if (status <= 0)
333                     break;
334
335                   /* We're supposed to wait a bit with this update, so we'll
336                    * wait for the next addition to the queue or to the end of
337                    * the wait period - whichever comes first. */
338                   ts_wait.tv_sec = tv_next_update.tv_sec;
339                   ts_wait.tv_nsec = 1000 * tv_next_update.tv_usec;
340
341                   status = pthread_cond_timedwait (&queue_cond, &queue_lock,
342                       &ts_wait);
343                   if (status == ETIMEDOUT)
344                     break;
345                 } /* while (true) */
346
347                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
348                  * the same time, ALWAYS lock `cache_lock' first! */
349
350                 /* We're in the shutdown phase */
351                 if ((flushq_head == NULL) && (queue_head == NULL))
352                 {
353                   pthread_mutex_unlock (&queue_lock);
354                   break;
355                 }
356
357                 if (flushq_head != NULL)
358                 {
359                   /* Dequeue the first flush entry */
360                   queue_entry = flushq_head;
361                   if (flushq_head == flushq_tail)
362                     flushq_head = flushq_tail = NULL;
363                   else
364                     flushq_head = flushq_head->next;
365                 }
366                 else /* if (queue_head != NULL) */
367                 {
368                   /* Dequeue the first regular entry */
369                   queue_entry = queue_head;
370                   if (queue_head == queue_tail)
371                     queue_head = queue_tail = NULL;
372                   else
373                     queue_head = queue_head->next;
374                 }
375
376                 /* Unlock the queue again */
377                 pthread_mutex_unlock (&queue_lock);
378
379                 /* We now need the cache lock so the entry isn't updated while
380                  * we make a copy of it's values */
381                 pthread_mutex_lock (&cache_lock);
382
383                 status = c_avl_get (cache, queue_entry->filename,
384                                 (void *) &cache_entry);
385
386                 if (status == 0)
387                 {
388                         values = cache_entry->values;
389                         values_num = cache_entry->values_num;
390
391                         cache_entry->values = NULL;
392                         cache_entry->values_num = 0;
393                         cache_entry->flags = FLAG_NONE;
394                 }
395
396                 pthread_mutex_unlock (&cache_lock);
397
398                 if (status != 0)
399                 {
400                         sfree (queue_entry->filename);
401                         sfree (queue_entry);
402                         continue;
403                 }
404
405                 /* Update `tv_next_update' */
406                 if (write_rate > 0.0) 
407                 {
408                   gettimeofday (&tv_now, /* timezone = */ NULL);
409                   tv_next_update.tv_sec = tv_now.tv_sec;
410                   tv_next_update.tv_usec = tv_now.tv_usec
411                     + ((suseconds_t) (1000000 * write_rate));
412                   while (tv_next_update.tv_usec > 1000000)
413                   {
414                     tv_next_update.tv_sec++;
415                     tv_next_update.tv_usec -= 1000000;
416                   }
417                 }
418
419                 /* Write the values to the RRD-file */
420                 srrd_update (queue_entry->filename, NULL,
421                                 values_num, (const char **)values);
422                 DEBUG ("rrdtool plugin: queue thread: Wrote %i value%s to %s",
423                                 values_num, (values_num == 1) ? "" : "s",
424                                 queue_entry->filename);
425
426                 for (i = 0; i < values_num; i++)
427                 {
428                         sfree (values[i]);
429                 }
430                 sfree (values);
431                 sfree (queue_entry->filename);
432                 sfree (queue_entry);
433         } /* while (42) */
434
435         pthread_mutex_lock (&cache_lock);
436         c_avl_destroy (cache);
437         cache = NULL;
438         pthread_mutex_unlock (&cache_lock);
439
440         pthread_exit ((void *) 0);
441         return ((void *) 0);
442 } /* void *rrd_queue_thread */
443
444 static int rrd_queue_enqueue (const char *filename,
445     rrd_queue_t **head, rrd_queue_t **tail)
446 {
447   rrd_queue_t *queue_entry;
448
449   queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
450   if (queue_entry == NULL)
451     return (-1);
452
453   queue_entry->filename = strdup (filename);
454   if (queue_entry->filename == NULL)
455   {
456     free (queue_entry);
457     return (-1);
458   }
459
460   queue_entry->next = NULL;
461
462   pthread_mutex_lock (&queue_lock);
463
464   if (*tail == NULL)
465     *head = queue_entry;
466   else
467     (*tail)->next = queue_entry;
468   *tail = queue_entry;
469
470   pthread_cond_signal (&queue_cond);
471   pthread_mutex_unlock (&queue_lock);
472
473   return (0);
474 } /* int rrd_queue_enqueue */
475
476 static int rrd_queue_dequeue (const char *filename,
477     rrd_queue_t **head, rrd_queue_t **tail)
478 {
479   rrd_queue_t *this;
480   rrd_queue_t *prev;
481
482   pthread_mutex_lock (&queue_lock);
483
484   prev = NULL;
485   this = *head;
486
487   while (this != NULL)
488   {
489     if (strcmp (this->filename, filename) == 0)
490       break;
491     
492     prev = this;
493     this = this->next;
494   }
495
496   if (this == NULL)
497   {
498     pthread_mutex_unlock (&queue_lock);
499     return (-1);
500   }
501
502   if (prev == NULL)
503     *head = this->next;
504   else
505     prev->next = this->next;
506
507   if (this->next == NULL)
508     *tail = prev;
509
510   pthread_mutex_unlock (&queue_lock);
511
512   sfree (this->filename);
513   sfree (this);
514
515   return (0);
516 } /* int rrd_queue_dequeue */
517
518 static void rrd_cache_flush (int timeout)
519 {
520         rrd_cache_t *rc;
521         time_t       now;
522
523         char **keys = NULL;
524         int    keys_num = 0;
525
526         char *key;
527         c_avl_iterator_t *iter;
528         int i;
529
530         DEBUG ("rrdtool plugin: Flushing cache, timeout = %i", timeout);
531
532         now = time (NULL);
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                 else if ((now - rc->first_value) < timeout)
541                         continue;
542                 else if (rc->values_num > 0)
543                 {
544                         int status;
545
546                         status = rrd_queue_enqueue (key, &queue_head,  &queue_tail);
547                         if (status == 0)
548                                 rc->flags = FLAG_QUEUED;
549                 }
550                 else /* ancient and no values -> waste of memory */
551                 {
552                         char **tmp = (char **) realloc ((void *) keys,
553                                         (keys_num + 1) * sizeof (char *));
554                         if (tmp == NULL)
555                         {
556                                 char errbuf[1024];
557                                 ERROR ("rrdtool plugin: "
558                                                 "realloc failed: %s",
559                                                 sstrerror (errno, errbuf,
560                                                         sizeof (errbuf)));
561                                 c_avl_iterator_destroy (iter);
562                                 sfree (keys);
563                                 return;
564                         }
565                         keys = tmp;
566                         keys[keys_num] = key;
567                         keys_num++;
568                 }
569         } /* while (c_avl_iterator_next) */
570         c_avl_iterator_destroy (iter);
571         
572         for (i = 0; i < keys_num; i++)
573         {
574                 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
575                 {
576                         DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
577                         continue;
578                 }
579
580                 assert (rc->values == NULL);
581                 assert (rc->values_num == 0);
582
583                 sfree (rc);
584                 sfree (key);
585                 keys[i] = NULL;
586         } /* for (i = 0..keys_num) */
587
588         sfree (keys);
589
590         cache_flush_last = now;
591 } /* void rrd_cache_flush */
592
593 static int rrd_cache_flush_identifier (int timeout, const char *identifier)
594 {
595   rrd_cache_t *rc;
596   time_t now;
597   int status;
598   char key[2048];
599
600   if (identifier == NULL)
601   {
602     rrd_cache_flush (timeout);
603     return (0);
604   }
605
606   now = time (NULL);
607
608   if (datadir == NULL)
609     snprintf (key, sizeof (key), "%s.rrd",
610         identifier);
611   else
612     snprintf (key, sizeof (key), "%s/%s.rrd",
613         datadir, identifier);
614   key[sizeof (key) - 1] = 0;
615
616   status = c_avl_get (cache, key, (void *) &rc);
617   if (status != 0)
618   {
619     INFO ("rrdtool plugin: rrd_cache_flush_identifier: "
620         "c_avl_get (%s) failed. Does that file really exist?",
621         key);
622     return (status);
623   }
624
625   if (rc->flags == FLAG_FLUSHQ)
626   {
627     status = 0;
628   }
629   else if (rc->flags == FLAG_QUEUED)
630   {
631     rrd_queue_dequeue (key, &queue_head, &queue_tail);
632     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
633     if (status == 0)
634       rc->flags = FLAG_FLUSHQ;
635   }
636   else if ((now - rc->first_value) < timeout)
637   {
638     status = 0;
639   }
640   else if (rc->values_num > 0)
641   {
642     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
643     if (status == 0)
644       rc->flags = FLAG_FLUSHQ;
645   }
646
647   return (status);
648 } /* int rrd_cache_flush_identifier */
649
650 static int rrd_cache_insert (const char *filename,
651                 const char *value, time_t value_time)
652 {
653         rrd_cache_t *rc = NULL;
654         int new_rc = 0;
655         char **values_new;
656
657         pthread_mutex_lock (&cache_lock);
658
659         /* This shouldn't happen, but it did happen at least once, so we'll be
660          * careful. */
661         if (cache == NULL)
662         {
663                 pthread_mutex_unlock (&cache_lock);
664                 WARNING ("rrdtool plugin: cache == NULL.");
665                 return (-1);
666         }
667
668         c_avl_get (cache, filename, (void *) &rc);
669
670         if (rc == NULL)
671         {
672                 rc = (rrd_cache_t *) malloc (sizeof (rrd_cache_t));
673                 if (rc == NULL)
674                         return (-1);
675                 rc->values_num = 0;
676                 rc->values = NULL;
677                 rc->first_value = 0;
678                 rc->last_value = 0;
679                 rc->random_variation = 0;
680                 rc->flags = FLAG_NONE;
681                 new_rc = 1;
682         }
683
684         if (rc->last_value >= value_time)
685         {
686                 pthread_mutex_unlock (&cache_lock);
687                 WARNING ("rrdtool plugin: (rc->last_value = %u) >= (value_time = %u)",
688                                 (unsigned int) rc->last_value,
689                                 (unsigned int) value_time);
690                 return (-1);
691         }
692
693         values_new = (char **) realloc ((void *) rc->values,
694                         (rc->values_num + 1) * sizeof (char *));
695         if (values_new == NULL)
696         {
697                 char errbuf[1024];
698                 void *cache_key = NULL;
699
700                 sstrerror (errno, errbuf, sizeof (errbuf));
701
702                 c_avl_remove (cache, filename, &cache_key, NULL);
703                 pthread_mutex_unlock (&cache_lock);
704
705                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
706
707                 sfree (cache_key);
708                 sfree (rc->values);
709                 sfree (rc);
710                 return (-1);
711         }
712         rc->values = values_new;
713
714         rc->values[rc->values_num] = strdup (value);
715         if (rc->values[rc->values_num] != NULL)
716                 rc->values_num++;
717
718         if (rc->values_num == 1)
719                 rc->first_value = value_time;
720         rc->last_value = value_time;
721
722         /* Insert if this is the first value */
723         if (new_rc == 1)
724         {
725                 void *cache_key = strdup (filename);
726
727                 if (cache_key == NULL)
728                 {
729                         char errbuf[1024];
730                         sstrerror (errno, errbuf, sizeof (errbuf));
731
732                         pthread_mutex_unlock (&cache_lock);
733
734                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
735
736                         sfree (rc->values[0]);
737                         sfree (rc->values);
738                         sfree (rc);
739                         return (-1);
740                 }
741
742                 c_avl_insert (cache, cache_key, rc);
743         }
744
745         DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
746                         "values_num = %i; age = %lu;",
747                         filename, rc->values_num,
748                         (unsigned long)(rc->last_value - rc->first_value));
749
750         if ((rc->last_value + rc->random_variation - rc->first_value) >= cache_timeout)
751         {
752                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
753                  * the same time, ALWAYS lock `cache_lock' first! */
754                 if (rc->flags == FLAG_NONE)
755                 {
756                         int status;
757
758                         status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
759                         if (status == 0)
760                                 rc->flags = FLAG_QUEUED;
761
762                         /* Update the jitter value. Negative values are
763                          * slightly preferred. */
764                         if (random_timeout > 0)
765                         {
766                                 rc->random_variation = (rand () % (2 * random_timeout))
767                                         - random_timeout;
768                         }
769                         else
770                         {
771                                 rc->random_variation = 0;
772                         }
773                 }
774                 else
775                 {
776                         DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
777                 }
778         }
779
780         if ((cache_timeout > 0) &&
781                         ((time (NULL) - cache_flush_last) > cache_flush_timeout))
782                 rrd_cache_flush (cache_flush_timeout);
783
784         pthread_mutex_unlock (&cache_lock);
785
786         return (0);
787 } /* int rrd_cache_insert */
788
789 static int rrd_compare_numeric (const void *a_ptr, const void *b_ptr)
790 {
791         int a = *((int *) a_ptr);
792         int b = *((int *) b_ptr);
793
794         if (a < b)
795                 return (-1);
796         else if (a > b)
797                 return (1);
798         else
799                 return (0);
800 } /* int rrd_compare_numeric */
801
802 static int rrd_write (const data_set_t *ds, const value_list_t *vl,
803                 user_data_t __attribute__((unused)) *user_data)
804 {
805         struct stat  statbuf;
806         char         filename[512];
807         char         values[512];
808         int          status;
809
810         if (0 != strcmp (ds->type, vl->type)) {
811                 ERROR ("rrdtool plugin: DS type does not match value list type");
812                 return -1;
813         }
814
815         if (value_list_to_filename (filename, sizeof (filename), ds, vl) != 0)
816                 return (-1);
817
818         if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
819                 return (-1);
820
821         if (stat (filename, &statbuf) == -1)
822         {
823                 if (errno == ENOENT)
824                 {
825                         status = cu_rrd_create_file (filename,
826                                         ds, vl, &rrdcreate_config);
827                         if (status != 0)
828                                 return (-1);
829                 }
830                 else
831                 {
832                         char errbuf[1024];
833                         ERROR ("stat(%s) failed: %s", filename,
834                                         sstrerror (errno, errbuf,
835                                                 sizeof (errbuf)));
836                         return (-1);
837                 }
838         }
839         else if (!S_ISREG (statbuf.st_mode))
840         {
841                 ERROR ("stat(%s): Not a regular file!",
842                                 filename);
843                 return (-1);
844         }
845
846         status = rrd_cache_insert (filename, values, vl->time);
847
848         return (status);
849 } /* int rrd_write */
850
851 static int rrd_flush (int timeout, const char *identifier,
852                 user_data_t __attribute__((unused)) *user_data)
853 {
854         pthread_mutex_lock (&cache_lock);
855
856         if (cache == NULL) {
857                 pthread_mutex_unlock (&cache_lock);
858                 return (0);
859         }
860
861         rrd_cache_flush_identifier (timeout, identifier);
862
863         pthread_mutex_unlock (&cache_lock);
864         return (0);
865 } /* int rrd_flush */
866
867 static int rrd_config (const char *key, const char *value)
868 {
869         if (strcasecmp ("CacheTimeout", key) == 0)
870         {
871                 int tmp = atoi (value);
872                 if (tmp < 0)
873                 {
874                         fprintf (stderr, "rrdtool: `CacheTimeout' must "
875                                         "be greater than 0.\n");
876                         ERROR ("rrdtool: `CacheTimeout' must "
877                                         "be greater than 0.\n");
878                         return (1);
879                 }
880                 cache_timeout = tmp;
881         }
882         else if (strcasecmp ("CacheFlush", key) == 0)
883         {
884                 int tmp = atoi (value);
885                 if (tmp < 0)
886                 {
887                         fprintf (stderr, "rrdtool: `CacheFlush' must "
888                                         "be greater than 0.\n");
889                         ERROR ("rrdtool: `CacheFlush' must "
890                                         "be greater than 0.\n");
891                         return (1);
892                 }
893                 cache_flush_timeout = tmp;
894         }
895         else if (strcasecmp ("DataDir", key) == 0)
896         {
897                 if (datadir != NULL)
898                         free (datadir);
899                 datadir = strdup (value);
900                 if (datadir != NULL)
901                 {
902                         int len = strlen (datadir);
903                         while ((len > 0) && (datadir[len - 1] == '/'))
904                         {
905                                 len--;
906                                 datadir[len] = '\0';
907                         }
908                         if (len <= 0)
909                         {
910                                 free (datadir);
911                                 datadir = NULL;
912                         }
913                 }
914         }
915         else if (strcasecmp ("StepSize", key) == 0)
916         {
917                 int temp = atoi (value);
918                 if (temp > 0)
919                         rrdcreate_config.stepsize = temp;
920         }
921         else if (strcasecmp ("HeartBeat", key) == 0)
922         {
923                 int temp = atoi (value);
924                 if (temp > 0)
925                         rrdcreate_config.heartbeat = temp;
926         }
927         else if (strcasecmp ("RRARows", key) == 0)
928         {
929                 int tmp = atoi (value);
930                 if (tmp <= 0)
931                 {
932                         fprintf (stderr, "rrdtool: `RRARows' must "
933                                         "be greater than 0.\n");
934                         ERROR ("rrdtool: `RRARows' must "
935                                         "be greater than 0.\n");
936                         return (1);
937                 }
938                 rrdcreate_config.rrarows = tmp;
939         }
940         else if (strcasecmp ("RRATimespan", key) == 0)
941         {
942                 char *saveptr = NULL;
943                 char *dummy;
944                 char *ptr;
945                 char *value_copy;
946                 int *tmp_alloc;
947
948                 value_copy = strdup (value);
949                 if (value_copy == NULL)
950                         return (1);
951
952                 dummy = value_copy;
953                 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
954                 {
955                         dummy = NULL;
956                         
957                         tmp_alloc = realloc (rrdcreate_config.timespans,
958                                         sizeof (int) * (rrdcreate_config.timespans_num + 1));
959                         if (tmp_alloc == NULL)
960                         {
961                                 fprintf (stderr, "rrdtool: realloc failed.\n");
962                                 ERROR ("rrdtool: realloc failed.\n");
963                                 free (value_copy);
964                                 return (1);
965                         }
966                         rrdcreate_config.timespans = tmp_alloc;
967                         rrdcreate_config.timespans[rrdcreate_config.timespans_num] = atoi (ptr);
968                         if (rrdcreate_config.timespans[rrdcreate_config.timespans_num] != 0)
969                                 rrdcreate_config.timespans_num++;
970                 } /* while (strtok_r) */
971
972                 qsort (/* base = */ rrdcreate_config.timespans,
973                                 /* nmemb  = */ rrdcreate_config.timespans_num,
974                                 /* size   = */ sizeof (rrdcreate_config.timespans[0]),
975                                 /* compar = */ rrd_compare_numeric);
976
977                 free (value_copy);
978         }
979         else if (strcasecmp ("XFF", key) == 0)
980         {
981                 double tmp = atof (value);
982                 if ((tmp < 0.0) || (tmp >= 1.0))
983                 {
984                         fprintf (stderr, "rrdtool: `XFF' must "
985                                         "be in the range 0 to 1 (exclusive).");
986                         ERROR ("rrdtool: `XFF' must "
987                                         "be in the range 0 to 1 (exclusive).");
988                         return (1);
989                 }
990                 rrdcreate_config.xff = tmp;
991         }
992         else if (strcasecmp ("WritesPerSecond", key) == 0)
993         {
994                 double wps = atof (value);
995
996                 if (wps < 0.0)
997                 {
998                         fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
999                                         "greater than or equal to zero.");
1000                         return (1);
1001                 }
1002                 else if (wps == 0.0)
1003                 {
1004                         write_rate = 0.0;
1005                 }
1006                 else
1007                 {
1008                         write_rate = 1.0 / wps;
1009                 }
1010         }
1011         else if (strcasecmp ("RandomTimeout", key) == 0)
1012         {
1013                 int tmp;
1014
1015                 tmp = atoi (value);
1016                 if (tmp < 0)
1017                 {
1018                         fprintf (stderr, "rrdtool: `RandomTimeout' must "
1019                                         "be greater than or equal to zero.\n");
1020                         ERROR ("rrdtool: `RandomTimeout' must "
1021                                         "be greater then or equal to zero.");
1022                 }
1023                 else
1024                 {
1025                         random_timeout = tmp;
1026                 }
1027         }
1028         else
1029         {
1030                 return (-1);
1031         }
1032         return (0);
1033 } /* int rrd_config */
1034
1035 static int rrd_shutdown (void)
1036 {
1037         pthread_mutex_lock (&cache_lock);
1038         rrd_cache_flush (-1);
1039         pthread_mutex_unlock (&cache_lock);
1040
1041         pthread_mutex_lock (&queue_lock);
1042         do_shutdown = 1;
1043         pthread_cond_signal (&queue_cond);
1044         pthread_mutex_unlock (&queue_lock);
1045
1046         if ((queue_thread_running != 0)
1047                         && ((queue_head != NULL) || (flushq_head != NULL)))
1048         {
1049                 INFO ("rrdtool plugin: Shutting down the queue thread. "
1050                                 "This may take a while.");
1051         }
1052         else if (queue_thread_running != 0)
1053         {
1054                 INFO ("rrdtool plugin: Shutting down the queue thread.");
1055         }
1056
1057         /* Wait for all the values to be written to disk before returning. */
1058         if (queue_thread_running != 0)
1059         {
1060                 pthread_join (queue_thread, NULL);
1061                 memset (&queue_thread, 0, sizeof (queue_thread));
1062                 queue_thread_running = 0;
1063                 DEBUG ("rrdtool plugin: queue_thread exited.");
1064         }
1065
1066         /* TODO: Maybe it'd be a good idea to free the cache here.. */
1067
1068         return (0);
1069 } /* int rrd_shutdown */
1070
1071 static int rrd_init (void)
1072 {
1073         static int init_once = 0;
1074         int status;
1075
1076         if (init_once != 0)
1077                 return (0);
1078         init_once = 1;
1079
1080         if (rrdcreate_config.stepsize < 0)
1081                 rrdcreate_config.stepsize = 0;
1082         if (rrdcreate_config.heartbeat <= 0)
1083                 rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
1084
1085         if ((rrdcreate_config.heartbeat > 0)
1086                         && (rrdcreate_config.heartbeat < interval_g))
1087                 WARNING ("rrdtool plugin: Your `heartbeat' is "
1088                                 "smaller than your `interval'. This will "
1089                                 "likely cause problems.");
1090         else if ((rrdcreate_config.stepsize > 0)
1091                         && (rrdcreate_config.stepsize < interval_g))
1092                 WARNING ("rrdtool plugin: Your `stepsize' is "
1093                                 "smaller than your `interval'. This will "
1094                                 "create needlessly big RRD-files.");
1095
1096         /* Set the cache up */
1097         pthread_mutex_lock (&cache_lock);
1098
1099         cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1100         if (cache == NULL)
1101         {
1102                 ERROR ("rrdtool plugin: c_avl_create failed.");
1103                 return (-1);
1104         }
1105
1106         cache_flush_last = time (NULL);
1107         if (cache_timeout < 2)
1108         {
1109                 cache_timeout = 0;
1110                 cache_flush_timeout = 0;
1111         }
1112         else if (cache_flush_timeout < cache_timeout)
1113                 cache_flush_timeout = 10 * cache_timeout;
1114
1115         pthread_mutex_unlock (&cache_lock);
1116
1117         status = pthread_create (&queue_thread, /* attr = */ NULL,
1118                         rrd_queue_thread, /* args = */ NULL);
1119         if (status != 0)
1120         {
1121                 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1122                 return (-1);
1123         }
1124         queue_thread_running = 1;
1125
1126         DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %i;"
1127                         " heartbeat = %i; rrarows = %i; xff = %lf;",
1128                         (datadir == NULL) ? "(null)" : datadir,
1129                         rrdcreate_config.stepsize,
1130                         rrdcreate_config.heartbeat,
1131                         rrdcreate_config.rrarows,
1132                         rrdcreate_config.xff);
1133
1134         return (0);
1135 } /* int rrd_init */
1136
1137 void module_register (void)
1138 {
1139         plugin_register_config ("rrdtool", rrd_config,
1140                         config_keys, config_keys_num);
1141         plugin_register_init ("rrdtool", rrd_init);
1142         plugin_register_write ("rrdtool", rrd_write, /* user_data = */ NULL);
1143         plugin_register_flush ("rrdtool", rrd_flush, /* user_data = */ NULL);
1144         plugin_register_shutdown ("rrdtool", rrd_shutdown);
1145 }