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