Code

Merge branch 'collectd-5.2' into collectd-5.3
[collectd.git] / src / rrdtool.c
1 /**
2  * collectd - src/rrdtool.c
3  * Copyright (C) 2006-2013  Florian octo Forster
4  * Copyright (C) 2008-2008  Sebastian Harl
5  * Copyright (C) 2009       Mariusz Gronczewski
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Sebastian Harl <sh at tokkee.org>
23  *   Mariusz Gronczewski <xani666 at gmail.com>
24  **/
26 #include "collectd.h"
27 #include "plugin.h"
28 #include "common.h"
29 #include "utils_avltree.h"
30 #include "utils_random.h"
31 #include "utils_rrdcreate.h"
33 #include <rrd.h>
35 #if HAVE_PTHREAD_H
36 # include <pthread.h>
37 #endif
39 /*
40  * Private types
41  */
42 struct rrd_cache_s
43 {
44         int      values_num;
45         char   **values;
46         cdtime_t first_value;
47         cdtime_t last_value;
48         int64_t  random_variation;
49         enum
50         {
51                 FLAG_NONE   = 0x00,
52                 FLAG_QUEUED = 0x01,
53                 FLAG_FLUSHQ = 0x02
54         } flags;
55 };
56 typedef struct rrd_cache_s rrd_cache_t;
58 enum rrd_queue_dir_e
59 {
60   QUEUE_INSERT_FRONT,
61   QUEUE_INSERT_BACK
62 };
63 typedef enum rrd_queue_dir_e rrd_queue_dir_t;
65 struct rrd_queue_s
66 {
67         char *filename;
68         struct rrd_queue_s *next;
69 };
70 typedef struct rrd_queue_s rrd_queue_t;
72 /*
73  * Private variables
74  */
75 static const char *config_keys[] =
76 {
77         "CacheTimeout",
78         "CacheFlush",
79         "CreateFilesAsync",
80         "DataDir",
81         "StepSize",
82         "HeartBeat",
83         "RRARows",
84         "RRATimespan",
85         "XFF",
86         "WritesPerSecond",
87         "RandomTimeout"
88 };
89 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
91 /* If datadir is zero, the daemon's basedir is used. If stepsize or heartbeat
92  * is zero a default, depending on the `interval' member of the value list is
93  * being used. */
94 static char *datadir   = NULL;
95 static double write_rate = 0.0;
96 static rrdcreate_config_t rrdcreate_config =
97 {
98         /* stepsize = */ 0,
99         /* heartbeat = */ 0,
100         /* rrarows = */ 1200,
101         /* xff = */ 0.1,
103         /* timespans = */ NULL,
104         /* timespans_num = */ 0,
106         /* consolidation_functions = */ NULL,
107         /* consolidation_functions_num = */ 0,
109         /* async = */ 0
110 };
112 /* XXX: If you need to lock both, cache_lock and queue_lock, at the same time,
113  * ALWAYS lock `cache_lock' first! */
114 static cdtime_t    cache_timeout = 0;
115 static cdtime_t    cache_flush_timeout = 0;
116 static cdtime_t    random_timeout = TIME_T_TO_CDTIME_T (1);
117 static cdtime_t    cache_flush_last;
118 static c_avl_tree_t *cache = NULL;
119 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
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;
126 static int             queue_thread_running = 1;
127 static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER;
128 static pthread_cond_t  queue_cond = PTHREAD_COND_INITIALIZER;
130 #if !HAVE_THREADSAFE_LIBRRD
131 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
132 #endif
134 static int do_shutdown = 0;
136 #if HAVE_THREADSAFE_LIBRRD
137 static int srrd_update (char *filename, char *template,
138                 int argc, const char **argv)
140         int status;
142         optind = 0; /* bug in librrd? */
143         rrd_clear_error ();
145         status = rrd_update_r (filename, template, argc, (void *) argv);
147         if (status != 0)
148         {
149                 WARNING ("rrdtool plugin: rrd_update_r (%s) failed: %s",
150                                 filename, rrd_get_error ());
151         }
153         return (status);
154 } /* int srrd_update */
155 /* #endif HAVE_THREADSAFE_LIBRRD */
157 #else /* !HAVE_THREADSAFE_LIBRRD */
158 static int srrd_update (char *filename, char *template,
159                 int argc, const char **argv)
161         int status;
163         int new_argc;
164         char **new_argv;
166         assert (template == NULL);
168         new_argc = 2 + argc;
169         new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
170         if (new_argv == NULL)
171         {
172                 ERROR ("rrdtool plugin: malloc failed.");
173                 return (-1);
174         }
176         new_argv[0] = "update";
177         new_argv[1] = filename;
179         memcpy (new_argv + 2, argv, argc * sizeof (char *));
180         new_argv[new_argc] = NULL;
182         pthread_mutex_lock (&librrd_lock);
183         optind = 0; /* bug in librrd? */
184         rrd_clear_error ();
186         status = rrd_update (new_argc, new_argv);
187         pthread_mutex_unlock (&librrd_lock);
189         if (status != 0)
190         {
191                 WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
192                                 filename, rrd_get_error ());
193         }
195         sfree (new_argv);
197         return (status);
198 } /* int srrd_update */
199 #endif /* !HAVE_THREADSAFE_LIBRRD */
201 static int value_list_to_string (char *buffer, int buffer_len,
202                 const data_set_t *ds, const value_list_t *vl)
204         int offset;
205         int status;
206         time_t tt;
207         int i;
209         memset (buffer, '\0', buffer_len);
211         tt = CDTIME_T_TO_TIME_T (vl->time);
212         status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) tt);
213         if ((status < 1) || (status >= buffer_len))
214                 return (-1);
215         offset = status;
217         for (i = 0; i < ds->ds_num; i++)
218         {
219                 if ((ds->ds[i].type != DS_TYPE_COUNTER)
220                                 && (ds->ds[i].type != DS_TYPE_GAUGE)
221                                 && (ds->ds[i].type != DS_TYPE_DERIVE)
222                                 && (ds->ds[i].type != DS_TYPE_ABSOLUTE))
223                         return (-1);
225                 if (ds->ds[i].type == DS_TYPE_COUNTER)
226                         status = ssnprintf (buffer + offset, buffer_len - offset,
227                                         ":%llu", vl->values[i].counter);
228                 else if (ds->ds[i].type == DS_TYPE_GAUGE)
229                         status = ssnprintf (buffer + offset, buffer_len - offset,
230                                         ":%lf", vl->values[i].gauge);
231                 else if (ds->ds[i].type == DS_TYPE_DERIVE)
232                         status = ssnprintf (buffer + offset, buffer_len - offset,
233                                         ":%"PRIi64, vl->values[i].derive);
234                 else /*if (ds->ds[i].type == DS_TYPE_ABSOLUTE) */
235                         status = ssnprintf (buffer + offset, buffer_len - offset,
236                                         ":%"PRIu64, vl->values[i].absolute);
238                 if ((status < 1) || (status >= (buffer_len - offset)))
239                         return (-1);
241                 offset += status;
242         } /* for ds->ds_num */
244         return (0);
245 } /* int value_list_to_string */
247 static int value_list_to_filename (char *buffer, size_t buffer_size,
248                 value_list_t const *vl)
250         char const suffix[] = ".rrd";
251         int status;
252         size_t len;
254         status = FORMAT_VL (buffer, buffer_size, vl);
255         if (status != 0)
256                 return (status);
258         len = strlen (buffer);
259         assert (len < buffer_size);
260         buffer += len;
261         buffer_size -= len;
263         if (buffer_size <= sizeof (suffix))
264                 return (ENOMEM);
266         memcpy (buffer, suffix, sizeof (suffix));
267         return (0);
268 } /* int value_list_to_filename */
270 static void *rrd_queue_thread (void __attribute__((unused)) *data)
272         struct timeval tv_next_update;
273         struct timeval tv_now;
275         gettimeofday (&tv_next_update, /* timezone = */ NULL);
277         while (42)
278         {
279                 rrd_queue_t *queue_entry;
280                 rrd_cache_t *cache_entry;
281                 char **values;
282                 int    values_num;
283                 int    status;
284                 int    i;
286                 values = NULL;
287                 values_num = 0;
289                 pthread_mutex_lock (&queue_lock);
290                 /* Wait for values to arrive */
291                 while (42)
292                 {
293                   struct timespec ts_wait;
295                   while ((flushq_head == NULL) && (queue_head == NULL)
296                       && (do_shutdown == 0))
297                     pthread_cond_wait (&queue_cond, &queue_lock);
299                   if ((flushq_head == NULL) && (queue_head == NULL))
300                     break;
302                   /* Don't delay if there's something to flush */
303                   if (flushq_head != NULL)
304                     break;
306                   /* Don't delay if we're shutting down */
307                   if (do_shutdown != 0)
308                     break;
310                   /* Don't delay if no delay was configured. */
311                   if (write_rate <= 0.0)
312                     break;
314                   gettimeofday (&tv_now, /* timezone = */ NULL);
315                   status = timeval_cmp (tv_next_update, tv_now, NULL);
316                   /* We're good to go */
317                   if (status <= 0)
318                     break;
320                   /* We're supposed to wait a bit with this update, so we'll
321                    * wait for the next addition to the queue or to the end of
322                    * the wait period - whichever comes first. */
323                   ts_wait.tv_sec = tv_next_update.tv_sec;
324                   ts_wait.tv_nsec = 1000 * tv_next_update.tv_usec;
326                   status = pthread_cond_timedwait (&queue_cond, &queue_lock,
327                       &ts_wait);
328                   if (status == ETIMEDOUT)
329                     break;
330                 } /* while (42) */
332                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
333                  * the same time, ALWAYS lock `cache_lock' first! */
335                 /* We're in the shutdown phase */
336                 if ((flushq_head == NULL) && (queue_head == NULL))
337                 {
338                   pthread_mutex_unlock (&queue_lock);
339                   break;
340                 }
342                 if (flushq_head != NULL)
343                 {
344                   /* Dequeue the first flush entry */
345                   queue_entry = flushq_head;
346                   if (flushq_head == flushq_tail)
347                     flushq_head = flushq_tail = NULL;
348                   else
349                     flushq_head = flushq_head->next;
350                 }
351                 else /* if (queue_head != NULL) */
352                 {
353                   /* Dequeue the first regular entry */
354                   queue_entry = queue_head;
355                   if (queue_head == queue_tail)
356                     queue_head = queue_tail = NULL;
357                   else
358                     queue_head = queue_head->next;
359                 }
361                 /* Unlock the queue again */
362                 pthread_mutex_unlock (&queue_lock);
364                 /* We now need the cache lock so the entry isn't updated while
365                  * we make a copy of it's values */
366                 pthread_mutex_lock (&cache_lock);
368                 status = c_avl_get (cache, queue_entry->filename,
369                                 (void *) &cache_entry);
371                 if (status == 0)
372                 {
373                         values = cache_entry->values;
374                         values_num = cache_entry->values_num;
376                         cache_entry->values = NULL;
377                         cache_entry->values_num = 0;
378                         cache_entry->flags = FLAG_NONE;
379                 }
381                 pthread_mutex_unlock (&cache_lock);
383                 if (status != 0)
384                 {
385                         sfree (queue_entry->filename);
386                         sfree (queue_entry);
387                         continue;
388                 }
390                 /* Update `tv_next_update' */
391                 if (write_rate > 0.0) 
392                 {
393                   gettimeofday (&tv_now, /* timezone = */ NULL);
394                   tv_next_update.tv_sec = tv_now.tv_sec;
395                   tv_next_update.tv_usec = tv_now.tv_usec
396                     + ((suseconds_t) (1000000 * write_rate));
397                   while (tv_next_update.tv_usec > 1000000)
398                   {
399                     tv_next_update.tv_sec++;
400                     tv_next_update.tv_usec -= 1000000;
401                   }
402                 }
404                 /* Write the values to the RRD-file */
405                 srrd_update (queue_entry->filename, NULL,
406                                 values_num, (const char **)values);
407                 DEBUG ("rrdtool plugin: queue thread: Wrote %i value%s to %s",
408                                 values_num, (values_num == 1) ? "" : "s",
409                                 queue_entry->filename);
411                 for (i = 0; i < values_num; i++)
412                 {
413                         sfree (values[i]);
414                 }
415                 sfree (values);
416                 sfree (queue_entry->filename);
417                 sfree (queue_entry);
418         } /* while (42) */
420         pthread_exit ((void *) 0);
421         return ((void *) 0);
422 } /* void *rrd_queue_thread */
424 static int rrd_queue_enqueue (const char *filename,
425     rrd_queue_t **head, rrd_queue_t **tail)
427   rrd_queue_t *queue_entry;
429   queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
430   if (queue_entry == NULL)
431     return (-1);
433   queue_entry->filename = strdup (filename);
434   if (queue_entry->filename == NULL)
435   {
436     free (queue_entry);
437     return (-1);
438   }
440   queue_entry->next = NULL;
442   pthread_mutex_lock (&queue_lock);
444   if (*tail == NULL)
445     *head = queue_entry;
446   else
447     (*tail)->next = queue_entry;
448   *tail = queue_entry;
450   pthread_cond_signal (&queue_cond);
451   pthread_mutex_unlock (&queue_lock);
453   return (0);
454 } /* int rrd_queue_enqueue */
456 static int rrd_queue_dequeue (const char *filename,
457     rrd_queue_t **head, rrd_queue_t **tail)
459   rrd_queue_t *this;
460   rrd_queue_t *prev;
462   pthread_mutex_lock (&queue_lock);
464   prev = NULL;
465   this = *head;
467   while (this != NULL)
468   {
469     if (strcmp (this->filename, filename) == 0)
470       break;
471     
472     prev = this;
473     this = this->next;
474   }
476   if (this == NULL)
477   {
478     pthread_mutex_unlock (&queue_lock);
479     return (-1);
480   }
482   if (prev == NULL)
483     *head = this->next;
484   else
485     prev->next = this->next;
487   if (this->next == NULL)
488     *tail = prev;
490   pthread_mutex_unlock (&queue_lock);
492   sfree (this->filename);
493   sfree (this);
495   return (0);
496 } /* int rrd_queue_dequeue */
498 /* XXX: You must hold "cache_lock" when calling this function! */
499 static void rrd_cache_flush (cdtime_t timeout)
501         rrd_cache_t *rc;
502         cdtime_t     now;
504         char **keys = NULL;
505         int    keys_num = 0;
507         char *key;
508         c_avl_iterator_t *iter;
509         int i;
511         DEBUG ("rrdtool plugin: Flushing cache, timeout = %.3f",
512                         CDTIME_T_TO_DOUBLE (timeout));
514         now = cdtime ();
515         timeout = TIME_T_TO_CDTIME_T (timeout);
517         /* Build a list of entries to be flushed */
518         iter = c_avl_get_iterator (cache);
519         while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
520         {
521                 if (rc->flags != FLAG_NONE)
522                         continue;
523                 /* timeout == 0  =>  flush everything */
524                 else if ((timeout != 0)
525                                 && ((now - rc->first_value) < timeout))
526                         continue;
527                 else if (rc->values_num > 0)
528                 {
529                         int status;
531                         status = rrd_queue_enqueue (key, &queue_head,  &queue_tail);
532                         if (status == 0)
533                                 rc->flags = FLAG_QUEUED;
534                 }
535                 else /* ancient and no values -> waste of memory */
536                 {
537                         char **tmp = (char **) realloc ((void *) keys,
538                                         (keys_num + 1) * sizeof (char *));
539                         if (tmp == NULL)
540                         {
541                                 char errbuf[1024];
542                                 ERROR ("rrdtool plugin: "
543                                                 "realloc failed: %s",
544                                                 sstrerror (errno, errbuf,
545                                                         sizeof (errbuf)));
546                                 c_avl_iterator_destroy (iter);
547                                 sfree (keys);
548                                 return;
549                         }
550                         keys = tmp;
551                         keys[keys_num] = key;
552                         keys_num++;
553                 }
554         } /* while (c_avl_iterator_next) */
555         c_avl_iterator_destroy (iter);
556         
557         for (i = 0; i < keys_num; i++)
558         {
559                 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
560                 {
561                         DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
562                         continue;
563                 }
565                 assert (rc->values == NULL);
566                 assert (rc->values_num == 0);
568                 sfree (rc);
569                 sfree (key);
570                 keys[i] = NULL;
571         } /* for (i = 0..keys_num) */
573         sfree (keys);
575         cache_flush_last = now;
576 } /* void rrd_cache_flush */
578 static int rrd_cache_flush_identifier (cdtime_t timeout,
579     const char *identifier)
581   rrd_cache_t *rc;
582   cdtime_t now;
583   int status;
584   char key[2048];
586   if (identifier == NULL)
587   {
588     rrd_cache_flush (timeout);
589     return (0);
590   }
592   now = cdtime ();
594   if (datadir == NULL)
595     snprintf (key, sizeof (key), "%s.rrd",
596         identifier);
597   else
598     snprintf (key, sizeof (key), "%s/%s.rrd",
599         datadir, identifier);
600   key[sizeof (key) - 1] = 0;
602   status = c_avl_get (cache, key, (void *) &rc);
603   if (status != 0)
604   {
605     INFO ("rrdtool plugin: rrd_cache_flush_identifier: "
606         "c_avl_get (%s) failed. Does that file really exist?",
607         key);
608     return (status);
609   }
611   if (rc->flags == FLAG_FLUSHQ)
612   {
613     status = 0;
614   }
615   else if (rc->flags == FLAG_QUEUED)
616   {
617     rrd_queue_dequeue (key, &queue_head, &queue_tail);
618     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
619     if (status == 0)
620       rc->flags = FLAG_FLUSHQ;
621   }
622   else if ((now - rc->first_value) < timeout)
623   {
624     status = 0;
625   }
626   else if (rc->values_num > 0)
627   {
628     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
629     if (status == 0)
630       rc->flags = FLAG_FLUSHQ;
631   }
633   return (status);
634 } /* int rrd_cache_flush_identifier */
636 static int64_t rrd_get_random_variation (void)
638   long min;
639   long max;
641   if (random_timeout <= 0)
642     return (0);
644   /* Assure that "cache_timeout + random_variation" is never negative. */
645   if (random_timeout > cache_timeout)
646   {
647           INFO ("rrdtool plugin: Adjusting \"RandomTimeout\" to %.3f seconds.",
648                           CDTIME_T_TO_DOUBLE (cache_timeout));
649           random_timeout = cache_timeout;
650   }
652   max = (long) (random_timeout / 2);
653   min = max - ((long) random_timeout);
655   return ((int64_t) cdrand_range (min, max));
656 } /* int64_t rrd_get_random_variation */
658 static int rrd_cache_insert (const char *filename,
659                 const char *value, cdtime_t value_time)
661         rrd_cache_t *rc = NULL;
662         int new_rc = 0;
663         char **values_new;
665         pthread_mutex_lock (&cache_lock);
667         /* This shouldn't happen, but it did happen at least once, so we'll be
668          * careful. */
669         if (cache == NULL)
670         {
671                 pthread_mutex_unlock (&cache_lock);
672                 WARNING ("rrdtool plugin: cache == NULL.");
673                 return (-1);
674         }
676         c_avl_get (cache, filename, (void *) &rc);
678         if (rc == NULL)
679         {
680                 rc = malloc (sizeof (*rc));
681                 if (rc == NULL)
682                         return (-1);
683                 rc->values_num = 0;
684                 rc->values = NULL;
685                 rc->first_value = 0;
686                 rc->last_value = 0;
687                 rc->random_variation = rrd_get_random_variation ();
688                 rc->flags = FLAG_NONE;
689                 new_rc = 1;
690         }
692         if (rc->last_value >= value_time)
693         {
694                 pthread_mutex_unlock (&cache_lock);
695                 DEBUG ("rrdtool plugin: (rc->last_value = %"PRIu64") "
696                                 ">= (value_time = %"PRIu64")",
697                                 rc->last_value, value_time);
698                 return (-1);
699         }
701         values_new = (char **) realloc ((void *) rc->values,
702                         (rc->values_num + 1) * sizeof (char *));
703         if (values_new == NULL)
704         {
705                 char errbuf[1024];
706                 void *cache_key = NULL;
708                 sstrerror (errno, errbuf, sizeof (errbuf));
710                 c_avl_remove (cache, filename, &cache_key, NULL);
711                 pthread_mutex_unlock (&cache_lock);
713                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
715                 sfree (cache_key);
716                 sfree (rc->values);
717                 sfree (rc);
718                 return (-1);
719         }
720         rc->values = values_new;
722         rc->values[rc->values_num] = strdup (value);
723         if (rc->values[rc->values_num] != NULL)
724                 rc->values_num++;
726         if (rc->values_num == 1)
727                 rc->first_value = value_time;
728         rc->last_value = value_time;
730         /* Insert if this is the first value */
731         if (new_rc == 1)
732         {
733                 void *cache_key = strdup (filename);
735                 if (cache_key == NULL)
736                 {
737                         char errbuf[1024];
738                         sstrerror (errno, errbuf, sizeof (errbuf));
740                         pthread_mutex_unlock (&cache_lock);
742                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
744                         sfree (rc->values[0]);
745                         sfree (rc->values);
746                         sfree (rc);
747                         return (-1);
748                 }
750                 c_avl_insert (cache, cache_key, rc);
751         }
753         DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
754                         "values_num = %i; age = %.3f;",
755                         filename, rc->values_num,
756                         CDTIME_T_TO_DOUBLE (rc->last_value - rc->first_value));
758         if ((rc->last_value - rc->first_value) >= (cache_timeout + rc->random_variation))
759         {
760                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
761                  * the same time, ALWAYS lock `cache_lock' first! */
762                 if (rc->flags == FLAG_NONE)
763                 {
764                         int status;
766                         status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
767                         if (status == 0)
768                                 rc->flags = FLAG_QUEUED;
770                         rc->random_variation = rrd_get_random_variation ();
771                 }
772                 else
773                 {
774                         DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
775                 }
776         }
778         if ((cache_timeout > 0) &&
779                         ((cdtime () - cache_flush_last) > cache_flush_timeout))
780                 rrd_cache_flush (cache_flush_timeout);
782         pthread_mutex_unlock (&cache_lock);
784         return (0);
785 } /* int rrd_cache_insert */
787 static int rrd_cache_destroy (void) /* {{{ */
789   void *key = NULL;
790   void *value = NULL;
792   int non_empty = 0;
794   pthread_mutex_lock (&cache_lock);
796   if (cache == NULL)
797   {
798     pthread_mutex_unlock (&cache_lock);
799     return (0);
800   }
802   while (c_avl_pick (cache, &key, &value) == 0)
803   {
804     rrd_cache_t *rc;
805     int i;
807     sfree (key);
808     key = NULL;
810     rc = value;
811     value = NULL;
813     if (rc->values_num > 0)
814       non_empty++;
816     for (i = 0; i < rc->values_num; i++)
817       sfree (rc->values[i]);
818     sfree (rc->values);
819     sfree (rc);
820   }
822   c_avl_destroy (cache);
823   cache = NULL;
825   if (non_empty > 0)
826   {
827     INFO ("rrdtool plugin: %i cache %s had values when destroying the cache.",
828         non_empty, (non_empty == 1) ? "entry" : "entries");
829   }
830   else
831   {
832     DEBUG ("rrdtool plugin: No values have been lost "
833         "when destroying the cache.");
834   }
836   pthread_mutex_unlock (&cache_lock);
837   return (0);
838 } /* }}} int rrd_cache_destroy */
840 static int rrd_compare_numeric (const void *a_ptr, const void *b_ptr)
842         int a = *((int *) a_ptr);
843         int b = *((int *) b_ptr);
845         if (a < b)
846                 return (-1);
847         else if (a > b)
848                 return (1);
849         else
850                 return (0);
851 } /* int rrd_compare_numeric */
853 static int rrd_write (const data_set_t *ds, const value_list_t *vl,
854                 user_data_t __attribute__((unused)) *user_data)
856         struct stat  statbuf;
857         char         filename[512];
858         char         values[512];
859         int          status;
861         if (do_shutdown)
862                 return (0);
864         if (0 != strcmp (ds->type, vl->type)) {
865                 ERROR ("rrdtool plugin: DS type does not match value list type");
866                 return -1;
867         }
869         if (value_list_to_filename (filename, sizeof (filename), vl) != 0)
870                 return (-1);
872         if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
873                 return (-1);
875         if (stat (filename, &statbuf) == -1)
876         {
877                 if (errno == ENOENT)
878                 {
879                         status = cu_rrd_create_file (filename,
880                                         ds, vl, &rrdcreate_config);
881                         if (status != 0)
882                                 return (-1);
883                         else if (rrdcreate_config.async)
884                                 return (0);
885                 }
886                 else
887                 {
888                         char errbuf[1024];
889                         ERROR ("stat(%s) failed: %s", filename,
890                                         sstrerror (errno, errbuf,
891                                                 sizeof (errbuf)));
892                         return (-1);
893                 }
894         }
895         else if (!S_ISREG (statbuf.st_mode))
896         {
897                 ERROR ("stat(%s): Not a regular file!",
898                                 filename);
899                 return (-1);
900         }
902         status = rrd_cache_insert (filename, values, vl->time);
904         return (status);
905 } /* int rrd_write */
907 static int rrd_flush (cdtime_t timeout, const char *identifier,
908                 __attribute__((unused)) user_data_t *user_data)
910         pthread_mutex_lock (&cache_lock);
912         if (cache == NULL) {
913                 pthread_mutex_unlock (&cache_lock);
914                 return (0);
915         }
917         rrd_cache_flush_identifier (timeout, identifier);
919         pthread_mutex_unlock (&cache_lock);
920         return (0);
921 } /* int rrd_flush */
923 static int rrd_config (const char *key, const char *value)
925         if (strcasecmp ("CacheTimeout", key) == 0)
926         {
927                 double tmp = atof (value);
928                 if (tmp < 0)
929                 {
930                         fprintf (stderr, "rrdtool: `CacheTimeout' must "
931                                         "be greater than 0.\n");
932                         ERROR ("rrdtool: `CacheTimeout' must "
933                                         "be greater than 0.\n");
934                         return (1);
935                 }
936                 cache_timeout = DOUBLE_TO_CDTIME_T (tmp);
937         }
938         else if (strcasecmp ("CacheFlush", key) == 0)
939         {
940                 int tmp = atoi (value);
941                 if (tmp < 0)
942                 {
943                         fprintf (stderr, "rrdtool: `CacheFlush' must "
944                                         "be greater than 0.\n");
945                         ERROR ("rrdtool: `CacheFlush' must "
946                                         "be greater than 0.\n");
947                         return (1);
948                 }
949                 cache_flush_timeout = tmp;
950         }
951         else if (strcasecmp ("DataDir", key) == 0)
952         {
953                 if (datadir != NULL)
954                         free (datadir);
955                 datadir = strdup (value);
956                 if (datadir != NULL)
957                 {
958                         int len = strlen (datadir);
959                         while ((len > 0) && (datadir[len - 1] == '/'))
960                         {
961                                 len--;
962                                 datadir[len] = '\0';
963                         }
964                         if (len <= 0)
965                         {
966                                 free (datadir);
967                                 datadir = NULL;
968                         }
969                 }
970         }
971         else if (strcasecmp ("StepSize", key) == 0)
972         {
973                 unsigned long temp = strtoul (value, NULL, 0);
974                 if (temp > 0)
975                         rrdcreate_config.stepsize = temp;
976         }
977         else if (strcasecmp ("HeartBeat", key) == 0)
978         {
979                 int temp = atoi (value);
980                 if (temp > 0)
981                         rrdcreate_config.heartbeat = temp;
982         }
983         else if (strcasecmp ("CreateFilesAsync", key) == 0)
984         {
985                 if (IS_TRUE (value))
986                         rrdcreate_config.async = 1;
987                 else
988                         rrdcreate_config.async = 0;
989         }
990         else if (strcasecmp ("RRARows", key) == 0)
991         {
992                 int tmp = atoi (value);
993                 if (tmp <= 0)
994                 {
995                         fprintf (stderr, "rrdtool: `RRARows' must "
996                                         "be greater than 0.\n");
997                         ERROR ("rrdtool: `RRARows' must "
998                                         "be greater than 0.\n");
999                         return (1);
1000                 }
1001                 rrdcreate_config.rrarows = tmp;
1002         }
1003         else if (strcasecmp ("RRATimespan", key) == 0)
1004         {
1005                 char *saveptr = NULL;
1006                 char *dummy;
1007                 char *ptr;
1008                 char *value_copy;
1009                 int *tmp_alloc;
1011                 value_copy = strdup (value);
1012                 if (value_copy == NULL)
1013                         return (1);
1015                 dummy = value_copy;
1016                 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
1017                 {
1018                         dummy = NULL;
1019                         
1020                         tmp_alloc = realloc (rrdcreate_config.timespans,
1021                                         sizeof (int) * (rrdcreate_config.timespans_num + 1));
1022                         if (tmp_alloc == NULL)
1023                         {
1024                                 fprintf (stderr, "rrdtool: realloc failed.\n");
1025                                 ERROR ("rrdtool: realloc failed.\n");
1026                                 free (value_copy);
1027                                 return (1);
1028                         }
1029                         rrdcreate_config.timespans = tmp_alloc;
1030                         rrdcreate_config.timespans[rrdcreate_config.timespans_num] = atoi (ptr);
1031                         if (rrdcreate_config.timespans[rrdcreate_config.timespans_num] != 0)
1032                                 rrdcreate_config.timespans_num++;
1033                 } /* while (strtok_r) */
1035                 qsort (/* base = */ rrdcreate_config.timespans,
1036                                 /* nmemb  = */ rrdcreate_config.timespans_num,
1037                                 /* size   = */ sizeof (rrdcreate_config.timespans[0]),
1038                                 /* compar = */ rrd_compare_numeric);
1040                 free (value_copy);
1041         }
1042         else if (strcasecmp ("XFF", key) == 0)
1043         {
1044                 double tmp = atof (value);
1045                 if ((tmp < 0.0) || (tmp >= 1.0))
1046                 {
1047                         fprintf (stderr, "rrdtool: `XFF' must "
1048                                         "be in the range 0 to 1 (exclusive).");
1049                         ERROR ("rrdtool: `XFF' must "
1050                                         "be in the range 0 to 1 (exclusive).");
1051                         return (1);
1052                 }
1053                 rrdcreate_config.xff = tmp;
1054         }
1055         else if (strcasecmp ("WritesPerSecond", key) == 0)
1056         {
1057                 double wps = atof (value);
1059                 if (wps < 0.0)
1060                 {
1061                         fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
1062                                         "greater than or equal to zero.");
1063                         return (1);
1064                 }
1065                 else if (wps == 0.0)
1066                 {
1067                         write_rate = 0.0;
1068                 }
1069                 else
1070                 {
1071                         write_rate = 1.0 / wps;
1072                 }
1073         }
1074         else if (strcasecmp ("RandomTimeout", key) == 0)
1075         {
1076                 double tmp;
1078                 tmp = atof (value);
1079                 if (tmp < 0.0)
1080                 {
1081                         fprintf (stderr, "rrdtool: `RandomTimeout' must "
1082                                         "be greater than or equal to zero.\n");
1083                         ERROR ("rrdtool: `RandomTimeout' must "
1084                                         "be greater then or equal to zero.");
1085                 }
1086                 else
1087                 {
1088                         random_timeout = DOUBLE_TO_CDTIME_T (tmp);
1089                 }
1090         }
1091         else
1092         {
1093                 return (-1);
1094         }
1095         return (0);
1096 } /* int rrd_config */
1098 static int rrd_shutdown (void)
1100         pthread_mutex_lock (&cache_lock);
1101         rrd_cache_flush (0);
1102         pthread_mutex_unlock (&cache_lock);
1104         pthread_mutex_lock (&queue_lock);
1105         do_shutdown = 1;
1106         pthread_cond_signal (&queue_cond);
1107         pthread_mutex_unlock (&queue_lock);
1109         if ((queue_thread_running != 0)
1110                         && ((queue_head != NULL) || (flushq_head != NULL)))
1111         {
1112                 INFO ("rrdtool plugin: Shutting down the queue thread. "
1113                                 "This may take a while.");
1114         }
1115         else if (queue_thread_running != 0)
1116         {
1117                 INFO ("rrdtool plugin: Shutting down the queue thread.");
1118         }
1120         /* Wait for all the values to be written to disk before returning. */
1121         if (queue_thread_running != 0)
1122         {
1123                 pthread_join (queue_thread, NULL);
1124                 memset (&queue_thread, 0, sizeof (queue_thread));
1125                 queue_thread_running = 0;
1126                 DEBUG ("rrdtool plugin: queue_thread exited.");
1127         }
1129         rrd_cache_destroy ();
1131         return (0);
1132 } /* int rrd_shutdown */
1134 static int rrd_init (void)
1136         static int init_once = 0;
1137         int status;
1139         if (init_once != 0)
1140                 return (0);
1141         init_once = 1;
1143         if (rrdcreate_config.heartbeat <= 0)
1144                 rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
1146         /* Set the cache up */
1147         pthread_mutex_lock (&cache_lock);
1149         cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1150         if (cache == NULL)
1151         {
1152                 ERROR ("rrdtool plugin: c_avl_create failed.");
1153                 return (-1);
1154         }
1156         cache_flush_last = cdtime ();
1157         if (cache_timeout == 0)
1158         {
1159                 cache_flush_timeout = 0;
1160         }
1161         else if (cache_flush_timeout < cache_timeout)
1162                 cache_flush_timeout = 10 * cache_timeout;
1164         pthread_mutex_unlock (&cache_lock);
1166         status = plugin_thread_create (&queue_thread, /* attr = */ NULL,
1167                         rrd_queue_thread, /* args = */ NULL);
1168         if (status != 0)
1169         {
1170                 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1171                 return (-1);
1172         }
1173         queue_thread_running = 1;
1175         DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %lu;"
1176                         " heartbeat = %i; rrarows = %i; xff = %lf;",
1177                         (datadir == NULL) ? "(null)" : datadir,
1178                         rrdcreate_config.stepsize,
1179                         rrdcreate_config.heartbeat,
1180                         rrdcreate_config.rrarows,
1181                         rrdcreate_config.xff);
1183         return (0);
1184 } /* int rrd_init */
1186 void module_register (void)
1188         plugin_register_config ("rrdtool", rrd_config,
1189                         config_keys, config_keys_num);
1190         plugin_register_init ("rrdtool", rrd_init);
1191         plugin_register_write ("rrdtool", rrd_write, /* user_data = */ NULL);
1192         plugin_register_flush ("rrdtool", rrd_flush, /* user_data = */ NULL);
1193         plugin_register_shutdown ("rrdtool", rrd_shutdown);