Merge pull request #1611 from stefanth/Collection3/graph-rendering-speedup
[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  **/
25
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"
32
33 #include <rrd.h>
34
35 #if HAVE_PTHREAD_H
36 # include <pthread.h>
37 #endif
38
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;
57
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;
64
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;
71
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);
90
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,
102
103         /* timespans = */ NULL,
104         /* timespans_num = */ 0,
105
106         /* consolidation_functions = */ NULL,
107         /* consolidation_functions_num = */ 0,
108
109         /* async = */ 0
110 };
111
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;
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;
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;
129
130 #if !HAVE_THREADSAFE_LIBRRD
131 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
132 #endif
133
134 static int do_shutdown = 0;
135
136 #if HAVE_THREADSAFE_LIBRRD
137 static int srrd_update (char *filename, char *template,
138                 int argc, const char **argv)
139 {
140         int status;
141
142         optind = 0; /* bug in librrd? */
143         rrd_clear_error ();
144
145         status = rrd_update_r (filename, template, argc, (void *) argv);
146
147         if (status != 0)
148         {
149                 WARNING ("rrdtool plugin: rrd_update_r (%s) failed: %s",
150                                 filename, rrd_get_error ());
151         }
152
153         return (status);
154 } /* int srrd_update */
155 /* #endif HAVE_THREADSAFE_LIBRRD */
156
157 #else /* !HAVE_THREADSAFE_LIBRRD */
158 static int srrd_update (char *filename, char *template,
159                 int argc, const char **argv)
160 {
161         int status;
162
163         int new_argc;
164         char **new_argv;
165
166         assert (template == NULL);
167
168         new_argc = 2 + argc;
169         new_argv = malloc ((new_argc + 1) * sizeof (*new_argv));
170         if (new_argv == NULL)
171         {
172                 ERROR ("rrdtool plugin: malloc failed.");
173                 return (-1);
174         }
175
176         new_argv[0] = "update";
177         new_argv[1] = filename;
178
179         memcpy (new_argv + 2, argv, argc * sizeof (char *));
180         new_argv[new_argc] = NULL;
181
182         pthread_mutex_lock (&librrd_lock);
183         optind = 0; /* bug in librrd? */
184         rrd_clear_error ();
185
186         status = rrd_update (new_argc, new_argv);
187         pthread_mutex_unlock (&librrd_lock);
188
189         if (status != 0)
190         {
191                 WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
192                                 filename, rrd_get_error ());
193         }
194
195         sfree (new_argv);
196
197         return (status);
198 } /* int srrd_update */
199 #endif /* !HAVE_THREADSAFE_LIBRRD */
200
201 static int value_list_to_string_multiple (char *buffer, int buffer_len,
202                 const data_set_t *ds, const value_list_t *vl)
203 {
204         int offset;
205         int status;
206         time_t tt;
207         size_t i;
208
209         memset (buffer, '\0', buffer_len);
210
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;
216
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);
224
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                                         ":"GAUGE_FORMAT, 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);
237
238                 if ((status < 1) || (status >= (buffer_len - offset)))
239                         return (-1);
240
241                 offset += status;
242         } /* for ds->ds_num */
243
244         return (0);
245 } /* int value_list_to_string_multiple */
246
247 static int value_list_to_string (char *buffer, int buffer_len,
248                 const data_set_t *ds, const value_list_t *vl)
249 {
250         int status;
251         time_t tt;
252
253         if (ds->ds_num != 1)
254                 return (value_list_to_string_multiple (buffer, buffer_len,
255                                         ds, vl));
256
257         tt = CDTIME_T_TO_TIME_T (vl->time);
258         switch (ds->ds[0].type)
259         {
260                 case DS_TYPE_DERIVE:
261                         status = ssnprintf (buffer, buffer_len, "%u:%"PRIi64,
262                                 (unsigned) tt, vl->values[0].derive);
263                         break;
264                 case DS_TYPE_GAUGE:
265                         status = ssnprintf (buffer, buffer_len, "%u:"GAUGE_FORMAT,
266                                 (unsigned) tt, vl->values[0].gauge);
267                         break;
268                 case DS_TYPE_COUNTER:
269                         status = ssnprintf (buffer, buffer_len, "%u:%llu",
270                                 (unsigned) tt, vl->values[0].counter);
271                         break;
272                 case DS_TYPE_ABSOLUTE:
273                         status = ssnprintf (buffer, buffer_len, "%u:%"PRIu64,
274                                 (unsigned) tt, vl->values[0].absolute);
275                         break;
276                 default:
277                         return (EINVAL);
278         }
279
280         if ((status < 1) || (status >= buffer_len))
281                 return (ENOMEM);
282
283         return (0);
284 } /* int value_list_to_string */
285
286 static int value_list_to_filename (char *buffer, size_t buffer_size,
287                 value_list_t const *vl)
288 {
289         char const suffix[] = ".rrd";
290         int status;
291         size_t len;
292
293         if (datadir != NULL)
294         {
295                 size_t datadir_len = strlen (datadir) + 1;
296
297                 if (datadir_len >= buffer_size)
298                         return (ENOMEM);
299
300                 sstrncpy (buffer, datadir, buffer_size);
301                 buffer[datadir_len - 1] = '/';
302                 buffer[datadir_len] = 0;
303
304                 buffer += datadir_len;
305                 buffer_size -= datadir_len;
306         }
307
308         status = FORMAT_VL (buffer, buffer_size, vl);
309         if (status != 0)
310                 return (status);
311
312         len = strlen (buffer);
313         assert (len < buffer_size);
314         buffer += len;
315         buffer_size -= len;
316
317         if (buffer_size <= sizeof (suffix))
318                 return (ENOMEM);
319
320         memcpy (buffer, suffix, sizeof (suffix));
321         return (0);
322 } /* int value_list_to_filename */
323
324 static void *rrd_queue_thread (void __attribute__((unused)) *data)
325 {
326         struct timeval tv_next_update;
327         struct timeval tv_now;
328
329         gettimeofday (&tv_next_update, /* timezone = */ NULL);
330
331         while (42)
332         {
333                 rrd_queue_t *queue_entry;
334                 rrd_cache_t *cache_entry;
335                 char **values;
336                 int    values_num;
337                 int    status;
338                 int    i;
339
340                 values = NULL;
341                 values_num = 0;
342
343                 pthread_mutex_lock (&queue_lock);
344                 /* Wait for values to arrive */
345                 while (42)
346                 {
347                   struct timespec ts_wait;
348
349                   while ((flushq_head == NULL) && (queue_head == NULL)
350                       && (do_shutdown == 0))
351                     pthread_cond_wait (&queue_cond, &queue_lock);
352
353                   if ((flushq_head == NULL) && (queue_head == NULL))
354                     break;
355
356                   /* Don't delay if there's something to flush */
357                   if (flushq_head != NULL)
358                     break;
359
360                   /* Don't delay if we're shutting down */
361                   if (do_shutdown != 0)
362                     break;
363
364                   /* Don't delay if no delay was configured. */
365                   if (write_rate <= 0.0)
366                     break;
367
368                   gettimeofday (&tv_now, /* timezone = */ NULL);
369                   status = timeval_cmp (tv_next_update, tv_now, NULL);
370                   /* We're good to go */
371                   if (status <= 0)
372                     break;
373
374                   /* We're supposed to wait a bit with this update, so we'll
375                    * wait for the next addition to the queue or to the end of
376                    * the wait period - whichever comes first. */
377                   ts_wait.tv_sec = tv_next_update.tv_sec;
378                   ts_wait.tv_nsec = 1000 * tv_next_update.tv_usec;
379
380                   status = pthread_cond_timedwait (&queue_cond, &queue_lock,
381                       &ts_wait);
382                   if (status == ETIMEDOUT)
383                     break;
384                 } /* while (42) */
385
386                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
387                  * the same time, ALWAYS lock `cache_lock' first! */
388
389                 /* We're in the shutdown phase */
390                 if ((flushq_head == NULL) && (queue_head == NULL))
391                 {
392                   pthread_mutex_unlock (&queue_lock);
393                   break;
394                 }
395
396                 if (flushq_head != NULL)
397                 {
398                   /* Dequeue the first flush entry */
399                   queue_entry = flushq_head;
400                   if (flushq_head == flushq_tail)
401                     flushq_head = flushq_tail = NULL;
402                   else
403                     flushq_head = flushq_head->next;
404                 }
405                 else /* if (queue_head != NULL) */
406                 {
407                   /* Dequeue the first regular entry */
408                   queue_entry = queue_head;
409                   if (queue_head == queue_tail)
410                     queue_head = queue_tail = NULL;
411                   else
412                     queue_head = queue_head->next;
413                 }
414
415                 /* Unlock the queue again */
416                 pthread_mutex_unlock (&queue_lock);
417
418                 /* We now need the cache lock so the entry isn't updated while
419                  * we make a copy of it's values */
420                 pthread_mutex_lock (&cache_lock);
421
422                 status = c_avl_get (cache, queue_entry->filename,
423                                 (void *) &cache_entry);
424
425                 if (status == 0)
426                 {
427                         values = cache_entry->values;
428                         values_num = cache_entry->values_num;
429
430                         cache_entry->values = NULL;
431                         cache_entry->values_num = 0;
432                         cache_entry->flags = FLAG_NONE;
433                 }
434
435                 pthread_mutex_unlock (&cache_lock);
436
437                 if (status != 0)
438                 {
439                         sfree (queue_entry->filename);
440                         sfree (queue_entry);
441                         continue;
442                 }
443
444                 /* Update `tv_next_update' */
445                 if (write_rate > 0.0)
446                 {
447                   gettimeofday (&tv_now, /* timezone = */ NULL);
448                   tv_next_update.tv_sec = tv_now.tv_sec;
449                   tv_next_update.tv_usec = tv_now.tv_usec
450                     + ((suseconds_t) (1000000 * write_rate));
451                   while (tv_next_update.tv_usec > 1000000)
452                   {
453                     tv_next_update.tv_sec++;
454                     tv_next_update.tv_usec -= 1000000;
455                   }
456                 }
457
458                 /* Write the values to the RRD-file */
459                 srrd_update (queue_entry->filename, NULL,
460                                 values_num, (const char **)values);
461                 DEBUG ("rrdtool plugin: queue thread: Wrote %i value%s to %s",
462                                 values_num, (values_num == 1) ? "" : "s",
463                                 queue_entry->filename);
464
465                 for (i = 0; i < values_num; i++)
466                 {
467                         sfree (values[i]);
468                 }
469                 sfree (values);
470                 sfree (queue_entry->filename);
471                 sfree (queue_entry);
472         } /* while (42) */
473
474         pthread_exit ((void *) 0);
475         return ((void *) 0);
476 } /* void *rrd_queue_thread */
477
478 static int rrd_queue_enqueue (const char *filename,
479     rrd_queue_t **head, rrd_queue_t **tail)
480 {
481   rrd_queue_t *queue_entry;
482
483   queue_entry = malloc (sizeof (*queue_entry));
484   if (queue_entry == NULL)
485     return (-1);
486
487   queue_entry->filename = strdup (filename);
488   if (queue_entry->filename == NULL)
489   {
490     free (queue_entry);
491     return (-1);
492   }
493
494   queue_entry->next = NULL;
495
496   pthread_mutex_lock (&queue_lock);
497
498   if (*tail == NULL)
499     *head = queue_entry;
500   else
501     (*tail)->next = queue_entry;
502   *tail = queue_entry;
503
504   pthread_cond_signal (&queue_cond);
505   pthread_mutex_unlock (&queue_lock);
506
507   return (0);
508 } /* int rrd_queue_enqueue */
509
510 static int rrd_queue_dequeue (const char *filename,
511     rrd_queue_t **head, rrd_queue_t **tail)
512 {
513   rrd_queue_t *this;
514   rrd_queue_t *prev;
515
516   pthread_mutex_lock (&queue_lock);
517
518   prev = NULL;
519   this = *head;
520
521   while (this != NULL)
522   {
523     if (strcmp (this->filename, filename) == 0)
524       break;
525
526     prev = this;
527     this = this->next;
528   }
529
530   if (this == NULL)
531   {
532     pthread_mutex_unlock (&queue_lock);
533     return (-1);
534   }
535
536   if (prev == NULL)
537     *head = this->next;
538   else
539     prev->next = this->next;
540
541   if (this->next == NULL)
542     *tail = prev;
543
544   pthread_mutex_unlock (&queue_lock);
545
546   sfree (this->filename);
547   sfree (this);
548
549   return (0);
550 } /* int rrd_queue_dequeue */
551
552 /* XXX: You must hold "cache_lock" when calling this function! */
553 static void rrd_cache_flush (cdtime_t timeout)
554 {
555         rrd_cache_t *rc;
556         cdtime_t     now;
557
558         char **keys = NULL;
559         int    keys_num = 0;
560
561         char *key;
562         c_avl_iterator_t *iter;
563         int i;
564
565         DEBUG ("rrdtool plugin: Flushing cache, timeout = %.3f",
566                         CDTIME_T_TO_DOUBLE (timeout));
567
568         now = cdtime ();
569         timeout = TIME_T_TO_CDTIME_T (timeout);
570
571         /* Build a list of entries to be flushed */
572         iter = c_avl_get_iterator (cache);
573         while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
574         {
575                 if (rc->flags != FLAG_NONE)
576                         continue;
577                 /* timeout == 0  =>  flush everything */
578                 else if ((timeout != 0)
579                                 && ((now - rc->first_value) < timeout))
580                         continue;
581                 else if (rc->values_num > 0)
582                 {
583                         int status;
584
585                         status = rrd_queue_enqueue (key, &queue_head,  &queue_tail);
586                         if (status == 0)
587                                 rc->flags = FLAG_QUEUED;
588                 }
589                 else /* ancient and no values -> waste of memory */
590                 {
591                         char **tmp = (char **) realloc ((void *) keys,
592                                         (keys_num + 1) * sizeof (char *));
593                         if (tmp == NULL)
594                         {
595                                 char errbuf[1024];
596                                 ERROR ("rrdtool plugin: "
597                                                 "realloc failed: %s",
598                                                 sstrerror (errno, errbuf,
599                                                         sizeof (errbuf)));
600                                 c_avl_iterator_destroy (iter);
601                                 sfree (keys);
602                                 return;
603                         }
604                         keys = tmp;
605                         keys[keys_num] = key;
606                         keys_num++;
607                 }
608         } /* while (c_avl_iterator_next) */
609         c_avl_iterator_destroy (iter);
610
611         for (i = 0; i < keys_num; i++)
612         {
613                 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
614                 {
615                         DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
616                         continue;
617                 }
618
619                 assert (rc->values == NULL);
620                 assert (rc->values_num == 0);
621
622                 sfree (rc);
623                 sfree (key);
624                 keys[i] = NULL;
625         } /* for (i = 0..keys_num) */
626
627         sfree (keys);
628
629         cache_flush_last = now;
630 } /* void rrd_cache_flush */
631
632 static int rrd_cache_flush_identifier (cdtime_t timeout,
633     const char *identifier)
634 {
635   rrd_cache_t *rc;
636   cdtime_t now;
637   int status;
638   char key[2048];
639
640   if (identifier == NULL)
641   {
642     rrd_cache_flush (timeout);
643     return (0);
644   }
645
646   now = cdtime ();
647
648   if (datadir == NULL)
649     snprintf (key, sizeof (key), "%s.rrd",
650         identifier);
651   else
652     snprintf (key, sizeof (key), "%s/%s.rrd",
653         datadir, identifier);
654   key[sizeof (key) - 1] = 0;
655
656   status = c_avl_get (cache, key, (void *) &rc);
657   if (status != 0)
658   {
659     INFO ("rrdtool plugin: rrd_cache_flush_identifier: "
660         "c_avl_get (%s) failed. Does that file really exist?",
661         key);
662     return (status);
663   }
664
665   if (rc->flags == FLAG_FLUSHQ)
666   {
667     status = 0;
668   }
669   else if (rc->flags == FLAG_QUEUED)
670   {
671     rrd_queue_dequeue (key, &queue_head, &queue_tail);
672     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
673     if (status == 0)
674       rc->flags = FLAG_FLUSHQ;
675   }
676   else if ((now - rc->first_value) < timeout)
677   {
678     status = 0;
679   }
680   else if (rc->values_num > 0)
681   {
682     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
683     if (status == 0)
684       rc->flags = FLAG_FLUSHQ;
685   }
686
687   return (status);
688 } /* int rrd_cache_flush_identifier */
689
690 static int64_t rrd_get_random_variation (void)
691 {
692   long min;
693   long max;
694
695   if (random_timeout <= 0)
696     return (0);
697
698   /* Assure that "cache_timeout + random_variation" is never negative. */
699   if (random_timeout > cache_timeout)
700   {
701           INFO ("rrdtool plugin: Adjusting \"RandomTimeout\" to %.3f seconds.",
702                           CDTIME_T_TO_DOUBLE (cache_timeout));
703           random_timeout = cache_timeout;
704   }
705
706   max = (long) (random_timeout / 2);
707   min = max - ((long) random_timeout);
708
709   return ((int64_t) cdrand_range (min, max));
710 } /* int64_t rrd_get_random_variation */
711
712 static int rrd_cache_insert (const char *filename,
713                 const char *value, cdtime_t value_time)
714 {
715         rrd_cache_t *rc = NULL;
716         int new_rc = 0;
717         char **values_new;
718
719         pthread_mutex_lock (&cache_lock);
720
721         /* This shouldn't happen, but it did happen at least once, so we'll be
722          * careful. */
723         if (cache == NULL)
724         {
725                 pthread_mutex_unlock (&cache_lock);
726                 WARNING ("rrdtool plugin: cache == NULL.");
727                 return (-1);
728         }
729
730         c_avl_get (cache, filename, (void *) &rc);
731
732         if (rc == NULL)
733         {
734                 rc = malloc (sizeof (*rc));
735                 if (rc == NULL)
736                 {
737                         pthread_mutex_unlock (&cache_lock);
738                         return (-1);
739                 }
740                 rc->values_num = 0;
741                 rc->values = NULL;
742                 rc->first_value = 0;
743                 rc->last_value = 0;
744                 rc->random_variation = rrd_get_random_variation ();
745                 rc->flags = FLAG_NONE;
746                 new_rc = 1;
747         }
748
749         assert (value_time > 0); /* plugin_dispatch() ensures this. */
750         if (rc->last_value >= value_time)
751         {
752                 pthread_mutex_unlock (&cache_lock);
753                 DEBUG ("rrdtool plugin: (rc->last_value = %"PRIu64") "
754                                 ">= (value_time = %"PRIu64")",
755                                 rc->last_value, value_time);
756                 return (-1);
757         }
758
759         values_new = (char **) realloc ((void *) rc->values,
760                         (rc->values_num + 1) * sizeof (char *));
761         if (values_new == NULL)
762         {
763                 char errbuf[1024];
764                 void *cache_key = NULL;
765
766                 sstrerror (errno, errbuf, sizeof (errbuf));
767
768                 c_avl_remove (cache, filename, &cache_key, NULL);
769                 pthread_mutex_unlock (&cache_lock);
770
771                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
772
773                 sfree (cache_key);
774                 sfree (rc->values);
775                 sfree (rc);
776                 return (-1);
777         }
778         rc->values = values_new;
779
780         rc->values[rc->values_num] = strdup (value);
781         if (rc->values[rc->values_num] != NULL)
782                 rc->values_num++;
783
784         if (rc->values_num == 1)
785                 rc->first_value = value_time;
786         rc->last_value = value_time;
787
788         /* Insert if this is the first value */
789         if (new_rc == 1)
790         {
791                 void *cache_key = strdup (filename);
792
793                 if (cache_key == NULL)
794                 {
795                         char errbuf[1024];
796                         sstrerror (errno, errbuf, sizeof (errbuf));
797
798                         pthread_mutex_unlock (&cache_lock);
799
800                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
801
802                         sfree (rc->values[0]);
803                         sfree (rc->values);
804                         sfree (rc);
805                         return (-1);
806                 }
807
808                 c_avl_insert (cache, cache_key, rc);
809         }
810
811         DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
812                         "values_num = %i; age = %.3f;",
813                         filename, rc->values_num,
814                         CDTIME_T_TO_DOUBLE (rc->last_value - rc->first_value));
815
816         if ((rc->last_value - rc->first_value) >= (cache_timeout + rc->random_variation))
817         {
818                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
819                  * the same time, ALWAYS lock `cache_lock' first! */
820                 if (rc->flags == FLAG_NONE)
821                 {
822                         int status;
823
824                         status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
825                         if (status == 0)
826                                 rc->flags = FLAG_QUEUED;
827
828                         rc->random_variation = rrd_get_random_variation ();
829                 }
830                 else
831                 {
832                         DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
833                 }
834         }
835
836         if ((cache_timeout > 0) &&
837                         ((cdtime () - cache_flush_last) > cache_flush_timeout))
838                 rrd_cache_flush (cache_flush_timeout);
839
840         pthread_mutex_unlock (&cache_lock);
841
842         return (0);
843 } /* int rrd_cache_insert */
844
845 static int rrd_cache_destroy (void) /* {{{ */
846 {
847   void *key = NULL;
848   void *value = NULL;
849
850   int non_empty = 0;
851
852   pthread_mutex_lock (&cache_lock);
853
854   if (cache == NULL)
855   {
856     pthread_mutex_unlock (&cache_lock);
857     return (0);
858   }
859
860   while (c_avl_pick (cache, &key, &value) == 0)
861   {
862     rrd_cache_t *rc;
863     int i;
864
865     sfree (key);
866     key = NULL;
867
868     rc = value;
869     value = NULL;
870
871     if (rc->values_num > 0)
872       non_empty++;
873
874     for (i = 0; i < rc->values_num; i++)
875       sfree (rc->values[i]);
876     sfree (rc->values);
877     sfree (rc);
878   }
879
880   c_avl_destroy (cache);
881   cache = NULL;
882
883   if (non_empty > 0)
884   {
885     INFO ("rrdtool plugin: %i cache %s had values when destroying the cache.",
886         non_empty, (non_empty == 1) ? "entry" : "entries");
887   }
888   else
889   {
890     DEBUG ("rrdtool plugin: No values have been lost "
891         "when destroying the cache.");
892   }
893
894   pthread_mutex_unlock (&cache_lock);
895   return (0);
896 } /* }}} int rrd_cache_destroy */
897
898 static int rrd_compare_numeric (const void *a_ptr, const void *b_ptr)
899 {
900         int a = *((int *) a_ptr);
901         int b = *((int *) b_ptr);
902
903         if (a < b)
904                 return (-1);
905         else if (a > b)
906                 return (1);
907         else
908                 return (0);
909 } /* int rrd_compare_numeric */
910
911 static int rrd_write (const data_set_t *ds, const value_list_t *vl,
912                 user_data_t __attribute__((unused)) *user_data)
913 {
914         struct stat  statbuf;
915         char         filename[512];
916         char         values[512];
917         int          status;
918
919         if (do_shutdown)
920                 return (0);
921
922         if (0 != strcmp (ds->type, vl->type)) {
923                 ERROR ("rrdtool plugin: DS type does not match value list type");
924                 return -1;
925         }
926
927         if (value_list_to_filename (filename, sizeof (filename), vl) != 0)
928                 return (-1);
929
930         if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
931                 return (-1);
932
933         if (stat (filename, &statbuf) == -1)
934         {
935                 if (errno == ENOENT)
936                 {
937                         status = cu_rrd_create_file (filename,
938                                         ds, vl, &rrdcreate_config);
939                         if (status != 0)
940                                 return (-1);
941                         else if (rrdcreate_config.async)
942                                 return (0);
943                 }
944                 else
945                 {
946                         char errbuf[1024];
947                         ERROR ("stat(%s) failed: %s", filename,
948                                         sstrerror (errno, errbuf,
949                                                 sizeof (errbuf)));
950                         return (-1);
951                 }
952         }
953         else if (!S_ISREG (statbuf.st_mode))
954         {
955                 ERROR ("stat(%s): Not a regular file!",
956                                 filename);
957                 return (-1);
958         }
959
960         status = rrd_cache_insert (filename, values, vl->time);
961
962         return (status);
963 } /* int rrd_write */
964
965 static int rrd_flush (cdtime_t timeout, const char *identifier,
966                 __attribute__((unused)) user_data_t *user_data)
967 {
968         pthread_mutex_lock (&cache_lock);
969
970         if (cache == NULL) {
971                 pthread_mutex_unlock (&cache_lock);
972                 return (0);
973         }
974
975         rrd_cache_flush_identifier (timeout, identifier);
976
977         pthread_mutex_unlock (&cache_lock);
978         return (0);
979 } /* int rrd_flush */
980
981 static int rrd_config (const char *key, const char *value)
982 {
983         if (strcasecmp ("CacheTimeout", key) == 0)
984         {
985                 double tmp = atof (value);
986                 if (tmp < 0)
987                 {
988                         fprintf (stderr, "rrdtool: `CacheTimeout' must "
989                                         "be greater than 0.\n");
990                         ERROR ("rrdtool: `CacheTimeout' must "
991                                         "be greater than 0.\n");
992                         return (1);
993                 }
994                 cache_timeout = DOUBLE_TO_CDTIME_T (tmp);
995         }
996         else if (strcasecmp ("CacheFlush", key) == 0)
997         {
998                 int tmp = atoi (value);
999                 if (tmp < 0)
1000                 {
1001                         fprintf (stderr, "rrdtool: `CacheFlush' must "
1002                                         "be greater than 0.\n");
1003                         ERROR ("rrdtool: `CacheFlush' must "
1004                                         "be greater than 0.\n");
1005                         return (1);
1006                 }
1007                 cache_flush_timeout = tmp;
1008         }
1009         else if (strcasecmp ("DataDir", key) == 0)
1010         {
1011                 char *tmp;
1012                 size_t len;
1013
1014                 tmp = strdup (value);
1015                 if (tmp == NULL)
1016                 {
1017                         ERROR ("rrdtool plugin: strdup failed.");
1018                         return (1);
1019                 }
1020
1021                 len = strlen (tmp);
1022                 while ((len > 0) && (tmp[len - 1] == '/'))
1023                 {
1024                         len--;
1025                         tmp[len] = 0;
1026                 }
1027
1028                 if (len == 0)
1029                 {
1030                         ERROR ("rrdtool plugin: Invalid \"DataDir\" option.");
1031                         sfree (tmp);
1032                         return (1);
1033                 }
1034
1035                 if (datadir != NULL)
1036                 {
1037                         sfree (datadir);
1038                 }
1039
1040                 datadir = tmp;
1041         }
1042         else if (strcasecmp ("StepSize", key) == 0)
1043         {
1044                 unsigned long temp = strtoul (value, NULL, 0);
1045                 if (temp > 0)
1046                         rrdcreate_config.stepsize = temp;
1047         }
1048         else if (strcasecmp ("HeartBeat", key) == 0)
1049         {
1050                 int temp = atoi (value);
1051                 if (temp > 0)
1052                         rrdcreate_config.heartbeat = temp;
1053         }
1054         else if (strcasecmp ("CreateFilesAsync", key) == 0)
1055         {
1056                 if (IS_TRUE (value))
1057                         rrdcreate_config.async = 1;
1058                 else
1059                         rrdcreate_config.async = 0;
1060         }
1061         else if (strcasecmp ("RRARows", key) == 0)
1062         {
1063                 int tmp = atoi (value);
1064                 if (tmp <= 0)
1065                 {
1066                         fprintf (stderr, "rrdtool: `RRARows' must "
1067                                         "be greater than 0.\n");
1068                         ERROR ("rrdtool: `RRARows' must "
1069                                         "be greater than 0.\n");
1070                         return (1);
1071                 }
1072                 rrdcreate_config.rrarows = tmp;
1073         }
1074         else if (strcasecmp ("RRATimespan", key) == 0)
1075         {
1076                 char *saveptr = NULL;
1077                 char *dummy;
1078                 char *ptr;
1079                 char *value_copy;
1080                 int *tmp_alloc;
1081
1082                 value_copy = strdup (value);
1083                 if (value_copy == NULL)
1084                         return (1);
1085
1086                 dummy = value_copy;
1087                 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
1088                 {
1089                         dummy = NULL;
1090
1091                         tmp_alloc = realloc (rrdcreate_config.timespans,
1092                                         sizeof (int) * (rrdcreate_config.timespans_num + 1));
1093                         if (tmp_alloc == NULL)
1094                         {
1095                                 fprintf (stderr, "rrdtool: realloc failed.\n");
1096                                 ERROR ("rrdtool: realloc failed.\n");
1097                                 free (value_copy);
1098                                 return (1);
1099                         }
1100                         rrdcreate_config.timespans = tmp_alloc;
1101                         rrdcreate_config.timespans[rrdcreate_config.timespans_num] = atoi (ptr);
1102                         if (rrdcreate_config.timespans[rrdcreate_config.timespans_num] != 0)
1103                                 rrdcreate_config.timespans_num++;
1104                 } /* while (strtok_r) */
1105
1106                 qsort (/* base = */ rrdcreate_config.timespans,
1107                                 /* nmemb  = */ rrdcreate_config.timespans_num,
1108                                 /* size   = */ sizeof (rrdcreate_config.timespans[0]),
1109                                 /* compar = */ rrd_compare_numeric);
1110
1111                 free (value_copy);
1112         }
1113         else if (strcasecmp ("XFF", key) == 0)
1114         {
1115                 double tmp = atof (value);
1116                 if ((tmp < 0.0) || (tmp >= 1.0))
1117                 {
1118                         fprintf (stderr, "rrdtool: `XFF' must "
1119                                         "be in the range 0 to 1 (exclusive).");
1120                         ERROR ("rrdtool: `XFF' must "
1121                                         "be in the range 0 to 1 (exclusive).");
1122                         return (1);
1123                 }
1124                 rrdcreate_config.xff = tmp;
1125         }
1126         else if (strcasecmp ("WritesPerSecond", key) == 0)
1127         {
1128                 double wps = atof (value);
1129
1130                 if (wps < 0.0)
1131                 {
1132                         fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
1133                                         "greater than or equal to zero.");
1134                         return (1);
1135                 }
1136                 else if (wps == 0.0)
1137                 {
1138                         write_rate = 0.0;
1139                 }
1140                 else
1141                 {
1142                         write_rate = 1.0 / wps;
1143                 }
1144         }
1145         else if (strcasecmp ("RandomTimeout", key) == 0)
1146         {
1147                 double tmp;
1148
1149                 tmp = atof (value);
1150                 if (tmp < 0.0)
1151                 {
1152                         fprintf (stderr, "rrdtool: `RandomTimeout' must "
1153                                         "be greater than or equal to zero.\n");
1154                         ERROR ("rrdtool: `RandomTimeout' must "
1155                                         "be greater then or equal to zero.");
1156                 }
1157                 else
1158                 {
1159                         random_timeout = DOUBLE_TO_CDTIME_T (tmp);
1160                 }
1161         }
1162         else
1163         {
1164                 return (-1);
1165         }
1166         return (0);
1167 } /* int rrd_config */
1168
1169 static int rrd_shutdown (void)
1170 {
1171         pthread_mutex_lock (&cache_lock);
1172         rrd_cache_flush (0);
1173         pthread_mutex_unlock (&cache_lock);
1174
1175         pthread_mutex_lock (&queue_lock);
1176         do_shutdown = 1;
1177         pthread_cond_signal (&queue_cond);
1178         pthread_mutex_unlock (&queue_lock);
1179
1180         if ((queue_thread_running != 0)
1181                         && ((queue_head != NULL) || (flushq_head != NULL)))
1182         {
1183                 INFO ("rrdtool plugin: Shutting down the queue thread. "
1184                                 "This may take a while.");
1185         }
1186         else if (queue_thread_running != 0)
1187         {
1188                 INFO ("rrdtool plugin: Shutting down the queue thread.");
1189         }
1190
1191         /* Wait for all the values to be written to disk before returning. */
1192         if (queue_thread_running != 0)
1193         {
1194                 pthread_join (queue_thread, NULL);
1195                 memset (&queue_thread, 0, sizeof (queue_thread));
1196                 queue_thread_running = 0;
1197                 DEBUG ("rrdtool plugin: queue_thread exited.");
1198         }
1199
1200         rrd_cache_destroy ();
1201
1202         return (0);
1203 } /* int rrd_shutdown */
1204
1205 static int rrd_init (void)
1206 {
1207         static int init_once = 0;
1208         int status;
1209
1210         if (init_once != 0)
1211                 return (0);
1212         init_once = 1;
1213
1214         if (rrdcreate_config.heartbeat <= 0)
1215                 rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
1216
1217         /* Set the cache up */
1218         pthread_mutex_lock (&cache_lock);
1219
1220         cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1221         if (cache == NULL)
1222         {
1223                 pthread_mutex_unlock (&cache_lock);
1224                 ERROR ("rrdtool plugin: c_avl_create failed.");
1225                 return (-1);
1226         }
1227
1228         cache_flush_last = cdtime ();
1229         if (cache_timeout == 0)
1230         {
1231                 cache_flush_timeout = 0;
1232         }
1233         else if (cache_flush_timeout < cache_timeout)
1234                 cache_flush_timeout = 10 * cache_timeout;
1235
1236         pthread_mutex_unlock (&cache_lock);
1237
1238         status = plugin_thread_create (&queue_thread, /* attr = */ NULL,
1239                         rrd_queue_thread, /* args = */ NULL);
1240         if (status != 0)
1241         {
1242                 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1243                 return (-1);
1244         }
1245         queue_thread_running = 1;
1246
1247         DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %lu;"
1248                         " heartbeat = %i; rrarows = %i; xff = %lf;",
1249                         (datadir == NULL) ? "(null)" : datadir,
1250                         rrdcreate_config.stepsize,
1251                         rrdcreate_config.heartbeat,
1252                         rrdcreate_config.rrarows,
1253                         rrdcreate_config.xff);
1254
1255         return (0);
1256 } /* int rrd_init */
1257
1258 void module_register (void)
1259 {
1260         plugin_register_config ("rrdtool", rrd_config,
1261                         config_keys, config_keys_num);
1262         plugin_register_init ("rrdtool", rrd_init);
1263         plugin_register_write ("rrdtool", rrd_write, /* user_data = */ NULL);
1264         plugin_register_flush ("rrdtool", rrd_flush, /* user_data = */ NULL);
1265         plugin_register_shutdown ("rrdtool", rrd_shutdown);
1266 }