e1c7902b1f5e346250f8ea82ae52512421fca173
[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
27 #include <rrd.h>
28
29 #if HAVE_PTHREAD_H
30 # include <pthread.h>
31 #endif
32
33 /*
34  * Private types
35  */
36 struct rrd_cache_s
37 {
38         int    values_num;
39         char **values;
40         time_t first_value;
41         time_t last_value;
42         enum
43         {
44                 FLAG_NONE   = 0x00,
45                 FLAG_QUEUED = 0x01,
46                 FLAG_FLUSHQ = 0x02
47         } flags;
48 };
49 typedef struct rrd_cache_s rrd_cache_t;
50
51 enum rrd_queue_dir_e
52 {
53   QUEUE_INSERT_FRONT,
54   QUEUE_INSERT_BACK
55 };
56 typedef enum rrd_queue_dir_e rrd_queue_dir_t;
57
58 struct rrd_queue_s
59 {
60         char *filename;
61         struct rrd_queue_s *next;
62 };
63 typedef struct rrd_queue_s rrd_queue_t;
64
65 /*
66  * Private variables
67  */
68 static int rra_timespans[] =
69 {
70         3600,
71         86400,
72         604800,
73         2678400,
74         31622400
75 };
76 static int rra_timespans_num = STATIC_ARRAY_SIZE (rra_timespans);
77
78 static int *rra_timespans_custom = NULL;
79 static int rra_timespans_custom_num = 0;
80
81 static char *rra_types[] =
82 {
83         "AVERAGE",
84         "MIN",
85         "MAX"
86 };
87 static int rra_types_num = STATIC_ARRAY_SIZE (rra_types);
88
89 static const char *config_keys[] =
90 {
91         "CacheTimeout",
92         "CacheFlush",
93         "DataDir",
94         "StepSize",
95         "HeartBeat",
96         "RRARows",
97         "RRATimespan",
98         "XFF",
99         "WritesPerSecond"
100 };
101 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
102
103 /* If datadir is zero, the daemon's basedir is used. If stepsize or heartbeat
104  * is zero a default, depending on the `interval' member of the value list is
105  * being used. */
106 static char   *datadir   = NULL;
107 static int     stepsize  = 0;
108 static int     heartbeat = 0;
109 static int     rrarows   = 1200;
110 static double  xff       = 0.1;
111 static double  write_rate = 0.0;
112
113 /* XXX: If you need to lock both, cache_lock and queue_lock, at the same time,
114  * ALWAYS lock `cache_lock' first! */
115 static int         cache_timeout = 0;
116 static int         cache_flush_timeout = 0;
117 static time_t      cache_flush_last;
118 static c_avl_tree_t *cache = NULL;
119 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
120
121 static rrd_queue_t    *queue_head = NULL;
122 static rrd_queue_t    *queue_tail = NULL;
123 static rrd_queue_t    *flushq_head = NULL;
124 static rrd_queue_t    *flushq_tail = NULL;
125 static pthread_t       queue_thread = 0;
126 static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER;
127 static pthread_cond_t  queue_cond = PTHREAD_COND_INITIALIZER;
128
129 #if !HAVE_THREADSAFE_LIBRRD
130 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
131 #endif
132
133 static int do_shutdown = 0;
134
135 /* * * * * * * * * *
136  * WARNING:  Magic *
137  * * * * * * * * * */
138
139 static void rra_free (int rra_num, char **rra_def)
140 {
141         int i;
142
143         for (i = 0; i < rra_num; i++)
144         {
145                 sfree (rra_def[i]);
146         }
147         sfree (rra_def);
148 } /* void rra_free */
149
150 static int rra_get (char ***ret, const value_list_t *vl)
151 {
152         char **rra_def;
153         int rra_num;
154
155         int *rts;
156         int  rts_num;
157
158         int rra_max;
159
160         int span;
161
162         int cdp_num;
163         int cdp_len;
164         int i, j;
165
166         char buffer[64];
167
168         /* The stepsize we use here: If it is user-set, use it. If not, use the
169          * interval of the value-list. */
170         int ss;
171
172         if (rrarows <= 0)
173         {
174                 *ret = NULL;
175                 return (-1);
176         }
177
178         ss = (stepsize > 0) ? stepsize : vl->interval;
179         if (ss <= 0)
180         {
181                 *ret = NULL;
182                 return (-1);
183         }
184
185         /* Use the configured timespans or fall back to the built-in defaults */
186         if (rra_timespans_custom_num != 0)
187         {
188                 rts = rra_timespans_custom;
189                 rts_num = rra_timespans_custom_num;
190         }
191         else
192         {
193                 rts = rra_timespans;
194                 rts_num = rra_timespans_num;
195         }
196
197         rra_max = rts_num * rra_types_num;
198
199         if ((rra_def = (char **) malloc ((rra_max + 1) * sizeof (char *))) == NULL)
200                 return (-1);
201         memset (rra_def, '\0', (rra_max + 1) * sizeof (char *));
202         rra_num = 0;
203
204         cdp_len = 0;
205         for (i = 0; i < rts_num; i++)
206         {
207                 span = rts[i];
208
209                 if ((span / ss) < rrarows)
210                         span = ss * rrarows;
211
212                 if (cdp_len == 0)
213                         cdp_len = 1;
214                 else
215                         cdp_len = (int) floor (((double) span)
216                                         / ((double) (rrarows * ss)));
217
218                 cdp_num = (int) ceil (((double) span)
219                                 / ((double) (cdp_len * ss)));
220
221                 for (j = 0; j < rra_types_num; j++)
222                 {
223                         if (rra_num >= rra_max)
224                                 break;
225
226                         if (ssnprintf (buffer, sizeof (buffer), "RRA:%s:%3.1f:%u:%u",
227                                                 rra_types[j], xff,
228                                                 cdp_len, cdp_num) >= sizeof (buffer))
229                         {
230                                 ERROR ("rra_get: Buffer would have been truncated.");
231                                 continue;
232                         }
233
234                         rra_def[rra_num++] = sstrdup (buffer);
235                 }
236         }
237
238 #if COLLECT_DEBUG
239         DEBUG ("rra_num = %i", rra_num);
240         for (i = 0; i < rra_num; i++)
241                 DEBUG ("  %s", rra_def[i]);
242 #endif
243
244         *ret = rra_def;
245         return (rra_num);
246 } /* int rra_get */
247
248 static void ds_free (int ds_num, char **ds_def)
249 {
250         int i;
251
252         for (i = 0; i < ds_num; i++)
253                 if (ds_def[i] != NULL)
254                         free (ds_def[i]);
255         free (ds_def);
256 }
257
258 static int ds_get (char ***ret, const data_set_t *ds, const value_list_t *vl)
259 {
260         char **ds_def;
261         int ds_num;
262
263         char min[32];
264         char max[32];
265         char buffer[128];
266
267         DEBUG ("ds->ds_num = %i", ds->ds_num);
268
269         ds_def = (char **) malloc (ds->ds_num * sizeof (char *));
270         if (ds_def == NULL)
271         {
272                 char errbuf[1024];
273                 ERROR ("rrdtool plugin: malloc failed: %s",
274                                 sstrerror (errno, errbuf, sizeof (errbuf)));
275                 return (-1);
276         }
277         memset (ds_def, '\0', ds->ds_num * sizeof (char *));
278
279         for (ds_num = 0; ds_num < ds->ds_num; ds_num++)
280         {
281                 data_source_t *d = ds->ds + ds_num;
282                 char *type;
283                 int status;
284
285                 ds_def[ds_num] = NULL;
286
287                 if (d->type == DS_TYPE_COUNTER)
288                         type = "COUNTER";
289                 else if (d->type == DS_TYPE_GAUGE)
290                         type = "GAUGE";
291                 else
292                 {
293                         ERROR ("rrdtool plugin: Unknown DS type: %i",
294                                         d->type);
295                         break;
296                 }
297
298                 if (isnan (d->min))
299                 {
300                         sstrncpy (min, "U", sizeof (min));
301                 }
302                 else
303                         ssnprintf (min, sizeof (min), "%lf", d->min);
304
305                 if (isnan (d->max))
306                 {
307                         sstrncpy (max, "U", sizeof (max));
308                 }
309                 else
310                         ssnprintf (max, sizeof (max), "%lf", d->max);
311
312                 status = ssnprintf (buffer, sizeof (buffer),
313                                 "DS:%s:%s:%i:%s:%s",
314                                 d->name, type,
315                                 (heartbeat > 0) ? heartbeat : (2 * vl->interval),
316                                 min, max);
317                 if ((status < 1) || (status >= sizeof (buffer)))
318                         break;
319
320                 ds_def[ds_num] = sstrdup (buffer);
321         } /* for ds_num = 0 .. ds->ds_num */
322
323 #if COLLECT_DEBUG
324 {
325         int i;
326         DEBUG ("ds_num = %i", ds_num);
327         for (i = 0; i < ds_num; i++)
328                 DEBUG ("  %s", ds_def[i]);
329 }
330 #endif
331
332         if (ds_num != ds->ds_num)
333         {
334                 ds_free (ds_num, ds_def);
335                 return (-1);
336         }
337
338         *ret = ds_def;
339         return (ds_num);
340 }
341
342 #if HAVE_THREADSAFE_LIBRRD
343 static int srrd_create (char *filename, unsigned long pdp_step, time_t last_up,
344                 int argc, const char **argv)
345 {
346         int status;
347
348         optind = 0; /* bug in librrd? */
349         rrd_clear_error ();
350
351         status = rrd_create_r (filename, pdp_step, last_up, argc, (void *) argv);
352
353         if (status != 0)
354         {
355                 WARNING ("rrdtool plugin: rrd_create_r (%s) failed: %s",
356                                 filename, rrd_get_error ());
357         }
358
359         return (status);
360 } /* int srrd_create */
361
362 static int srrd_update (char *filename, char *template,
363                 int argc, const char **argv)
364 {
365         int status;
366
367         optind = 0; /* bug in librrd? */
368         rrd_clear_error ();
369
370         status = rrd_update_r (filename, template, argc, (void *) argv);
371
372         if (status != 0)
373         {
374                 WARNING ("rrdtool plugin: rrd_update_r (%s) failed: %s",
375                                 filename, rrd_get_error ());
376         }
377
378         return (status);
379 } /* int srrd_update */
380 /* #endif HAVE_THREADSAFE_LIBRRD */
381
382 #else /* !HAVE_THREADSAFE_LIBRRD */
383 static int srrd_create (char *filename, unsigned long pdp_step, time_t last_up,
384                 int argc, const char **argv)
385 {
386         int status;
387
388         int new_argc;
389         char **new_argv;
390
391         char pdp_step_str[16];
392         char last_up_str[16];
393
394         new_argc = 6 + argc;
395         new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
396         if (new_argv == NULL)
397         {
398                 ERROR ("rrdtool plugin: malloc failed.");
399                 return (-1);
400         }
401
402         if (last_up == 0)
403                 last_up = time (NULL) - 10;
404
405         ssnprintf (pdp_step_str, sizeof (pdp_step_str), "%lu", pdp_step);
406         ssnprintf (last_up_str, sizeof (last_up_str), "%u", (unsigned int) last_up);
407
408         new_argv[0] = "create";
409         new_argv[1] = filename;
410         new_argv[2] = "-s";
411         new_argv[3] = pdp_step_str;
412         new_argv[4] = "-b";
413         new_argv[5] = last_up_str;
414
415         memcpy (new_argv + 6, argv, argc * sizeof (char *));
416         new_argv[new_argc] = NULL;
417         
418         pthread_mutex_lock (&librrd_lock);
419         optind = 0; /* bug in librrd? */
420         rrd_clear_error ();
421
422         status = rrd_create (new_argc, new_argv);
423         pthread_mutex_unlock (&librrd_lock);
424
425         if (status != 0)
426         {
427                 WARNING ("rrdtool plugin: rrd_create (%s) failed: %s",
428                                 filename, rrd_get_error ());
429         }
430
431         sfree (new_argv);
432
433         return (status);
434 } /* int srrd_create */
435
436 static int srrd_update (char *filename, char *template,
437                 int argc, const char **argv)
438 {
439         int status;
440
441         int new_argc;
442         char **new_argv;
443
444         assert (template == NULL);
445
446         new_argc = 2 + argc;
447         new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
448         if (new_argv == NULL)
449         {
450                 ERROR ("rrdtool plugin: malloc failed.");
451                 return (-1);
452         }
453
454         new_argv[0] = "update";
455         new_argv[1] = filename;
456
457         memcpy (new_argv + 2, argv, argc * sizeof (char *));
458         new_argv[new_argc] = NULL;
459
460         pthread_mutex_lock (&librrd_lock);
461         optind = 0; /* bug in librrd? */
462         rrd_clear_error ();
463
464         status = rrd_update (new_argc, new_argv);
465         pthread_mutex_unlock (&librrd_lock);
466
467         if (status != 0)
468         {
469                 WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
470                                 argv[1], rrd_get_error ());
471         }
472
473         sfree (new_argv);
474
475         return (status);
476 } /* int srrd_update */
477 #endif /* !HAVE_THREADSAFE_LIBRRD */
478
479 static int rrd_create_file (char *filename, const data_set_t *ds, const value_list_t *vl)
480 {
481         char **argv;
482         int argc;
483         char **rra_def;
484         int rra_num;
485         char **ds_def;
486         int ds_num;
487         int status = 0;
488
489         if (check_create_dir (filename))
490                 return (-1);
491
492         if ((rra_num = rra_get (&rra_def, vl)) < 1)
493         {
494                 ERROR ("rrd_create_file failed: Could not calculate RRAs");
495                 return (-1);
496         }
497
498         if ((ds_num = ds_get (&ds_def, ds, vl)) < 1)
499         {
500                 ERROR ("rrd_create_file failed: Could not calculate DSes");
501                 return (-1);
502         }
503
504         argc = ds_num + rra_num;
505
506         if ((argv = (char **) malloc (sizeof (char *) * (argc + 1))) == NULL)
507         {
508                 char errbuf[1024];
509                 ERROR ("rrd_create failed: %s",
510                                 sstrerror (errno, errbuf, sizeof (errbuf)));
511                 return (-1);
512         }
513
514         memcpy (argv, ds_def, ds_num * sizeof (char *));
515         memcpy (argv + ds_num, rra_def, rra_num * sizeof (char *));
516         argv[ds_num + rra_num] = NULL;
517
518         assert (vl->time > 10);
519         status = srrd_create (filename,
520                         (stepsize > 0) ? stepsize : vl->interval,
521                         vl->time - 10,
522                         argc, (const char **)argv);
523
524         free (argv);
525         ds_free (ds_num, ds_def);
526         rra_free (rra_num, rra_def);
527
528         return (status);
529 }
530
531 static int value_list_to_string (char *buffer, int buffer_len,
532                 const data_set_t *ds, const value_list_t *vl)
533 {
534         int offset;
535         int status;
536         int i;
537
538         memset (buffer, '\0', buffer_len);
539
540         status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) vl->time);
541         if ((status < 1) || (status >= buffer_len))
542                 return (-1);
543         offset = status;
544
545         for (i = 0; i < ds->ds_num; i++)
546         {
547                 if ((ds->ds[i].type != DS_TYPE_COUNTER)
548                                 && (ds->ds[i].type != DS_TYPE_GAUGE))
549                         return (-1);
550
551                 if (ds->ds[i].type == DS_TYPE_COUNTER)
552                         status = ssnprintf (buffer + offset, buffer_len - offset,
553                                         ":%llu", vl->values[i].counter);
554                 else
555                         status = ssnprintf (buffer + offset, buffer_len - offset,
556                                         ":%lf", vl->values[i].gauge);
557
558                 if ((status < 1) || (status >= (buffer_len - offset)))
559                         return (-1);
560
561                 offset += status;
562         } /* for ds->ds_num */
563
564         return (0);
565 } /* int value_list_to_string */
566
567 static int value_list_to_filename (char *buffer, int buffer_len,
568                 const data_set_t *ds, const value_list_t *vl)
569 {
570         int offset = 0;
571         int status;
572
573         if (datadir != NULL)
574         {
575                 status = ssnprintf (buffer + offset, buffer_len - offset,
576                                 "%s/", datadir);
577                 if ((status < 1) || (status >= buffer_len - offset))
578                         return (-1);
579                 offset += status;
580         }
581
582         status = ssnprintf (buffer + offset, buffer_len - offset,
583                         "%s/", vl->host);
584         if ((status < 1) || (status >= buffer_len - offset))
585                 return (-1);
586         offset += status;
587
588         if (strlen (vl->plugin_instance) > 0)
589                 status = ssnprintf (buffer + offset, buffer_len - offset,
590                                 "%s-%s/", vl->plugin, vl->plugin_instance);
591         else
592                 status = ssnprintf (buffer + offset, buffer_len - offset,
593                                 "%s/", vl->plugin);
594         if ((status < 1) || (status >= buffer_len - offset))
595                 return (-1);
596         offset += status;
597
598         if (strlen (vl->type_instance) > 0)
599                 status = ssnprintf (buffer + offset, buffer_len - offset,
600                                 "%s-%s.rrd", vl->type, vl->type_instance);
601         else
602                 status = ssnprintf (buffer + offset, buffer_len - offset,
603                                 "%s.rrd", vl->type);
604         if ((status < 1) || (status >= buffer_len - offset))
605                 return (-1);
606         offset += status;
607
608         return (0);
609 } /* int value_list_to_filename */
610
611 static void *rrd_queue_thread (void *data)
612 {
613         struct timeval tv_next_update;
614         struct timeval tv_now;
615
616         gettimeofday (&tv_next_update, /* timezone = */ NULL);
617
618         while (42)
619         {
620                 rrd_queue_t *queue_entry;
621                 rrd_cache_t *cache_entry;
622                 char **values;
623                 int    values_num;
624                 int    i;
625
626                 pthread_mutex_lock (&queue_lock);
627                 /* Wait for values to arrive */
628                 while (true)
629                 {
630                   struct timespec ts_wait;
631                   int status;
632
633                   while ((flushq_head == NULL) && (queue_head == NULL)
634                       && (do_shutdown == 0))
635                     pthread_cond_wait (&queue_cond, &queue_lock);
636
637                   if ((flushq_head == NULL) && (queue_head == NULL))
638                     break;
639
640                   /* Don't delay if there's something to flush */
641                   if (flushq_head != NULL)
642                     break;
643
644                   /* Don't delay if we're shutting down */
645                   if (do_shutdown != 0)
646                     break;
647
648                   /* Don't delay if no delay was configured. */
649                   if (write_rate <= 0.0)
650                     break;
651
652                   gettimeofday (&tv_now, /* timezone = */ NULL);
653                   status = timeval_sub_timespec (&tv_next_update, &tv_now,
654                       &ts_wait);
655                   /* We're good to go */
656                   if (status != 0)
657                     break;
658
659                   /* We're supposed to wait a bit with this update, so we'll
660                    * wait for the next addition to the queue or to the end of
661                    * the wait period - whichever comes first. */
662                   ts_wait.tv_sec = tv_next_update.tv_sec;
663                   ts_wait.tv_nsec = 1000 * tv_next_update.tv_usec;
664
665                   status = pthread_cond_timedwait (&queue_cond, &queue_lock,
666                       &ts_wait);
667                   if (status == ETIMEDOUT)
668                     break;
669                 } /* while (true) */
670
671                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
672                  * the same time, ALWAYS lock `cache_lock' first! */
673
674                 /* We're in the shutdown phase */
675                 if ((flushq_head == NULL) && (queue_head == NULL))
676                 {
677                   pthread_mutex_unlock (&queue_lock);
678                   break;
679                 }
680
681                 if (flushq_head != NULL)
682                 {
683                   /* Dequeue the first flush entry */
684                   queue_entry = flushq_head;
685                   if (flushq_head == flushq_tail)
686                     flushq_head = flushq_tail = NULL;
687                   else
688                     flushq_head = flushq_head->next;
689                 }
690                 else /* if (queue_head != NULL) */
691                 {
692                   /* Dequeue the first regular entry */
693                   queue_entry = queue_head;
694                   if (queue_head == queue_tail)
695                     queue_head = queue_tail = NULL;
696                   else
697                     queue_head = queue_head->next;
698                 }
699
700                 /* Unlock the queue again */
701                 pthread_mutex_unlock (&queue_lock);
702
703                 /* We now need the cache lock so the entry isn't updated while
704                  * we make a copy of it's values */
705                 pthread_mutex_lock (&cache_lock);
706
707                 c_avl_get (cache, queue_entry->filename, (void *) &cache_entry);
708
709                 values = cache_entry->values;
710                 values_num = cache_entry->values_num;
711
712                 cache_entry->values = NULL;
713                 cache_entry->values_num = 0;
714                 cache_entry->flags = FLAG_NONE;
715
716                 pthread_mutex_unlock (&cache_lock);
717
718                 /* Update `tv_next_update' */
719                 if (write_rate > 0.0) 
720                 {
721                   gettimeofday (&tv_now, /* timezone = */ NULL);
722                   tv_next_update.tv_sec = tv_now.tv_sec;
723                   tv_next_update.tv_usec = tv_now.tv_usec
724                     + ((suseconds_t) (1000000 * write_rate));
725                   while (tv_next_update.tv_usec > 1000000)
726                   {
727                     tv_next_update.tv_sec++;
728                     tv_next_update.tv_usec -= 1000000;
729                   }
730                 }
731
732                 /* Write the values to the RRD-file */
733                 srrd_update (queue_entry->filename, NULL,
734                                 values_num, (const char **)values);
735                 DEBUG ("rrdtool plugin: queue thread: Wrote %i values to %s",
736                                 values_num, queue_entry->filename);
737
738                 for (i = 0; i < values_num; i++)
739                 {
740                         sfree (values[i]);
741                 }
742                 sfree (values);
743                 sfree (queue_entry->filename);
744                 sfree (queue_entry);
745         } /* while (42) */
746
747         pthread_mutex_lock (&cache_lock);
748         c_avl_destroy (cache);
749         cache = NULL;
750         pthread_mutex_unlock (&cache_lock);
751
752         pthread_exit ((void *) 0);
753         return ((void *) 0);
754 } /* void *rrd_queue_thread */
755
756 static int rrd_queue_enqueue (const char *filename,
757     rrd_queue_t **head, rrd_queue_t **tail)
758 {
759   rrd_queue_t *queue_entry;
760
761   queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
762   if (queue_entry == NULL)
763     return (-1);
764
765   queue_entry->filename = strdup (filename);
766   if (queue_entry->filename == NULL)
767   {
768     free (queue_entry);
769     return (-1);
770   }
771
772   queue_entry->next = NULL;
773
774   pthread_mutex_lock (&queue_lock);
775
776   if (*tail == NULL)
777     *head = queue_entry;
778   else
779     (*tail)->next = queue_entry;
780   *tail = queue_entry;
781
782   pthread_cond_signal (&queue_cond);
783   pthread_mutex_unlock (&queue_lock);
784
785   return (0);
786 } /* int rrd_queue_enqueue */
787
788 static int rrd_queue_dequeue (const char *filename,
789     rrd_queue_t **head, rrd_queue_t **tail)
790 {
791   rrd_queue_t *this;
792   rrd_queue_t *prev;
793
794   pthread_mutex_lock (&queue_lock);
795
796   prev = NULL;
797   this = *head;
798
799   while (this != NULL)
800   {
801     if (strcmp (this->filename, filename) == 0)
802       break;
803     
804     prev = this;
805     this = this->next;
806   }
807
808   if (this == NULL)
809   {
810     pthread_mutex_unlock (&queue_lock);
811     return (-1);
812   }
813
814   if (prev == NULL)
815     *head = this->next;
816   else
817     prev->next = this->next;
818
819   if (this->next == NULL)
820     *tail = prev;
821
822   pthread_mutex_unlock (&queue_lock);
823
824   sfree (this->filename);
825   sfree (this);
826
827   return (0);
828 } /* int rrd_queue_dequeue */
829
830 static void rrd_cache_flush (int timeout)
831 {
832         rrd_cache_t *rc;
833         time_t       now;
834
835         char **keys = NULL;
836         int    keys_num = 0;
837
838         char *key;
839         c_avl_iterator_t *iter;
840         int i;
841
842         DEBUG ("rrdtool plugin: Flushing cache, timeout = %i", timeout);
843
844         now = time (NULL);
845
846         /* Build a list of entries to be flushed */
847         iter = c_avl_get_iterator (cache);
848         while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
849         {
850                 if (rc->flags != FLAG_NONE)
851                         continue;
852                 else if ((now - rc->first_value) < timeout)
853                         continue;
854                 else if (rc->values_num > 0)
855                 {
856                         int status;
857
858                         status = rrd_queue_enqueue (key, &queue_head,  &queue_tail);
859                         if (status == 0)
860                                 rc->flags = FLAG_QUEUED;
861                 }
862                 else /* ancient and no values -> waste of memory */
863                 {
864                         char **tmp = (char **) realloc ((void *) keys,
865                                         (keys_num + 1) * sizeof (char *));
866                         if (tmp == NULL)
867                         {
868                                 char errbuf[1024];
869                                 ERROR ("rrdtool plugin: "
870                                                 "realloc failed: %s",
871                                                 sstrerror (errno, errbuf,
872                                                         sizeof (errbuf)));
873                                 c_avl_iterator_destroy (iter);
874                                 sfree (keys);
875                                 return;
876                         }
877                         keys = tmp;
878                         keys[keys_num] = key;
879                         keys_num++;
880                 }
881         } /* while (c_avl_iterator_next) */
882         c_avl_iterator_destroy (iter);
883         
884         for (i = 0; i < keys_num; i++)
885         {
886                 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
887                 {
888                         DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
889                         continue;
890                 }
891
892                 assert (rc->values == NULL);
893                 assert (rc->values_num == 0);
894
895                 sfree (rc);
896                 sfree (key);
897                 keys[i] = NULL;
898         } /* for (i = 0..keys_num) */
899
900         sfree (keys);
901
902         cache_flush_last = now;
903 } /* void rrd_cache_flush */
904
905 static int rrd_cache_flush_identifier (int timeout, const char *identifier)
906 {
907   rrd_cache_t *rc;
908   time_t now;
909   int status;
910   char key[2048];
911
912   if (identifier == NULL)
913   {
914     rrd_cache_flush (timeout);
915     return (0);
916   }
917
918   now = time (NULL);
919
920   if (datadir == NULL)
921     snprintf (key, sizeof (key), "%s.rrd",
922         identifier);
923   else
924     snprintf (key, sizeof (key), "%s/%s.rrd",
925         datadir, identifier);
926   key[sizeof (key) - 1] = 0;
927
928   status = c_avl_get (cache, key, (void *) &rc);
929   if (status != 0)
930   {
931     WARNING ("rrdtool plugin: rrd_cache_flush_identifier: "
932         "c_avl_get (%s) failed. Does that file really exist?",
933         key);
934     return (status);
935   }
936
937   if (rc->flags == FLAG_FLUSHQ)
938   {
939     status = 0;
940   }
941   else if (rc->flags == FLAG_QUEUED)
942   {
943     rrd_queue_dequeue (key, &queue_head, &queue_tail);
944     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
945     if (status == 0)
946       rc->flags = FLAG_FLUSHQ;
947   }
948   else if ((now - rc->first_value) < timeout)
949   {
950     status = 0;
951   }
952   else if (rc->values_num > 0)
953   {
954     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
955     if (status == 0)
956       rc->flags = FLAG_FLUSHQ;
957   }
958
959   return (status);
960 } /* int rrd_cache_flush_identifier */
961
962 static int rrd_cache_insert (const char *filename,
963                 const char *value, time_t value_time)
964 {
965         rrd_cache_t *rc = NULL;
966         int new_rc = 0;
967         char **values_new;
968
969         pthread_mutex_lock (&cache_lock);
970
971         c_avl_get (cache, filename, (void *) &rc);
972
973         if (rc == NULL)
974         {
975                 rc = (rrd_cache_t *) malloc (sizeof (rrd_cache_t));
976                 if (rc == NULL)
977                         return (-1);
978                 rc->values_num = 0;
979                 rc->values = NULL;
980                 rc->first_value = 0;
981                 rc->last_value = 0;
982                 rc->flags = FLAG_NONE;
983                 new_rc = 1;
984         }
985
986         if (rc->last_value >= value_time)
987         {
988                 pthread_mutex_unlock (&cache_lock);
989                 WARNING ("rrdtool plugin: (rc->last_value = %u) >= (value_time = %u)",
990                                 (unsigned int) rc->last_value,
991                                 (unsigned int) value_time);
992                 return (-1);
993         }
994
995         values_new = (char **) realloc ((void *) rc->values,
996                         (rc->values_num + 1) * sizeof (char *));
997         if (values_new == NULL)
998         {
999                 char errbuf[1024];
1000                 void *cache_key = NULL;
1001
1002                 sstrerror (errno, errbuf, sizeof (errbuf));
1003
1004                 c_avl_remove (cache, filename, &cache_key, NULL);
1005                 pthread_mutex_unlock (&cache_lock);
1006
1007                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
1008
1009                 sfree (cache_key);
1010                 sfree (rc->values);
1011                 sfree (rc);
1012                 return (-1);
1013         }
1014         rc->values = values_new;
1015
1016         rc->values[rc->values_num] = strdup (value);
1017         if (rc->values[rc->values_num] != NULL)
1018                 rc->values_num++;
1019
1020         if (rc->values_num == 1)
1021                 rc->first_value = value_time;
1022         rc->last_value = value_time;
1023
1024         /* Insert if this is the first value */
1025         if (new_rc == 1)
1026         {
1027                 void *cache_key = strdup (filename);
1028
1029                 if (cache_key == NULL)
1030                 {
1031                         char errbuf[1024];
1032                         sstrerror (errno, errbuf, sizeof (errbuf));
1033
1034                         pthread_mutex_unlock (&cache_lock);
1035
1036                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
1037
1038                         sfree (rc->values[0]);
1039                         sfree (rc->values);
1040                         sfree (rc);
1041                         return (-1);
1042                 }
1043
1044                 c_avl_insert (cache, cache_key, rc);
1045         }
1046
1047         DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
1048                         "values_num = %i; age = %lu;",
1049                         filename, rc->values_num,
1050                         (unsigned long)(rc->last_value - rc->first_value));
1051
1052         if ((rc->last_value - rc->first_value) >= cache_timeout)
1053         {
1054                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
1055                  * the same time, ALWAYS lock `cache_lock' first! */
1056                 if (rc->flags == FLAG_NONE)
1057                 {
1058                         int status;
1059
1060                         status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
1061                         if (status == 0)
1062                                 rc->flags = FLAG_QUEUED;
1063                 }
1064                 else
1065                 {
1066                         DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
1067                 }
1068         }
1069
1070         if ((cache_timeout > 0) &&
1071                         ((time (NULL) - cache_flush_last) > cache_flush_timeout))
1072                 rrd_cache_flush (cache_flush_timeout);
1073
1074         pthread_mutex_unlock (&cache_lock);
1075
1076         return (0);
1077 } /* int rrd_cache_insert */
1078
1079 static int rrd_compare_numeric (const void *a_ptr, const void *b_ptr)
1080 {
1081         int a = *((int *) a_ptr);
1082         int b = *((int *) b_ptr);
1083
1084         if (a < b)
1085                 return (-1);
1086         else if (a > b)
1087                 return (1);
1088         else
1089                 return (0);
1090 } /* int rrd_compare_numeric */
1091
1092 static int rrd_write (const data_set_t *ds, const value_list_t *vl)
1093 {
1094         struct stat  statbuf;
1095         char         filename[512];
1096         char         values[512];
1097         int          status;
1098
1099         if (0 != strcmp (ds->type, vl->type)) {
1100                 ERROR ("rrdtool plugin: DS type does not match value list type");
1101                 return -1;
1102         }
1103
1104         if (value_list_to_filename (filename, sizeof (filename), ds, vl) != 0)
1105                 return (-1);
1106
1107         if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
1108                 return (-1);
1109
1110         if (stat (filename, &statbuf) == -1)
1111         {
1112                 if (errno == ENOENT)
1113                 {
1114                         if (rrd_create_file (filename, ds, vl))
1115                                 return (-1);
1116                 }
1117                 else
1118                 {
1119                         char errbuf[1024];
1120                         ERROR ("stat(%s) failed: %s", filename,
1121                                         sstrerror (errno, errbuf,
1122                                                 sizeof (errbuf)));
1123                         return (-1);
1124                 }
1125         }
1126         else if (!S_ISREG (statbuf.st_mode))
1127         {
1128                 ERROR ("stat(%s): Not a regular file!",
1129                                 filename);
1130                 return (-1);
1131         }
1132
1133         status = rrd_cache_insert (filename, values, vl->time);
1134
1135         return (status);
1136 } /* int rrd_write */
1137
1138 static int rrd_flush (int timeout, const char *identifier)
1139 {
1140         pthread_mutex_lock (&cache_lock);
1141
1142         if (cache == NULL) {
1143                 pthread_mutex_unlock (&cache_lock);
1144                 return (0);
1145         }
1146
1147         rrd_cache_flush_identifier (timeout, identifier);
1148
1149         pthread_mutex_unlock (&cache_lock);
1150         return (0);
1151 } /* int rrd_flush */
1152
1153 static int rrd_config (const char *key, const char *value)
1154 {
1155         if (strcasecmp ("CacheTimeout", key) == 0)
1156         {
1157                 int tmp = atoi (value);
1158                 if (tmp < 0)
1159                 {
1160                         fprintf (stderr, "rrdtool: `CacheTimeout' must "
1161                                         "be greater than 0.\n");
1162                         ERROR ("rrdtool: `CacheTimeout' must "
1163                                         "be greater than 0.\n");
1164                         return (1);
1165                 }
1166                 cache_timeout = tmp;
1167         }
1168         else if (strcasecmp ("CacheFlush", key) == 0)
1169         {
1170                 int tmp = atoi (value);
1171                 if (tmp < 0)
1172                 {
1173                         fprintf (stderr, "rrdtool: `CacheFlush' must "
1174                                         "be greater than 0.\n");
1175                         ERROR ("rrdtool: `CacheFlush' must "
1176                                         "be greater than 0.\n");
1177                         return (1);
1178                 }
1179                 cache_flush_timeout = tmp;
1180         }
1181         else if (strcasecmp ("DataDir", key) == 0)
1182         {
1183                 if (datadir != NULL)
1184                         free (datadir);
1185                 datadir = strdup (value);
1186                 if (datadir != NULL)
1187                 {
1188                         int len = strlen (datadir);
1189                         while ((len > 0) && (datadir[len - 1] == '/'))
1190                         {
1191                                 len--;
1192                                 datadir[len] = '\0';
1193                         }
1194                         if (len <= 0)
1195                         {
1196                                 free (datadir);
1197                                 datadir = NULL;
1198                         }
1199                 }
1200         }
1201         else if (strcasecmp ("StepSize", key) == 0)
1202         {
1203                 stepsize = atoi (value);
1204                 if (stepsize < 0)
1205                         stepsize = 0;
1206         }
1207         else if (strcasecmp ("HeartBeat", key) == 0)
1208         {
1209                 heartbeat = atoi (value);
1210                 if (heartbeat < 0)
1211                         heartbeat = 0;
1212         }
1213         else if (strcasecmp ("RRARows", key) == 0)
1214         {
1215                 int tmp = atoi (value);
1216                 if (tmp <= 0)
1217                 {
1218                         fprintf (stderr, "rrdtool: `RRARows' must "
1219                                         "be greater than 0.\n");
1220                         ERROR ("rrdtool: `RRARows' must "
1221                                         "be greater than 0.\n");
1222                         return (1);
1223                 }
1224                 rrarows = tmp;
1225         }
1226         else if (strcasecmp ("RRATimespan", key) == 0)
1227         {
1228                 char *saveptr = NULL;
1229                 char *dummy;
1230                 char *ptr;
1231                 char *value_copy;
1232                 int *tmp_alloc;
1233
1234                 value_copy = strdup (value);
1235                 if (value_copy == NULL)
1236                         return (1);
1237
1238                 dummy = value_copy;
1239                 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
1240                 {
1241                         dummy = NULL;
1242                         
1243                         tmp_alloc = realloc (rra_timespans_custom,
1244                                         sizeof (int) * (rra_timespans_custom_num + 1));
1245                         if (tmp_alloc == NULL)
1246                         {
1247                                 fprintf (stderr, "rrdtool: realloc failed.\n");
1248                                 ERROR ("rrdtool: realloc failed.\n");
1249                                 free (value_copy);
1250                                 return (1);
1251                         }
1252                         rra_timespans_custom = tmp_alloc;
1253                         rra_timespans_custom[rra_timespans_custom_num] = atoi (ptr);
1254                         if (rra_timespans_custom[rra_timespans_custom_num] != 0)
1255                                 rra_timespans_custom_num++;
1256                 } /* while (strtok_r) */
1257
1258                 qsort (/* base = */ rra_timespans_custom,
1259                                 /* nmemb  = */ rra_timespans_custom_num,
1260                                 /* size   = */ sizeof (rra_timespans_custom[0]),
1261                                 /* compar = */ rrd_compare_numeric);
1262
1263                 free (value_copy);
1264         }
1265         else if (strcasecmp ("XFF", key) == 0)
1266         {
1267                 double tmp = atof (value);
1268                 if ((tmp < 0.0) || (tmp >= 1.0))
1269                 {
1270                         fprintf (stderr, "rrdtool: `XFF' must "
1271                                         "be in the range 0 to 1 (exclusive).");
1272                         ERROR ("rrdtool: `XFF' must "
1273                                         "be in the range 0 to 1 (exclusive).");
1274                         return (1);
1275                 }
1276                 xff = tmp;
1277         }
1278         else if (strcasecmp ("WritesPerSecond", key) == 0)
1279         {
1280                 double wps = atof (value);
1281
1282                 if (wps < 0.0)
1283                 {
1284                         fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
1285                                         "greater than or equal to zero.");
1286                         return (1);
1287                 }
1288                 else if (wps == 0.0)
1289                 {
1290                         write_rate = 0.0;
1291                 }
1292                 else
1293                 {
1294                         write_rate = 1.0 / wps;
1295                 }
1296         }
1297         else
1298         {
1299                 return (-1);
1300         }
1301         return (0);
1302 } /* int rrd_config */
1303
1304 static int rrd_shutdown (void)
1305 {
1306         pthread_mutex_lock (&cache_lock);
1307         rrd_cache_flush (-1);
1308         pthread_mutex_unlock (&cache_lock);
1309
1310         pthread_mutex_lock (&queue_lock);
1311         do_shutdown = 1;
1312         pthread_cond_signal (&queue_cond);
1313         pthread_mutex_unlock (&queue_lock);
1314
1315         /* Wait for all the values to be written to disk before returning. */
1316         if (queue_thread != 0)
1317         {
1318                 pthread_join (queue_thread, NULL);
1319                 queue_thread = 0;
1320                 DEBUG ("rrdtool plugin: queue_thread exited.");
1321         }
1322
1323         return (0);
1324 } /* int rrd_shutdown */
1325
1326 static int rrd_init (void)
1327 {
1328         int status;
1329
1330         if (stepsize < 0)
1331                 stepsize = 0;
1332         if (heartbeat <= 0)
1333                 heartbeat = 2 * stepsize;
1334
1335         if ((heartbeat > 0) && (heartbeat < interval_g))
1336                 WARNING ("rrdtool plugin: Your `heartbeat' is "
1337                                 "smaller than your `interval'. This will "
1338                                 "likely cause problems.");
1339         else if ((stepsize > 0) && (stepsize < interval_g))
1340                 WARNING ("rrdtool plugin: Your `stepsize' is "
1341                                 "smaller than your `interval'. This will "
1342                                 "create needlessly big RRD-files.");
1343
1344         /* Set the cache up */
1345         pthread_mutex_lock (&cache_lock);
1346
1347         cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1348         if (cache == NULL)
1349         {
1350                 ERROR ("rrdtool plugin: c_avl_create failed.");
1351                 return (-1);
1352         }
1353
1354         cache_flush_last = time (NULL);
1355         if (cache_timeout < 2)
1356         {
1357                 cache_timeout = 0;
1358                 cache_flush_timeout = 0;
1359         }
1360         else if (cache_flush_timeout < cache_timeout)
1361                 cache_flush_timeout = 10 * cache_timeout;
1362
1363         pthread_mutex_unlock (&cache_lock);
1364
1365         status = pthread_create (&queue_thread, NULL, rrd_queue_thread, NULL);
1366         if (status != 0)
1367         {
1368                 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1369                 return (-1);
1370         }
1371
1372         DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %i;"
1373                         " heartbeat = %i; rrarows = %i; xff = %lf;",
1374                         (datadir == NULL) ? "(null)" : datadir,
1375                         stepsize, heartbeat, rrarows, xff);
1376
1377         return (0);
1378 } /* int rrd_init */
1379
1380 void module_register (void)
1381 {
1382         plugin_register_config ("rrdtool", rrd_config,
1383                         config_keys, config_keys_num);
1384         plugin_register_init ("rrdtool", rrd_init);
1385         plugin_register_write ("rrdtool", rrd_write);
1386         plugin_register_flush ("rrdtool", rrd_flush);
1387         plugin_register_shutdown ("rrdtool", rrd_shutdown);
1388 }