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