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