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