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