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