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