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