Merge branch '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                                 && (ds->ds[i].type != DS_TYPE_DERIVE)
209                                 && (ds->ds[i].type != DS_TYPE_ABSOLUTE))
210                         return (-1);
211
212                 if (ds->ds[i].type == DS_TYPE_COUNTER)
213                         status = ssnprintf (buffer + offset, buffer_len - offset,
214                                         ":%llu", vl->values[i].counter);
215                 else if (ds->ds[i].type == DS_TYPE_GAUGE)
216                         status = ssnprintf (buffer + offset, buffer_len - offset,
217                                         ":%lf", vl->values[i].gauge);
218                 else if (ds->ds[i].type == DS_TYPE_DERIVE)
219                         status = ssnprintf (buffer + offset, buffer_len - offset,
220                                         ":%"PRIi64, vl->values[i].derive);
221                 else /*if (ds->ds[i].type == DS_TYPE_ABSOLUTE) */
222                         status = ssnprintf (buffer + offset, buffer_len - offset,
223                                         ":%"PRIu64, vl->values[i].absolute);
224
225                 if ((status < 1) || (status >= (buffer_len - offset)))
226                         return (-1);
227
228                 offset += status;
229         } /* for ds->ds_num */
230
231         return (0);
232 } /* int value_list_to_string */
233
234 static int value_list_to_filename (char *buffer, int buffer_len,
235                 const data_set_t __attribute__((unused)) *ds, const value_list_t *vl)
236 {
237         int offset = 0;
238         int status;
239
240         if (datadir != NULL)
241         {
242                 status = ssnprintf (buffer + offset, buffer_len - offset,
243                                 "%s/", datadir);
244                 if ((status < 1) || (status >= buffer_len - offset))
245                         return (-1);
246                 offset += status;
247         }
248
249         status = ssnprintf (buffer + offset, buffer_len - offset,
250                         "%s/", vl->host);
251         if ((status < 1) || (status >= buffer_len - offset))
252                 return (-1);
253         offset += status;
254
255         if (strlen (vl->plugin_instance) > 0)
256                 status = ssnprintf (buffer + offset, buffer_len - offset,
257                                 "%s-%s/", vl->plugin, vl->plugin_instance);
258         else
259                 status = ssnprintf (buffer + offset, buffer_len - offset,
260                                 "%s/", vl->plugin);
261         if ((status < 1) || (status >= buffer_len - offset))
262                 return (-1);
263         offset += status;
264
265         if (strlen (vl->type_instance) > 0)
266                 status = ssnprintf (buffer + offset, buffer_len - offset,
267                                 "%s-%s.rrd", vl->type, vl->type_instance);
268         else
269                 status = ssnprintf (buffer + offset, buffer_len - offset,
270                                 "%s.rrd", vl->type);
271         if ((status < 1) || (status >= buffer_len - offset))
272                 return (-1);
273         offset += status;
274
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 (true)
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 (true) */
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_mutex_lock (&cache_lock);
429         c_avl_destroy (cache);
430         cache = NULL;
431         pthread_mutex_unlock (&cache_lock);
432
433         pthread_exit ((void *) 0);
434         return ((void *) 0);
435 } /* void *rrd_queue_thread */
436
437 static int rrd_queue_enqueue (const char *filename,
438     rrd_queue_t **head, rrd_queue_t **tail)
439 {
440   rrd_queue_t *queue_entry;
441
442   queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
443   if (queue_entry == NULL)
444     return (-1);
445
446   queue_entry->filename = strdup (filename);
447   if (queue_entry->filename == NULL)
448   {
449     free (queue_entry);
450     return (-1);
451   }
452
453   queue_entry->next = NULL;
454
455   pthread_mutex_lock (&queue_lock);
456
457   if (*tail == NULL)
458     *head = queue_entry;
459   else
460     (*tail)->next = queue_entry;
461   *tail = queue_entry;
462
463   pthread_cond_signal (&queue_cond);
464   pthread_mutex_unlock (&queue_lock);
465
466   return (0);
467 } /* int rrd_queue_enqueue */
468
469 static int rrd_queue_dequeue (const char *filename,
470     rrd_queue_t **head, rrd_queue_t **tail)
471 {
472   rrd_queue_t *this;
473   rrd_queue_t *prev;
474
475   pthread_mutex_lock (&queue_lock);
476
477   prev = NULL;
478   this = *head;
479
480   while (this != NULL)
481   {
482     if (strcmp (this->filename, filename) == 0)
483       break;
484     
485     prev = this;
486     this = this->next;
487   }
488
489   if (this == NULL)
490   {
491     pthread_mutex_unlock (&queue_lock);
492     return (-1);
493   }
494
495   if (prev == NULL)
496     *head = this->next;
497   else
498     prev->next = this->next;
499
500   if (this->next == NULL)
501     *tail = prev;
502
503   pthread_mutex_unlock (&queue_lock);
504
505   sfree (this->filename);
506   sfree (this);
507
508   return (0);
509 } /* int rrd_queue_dequeue */
510
511 static void rrd_cache_flush (int timeout)
512 {
513         rrd_cache_t *rc;
514         time_t       now;
515
516         char **keys = NULL;
517         int    keys_num = 0;
518
519         char *key;
520         c_avl_iterator_t *iter;
521         int i;
522
523         DEBUG ("rrdtool plugin: Flushing cache, timeout = %i", timeout);
524
525         now = time (NULL);
526
527         /* Build a list of entries to be flushed */
528         iter = c_avl_get_iterator (cache);
529         while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
530         {
531                 if (rc->flags != FLAG_NONE)
532                         continue;
533                 else if ((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 (int timeout, const char *identifier)
587 {
588   rrd_cache_t *rc;
589   time_t now;
590   int status;
591   char key[2048];
592
593   if (identifier == NULL)
594   {
595     rrd_cache_flush (timeout);
596     return (0);
597   }
598
599   now = time (NULL);
600
601   if (datadir == NULL)
602     snprintf (key, sizeof (key), "%s.rrd",
603         identifier);
604   else
605     snprintf (key, sizeof (key), "%s/%s.rrd",
606         datadir, identifier);
607   key[sizeof (key) - 1] = 0;
608
609   status = c_avl_get (cache, key, (void *) &rc);
610   if (status != 0)
611   {
612     INFO ("rrdtool plugin: rrd_cache_flush_identifier: "
613         "c_avl_get (%s) failed. Does that file really exist?",
614         key);
615     return (status);
616   }
617
618   if (rc->flags == FLAG_FLUSHQ)
619   {
620     status = 0;
621   }
622   else if (rc->flags == FLAG_QUEUED)
623   {
624     rrd_queue_dequeue (key, &queue_head, &queue_tail);
625     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
626     if (status == 0)
627       rc->flags = FLAG_FLUSHQ;
628   }
629   else if ((now - rc->first_value) < timeout)
630   {
631     status = 0;
632   }
633   else if (rc->values_num > 0)
634   {
635     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
636     if (status == 0)
637       rc->flags = FLAG_FLUSHQ;
638   }
639
640   return (status);
641 } /* int rrd_cache_flush_identifier */
642
643 static int rrd_cache_insert (const char *filename,
644                 const char *value, time_t value_time)
645 {
646         rrd_cache_t *rc = NULL;
647         int new_rc = 0;
648         char **values_new;
649
650         pthread_mutex_lock (&cache_lock);
651
652         /* This shouldn't happen, but it did happen at least once, so we'll be
653          * careful. */
654         if (cache == NULL)
655         {
656                 pthread_mutex_unlock (&cache_lock);
657                 WARNING ("rrdtool plugin: cache == NULL.");
658                 return (-1);
659         }
660
661         c_avl_get (cache, filename, (void *) &rc);
662
663         if (rc == NULL)
664         {
665                 rc = (rrd_cache_t *) malloc (sizeof (rrd_cache_t));
666                 if (rc == NULL)
667                         return (-1);
668                 rc->values_num = 0;
669                 rc->values = NULL;
670                 rc->first_value = 0;
671                 rc->last_value = 0;
672                 rc->flags = FLAG_NONE;
673                 new_rc = 1;
674         }
675
676         if (rc->last_value >= value_time)
677         {
678                 pthread_mutex_unlock (&cache_lock);
679                 WARNING ("rrdtool plugin: (rc->last_value = %u) >= (value_time = %u)",
680                                 (unsigned int) rc->last_value,
681                                 (unsigned int) value_time);
682                 return (-1);
683         }
684
685         values_new = (char **) realloc ((void *) rc->values,
686                         (rc->values_num + 1) * sizeof (char *));
687         if (values_new == NULL)
688         {
689                 char errbuf[1024];
690                 void *cache_key = NULL;
691
692                 sstrerror (errno, errbuf, sizeof (errbuf));
693
694                 c_avl_remove (cache, filename, &cache_key, NULL);
695                 pthread_mutex_unlock (&cache_lock);
696
697                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
698
699                 sfree (cache_key);
700                 sfree (rc->values);
701                 sfree (rc);
702                 return (-1);
703         }
704         rc->values = values_new;
705
706         rc->values[rc->values_num] = strdup (value);
707         if (rc->values[rc->values_num] != NULL)
708                 rc->values_num++;
709
710         if (rc->values_num == 1)
711                 rc->first_value = value_time;
712         rc->last_value = value_time;
713
714         /* Insert if this is the first value */
715         if (new_rc == 1)
716         {
717                 void *cache_key = strdup (filename);
718
719                 if (cache_key == NULL)
720                 {
721                         char errbuf[1024];
722                         sstrerror (errno, errbuf, sizeof (errbuf));
723
724                         pthread_mutex_unlock (&cache_lock);
725
726                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
727
728                         sfree (rc->values[0]);
729                         sfree (rc->values);
730                         sfree (rc);
731                         return (-1);
732                 }
733
734                 c_avl_insert (cache, cache_key, rc);
735         }
736
737         DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
738                         "values_num = %i; age = %lu;",
739                         filename, rc->values_num,
740                         (unsigned long)(rc->last_value - rc->first_value));
741
742         if ((rc->last_value - rc->first_value) >= cache_timeout)
743         {
744                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
745                  * the same time, ALWAYS lock `cache_lock' first! */
746                 if (rc->flags == FLAG_NONE)
747                 {
748                         int status;
749
750                         status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
751                         if (status == 0)
752                                 rc->flags = FLAG_QUEUED;
753                 }
754                 else
755                 {
756                         DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
757                 }
758         }
759
760         if ((cache_timeout > 0) &&
761                         ((time (NULL) - cache_flush_last) > cache_flush_timeout))
762                 rrd_cache_flush (cache_flush_timeout);
763
764         pthread_mutex_unlock (&cache_lock);
765
766         return (0);
767 } /* int rrd_cache_insert */
768
769 static int rrd_compare_numeric (const void *a_ptr, const void *b_ptr)
770 {
771         int a = *((int *) a_ptr);
772         int b = *((int *) b_ptr);
773
774         if (a < b)
775                 return (-1);
776         else if (a > b)
777                 return (1);
778         else
779                 return (0);
780 } /* int rrd_compare_numeric */
781
782 static int rrd_write (const data_set_t *ds, const value_list_t *vl,
783                 user_data_t __attribute__((unused)) *user_data)
784 {
785         struct stat  statbuf;
786         char         filename[512];
787         char         values[512];
788         int          status;
789
790         if (0 != strcmp (ds->type, vl->type)) {
791                 ERROR ("rrdtool plugin: DS type does not match value list type");
792                 return -1;
793         }
794
795         if (value_list_to_filename (filename, sizeof (filename), ds, vl) != 0)
796                 return (-1);
797
798         if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
799                 return (-1);
800
801         if (stat (filename, &statbuf) == -1)
802         {
803                 if (errno == ENOENT)
804                 {
805                         status = cu_rrd_create_file (filename,
806                                         ds, vl, &rrdcreate_config);
807                         if (status != 0)
808                                 return (-1);
809                 }
810                 else
811                 {
812                         char errbuf[1024];
813                         ERROR ("stat(%s) failed: %s", filename,
814                                         sstrerror (errno, errbuf,
815                                                 sizeof (errbuf)));
816                         return (-1);
817                 }
818         }
819         else if (!S_ISREG (statbuf.st_mode))
820         {
821                 ERROR ("stat(%s): Not a regular file!",
822                                 filename);
823                 return (-1);
824         }
825
826         status = rrd_cache_insert (filename, values, vl->time);
827
828         return (status);
829 } /* int rrd_write */
830
831 static int rrd_flush (int timeout, const char *identifier,
832                 user_data_t __attribute__((unused)) *user_data)
833 {
834         pthread_mutex_lock (&cache_lock);
835
836         if (cache == NULL) {
837                 pthread_mutex_unlock (&cache_lock);
838                 return (0);
839         }
840
841         rrd_cache_flush_identifier (timeout, identifier);
842
843         pthread_mutex_unlock (&cache_lock);
844         return (0);
845 } /* int rrd_flush */
846
847 static int rrd_config (const char *key, const char *value)
848 {
849         if (strcasecmp ("CacheTimeout", key) == 0)
850         {
851                 int tmp = atoi (value);
852                 if (tmp < 0)
853                 {
854                         fprintf (stderr, "rrdtool: `CacheTimeout' must "
855                                         "be greater than 0.\n");
856                         ERROR ("rrdtool: `CacheTimeout' must "
857                                         "be greater than 0.\n");
858                         return (1);
859                 }
860                 cache_timeout = tmp;
861         }
862         else if (strcasecmp ("CacheFlush", key) == 0)
863         {
864                 int tmp = atoi (value);
865                 if (tmp < 0)
866                 {
867                         fprintf (stderr, "rrdtool: `CacheFlush' must "
868                                         "be greater than 0.\n");
869                         ERROR ("rrdtool: `CacheFlush' must "
870                                         "be greater than 0.\n");
871                         return (1);
872                 }
873                 cache_flush_timeout = tmp;
874         }
875         else if (strcasecmp ("DataDir", key) == 0)
876         {
877                 if (datadir != NULL)
878                         free (datadir);
879                 datadir = strdup (value);
880                 if (datadir != NULL)
881                 {
882                         int len = strlen (datadir);
883                         while ((len > 0) && (datadir[len - 1] == '/'))
884                         {
885                                 len--;
886                                 datadir[len] = '\0';
887                         }
888                         if (len <= 0)
889                         {
890                                 free (datadir);
891                                 datadir = NULL;
892                         }
893                 }
894         }
895         else if (strcasecmp ("StepSize", key) == 0)
896         {
897                 int temp = atoi (value);
898                 if (temp > 0)
899                         rrdcreate_config.stepsize = temp;
900         }
901         else if (strcasecmp ("HeartBeat", key) == 0)
902         {
903                 int temp = atoi (value);
904                 if (temp > 0)
905                         rrdcreate_config.heartbeat = temp;
906         }
907         else if (strcasecmp ("RRARows", key) == 0)
908         {
909                 int tmp = atoi (value);
910                 if (tmp <= 0)
911                 {
912                         fprintf (stderr, "rrdtool: `RRARows' must "
913                                         "be greater than 0.\n");
914                         ERROR ("rrdtool: `RRARows' must "
915                                         "be greater than 0.\n");
916                         return (1);
917                 }
918                 rrdcreate_config.rrarows = tmp;
919         }
920         else if (strcasecmp ("RRATimespan", key) == 0)
921         {
922                 char *saveptr = NULL;
923                 char *dummy;
924                 char *ptr;
925                 char *value_copy;
926                 int *tmp_alloc;
927
928                 value_copy = strdup (value);
929                 if (value_copy == NULL)
930                         return (1);
931
932                 dummy = value_copy;
933                 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
934                 {
935                         dummy = NULL;
936                         
937                         tmp_alloc = realloc (rrdcreate_config.timespans,
938                                         sizeof (int) * (rrdcreate_config.timespans_num + 1));
939                         if (tmp_alloc == NULL)
940                         {
941                                 fprintf (stderr, "rrdtool: realloc failed.\n");
942                                 ERROR ("rrdtool: realloc failed.\n");
943                                 free (value_copy);
944                                 return (1);
945                         }
946                         rrdcreate_config.timespans = tmp_alloc;
947                         rrdcreate_config.timespans[rrdcreate_config.timespans_num] = atoi (ptr);
948                         if (rrdcreate_config.timespans[rrdcreate_config.timespans_num] != 0)
949                                 rrdcreate_config.timespans_num++;
950                 } /* while (strtok_r) */
951
952                 qsort (/* base = */ rrdcreate_config.timespans,
953                                 /* nmemb  = */ rrdcreate_config.timespans_num,
954                                 /* size   = */ sizeof (rrdcreate_config.timespans[0]),
955                                 /* compar = */ rrd_compare_numeric);
956
957                 free (value_copy);
958         }
959         else if (strcasecmp ("XFF", key) == 0)
960         {
961                 double tmp = atof (value);
962                 if ((tmp < 0.0) || (tmp >= 1.0))
963                 {
964                         fprintf (stderr, "rrdtool: `XFF' must "
965                                         "be in the range 0 to 1 (exclusive).");
966                         ERROR ("rrdtool: `XFF' must "
967                                         "be in the range 0 to 1 (exclusive).");
968                         return (1);
969                 }
970                 rrdcreate_config.xff = tmp;
971         }
972         else if (strcasecmp ("WritesPerSecond", key) == 0)
973         {
974                 double wps = atof (value);
975
976                 if (wps < 0.0)
977                 {
978                         fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
979                                         "greater than or equal to zero.");
980                         return (1);
981                 }
982                 else if (wps == 0.0)
983                 {
984                         write_rate = 0.0;
985                 }
986                 else
987                 {
988                         write_rate = 1.0 / wps;
989                 }
990         }
991         else
992         {
993                 return (-1);
994         }
995         return (0);
996 } /* int rrd_config */
997
998 static int rrd_shutdown (void)
999 {
1000         pthread_mutex_lock (&cache_lock);
1001         rrd_cache_flush (-1);
1002         pthread_mutex_unlock (&cache_lock);
1003
1004         pthread_mutex_lock (&queue_lock);
1005         do_shutdown = 1;
1006         pthread_cond_signal (&queue_cond);
1007         pthread_mutex_unlock (&queue_lock);
1008
1009         if ((queue_thread_running != 0)
1010                         && ((queue_head != NULL) || (flushq_head != NULL)))
1011         {
1012                 INFO ("rrdtool plugin: Shutting down the queue thread. "
1013                                 "This may take a while.");
1014         }
1015         else if (queue_thread_running != 0)
1016         {
1017                 INFO ("rrdtool plugin: Shutting down the queue thread.");
1018         }
1019
1020         /* Wait for all the values to be written to disk before returning. */
1021         if (queue_thread_running != 0)
1022         {
1023                 pthread_join (queue_thread, NULL);
1024                 memset (&queue_thread, 0, sizeof (queue_thread));
1025                 queue_thread_running = 0;
1026                 DEBUG ("rrdtool plugin: queue_thread exited.");
1027         }
1028
1029         /* TODO: Maybe it'd be a good idea to free the cache here.. */
1030
1031         return (0);
1032 } /* int rrd_shutdown */
1033
1034 static int rrd_init (void)
1035 {
1036         static int init_once = 0;
1037         int status;
1038
1039         if (init_once != 0)
1040                 return (0);
1041         init_once = 1;
1042
1043         if (rrdcreate_config.stepsize < 0)
1044                 rrdcreate_config.stepsize = 0;
1045         if (rrdcreate_config.heartbeat <= 0)
1046                 rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
1047
1048         if ((rrdcreate_config.heartbeat > 0)
1049                         && (rrdcreate_config.heartbeat < interval_g))
1050                 WARNING ("rrdtool plugin: Your `heartbeat' is "
1051                                 "smaller than your `interval'. This will "
1052                                 "likely cause problems.");
1053         else if ((rrdcreate_config.stepsize > 0)
1054                         && (rrdcreate_config.stepsize < interval_g))
1055                 WARNING ("rrdtool plugin: Your `stepsize' is "
1056                                 "smaller than your `interval'. This will "
1057                                 "create needlessly big RRD-files.");
1058
1059         /* Set the cache up */
1060         pthread_mutex_lock (&cache_lock);
1061
1062         cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1063         if (cache == NULL)
1064         {
1065                 ERROR ("rrdtool plugin: c_avl_create failed.");
1066                 return (-1);
1067         }
1068
1069         cache_flush_last = time (NULL);
1070         if (cache_timeout < 2)
1071         {
1072                 cache_timeout = 0;
1073                 cache_flush_timeout = 0;
1074         }
1075         else if (cache_flush_timeout < cache_timeout)
1076                 cache_flush_timeout = 10 * cache_timeout;
1077
1078         pthread_mutex_unlock (&cache_lock);
1079
1080         status = pthread_create (&queue_thread, /* attr = */ NULL,
1081                         rrd_queue_thread, /* args = */ NULL);
1082         if (status != 0)
1083         {
1084                 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1085                 return (-1);
1086         }
1087         queue_thread_running = 1;
1088
1089         DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %i;"
1090                         " heartbeat = %i; rrarows = %i; xff = %lf;",
1091                         (datadir == NULL) ? "(null)" : datadir,
1092                         rrdcreate_config.stepsize,
1093                         rrdcreate_config.heartbeat,
1094                         rrdcreate_config.rrarows,
1095                         rrdcreate_config.xff);
1096
1097         return (0);
1098 } /* int rrd_init */
1099
1100 void module_register (void)
1101 {
1102         plugin_register_config ("rrdtool", rrd_config,
1103                         config_keys, config_keys_num);
1104         plugin_register_init ("rrdtool", rrd_init);
1105         plugin_register_write ("rrdtool", rrd_write, /* user_data = */ NULL);
1106         plugin_register_flush ("rrdtool", rrd_flush, /* user_data = */ NULL);
1107         plugin_register_shutdown ("rrdtool", rrd_shutdown);
1108 }