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