rrdtool plugin: Call rand(3) less often.
[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         int random_variation;
44         enum
45         {
46                 FLAG_NONE   = 0x00,
47                 FLAG_QUEUED = 0x01,
48                 FLAG_FLUSHQ = 0x02
49         } flags;
50 };
51 typedef struct rrd_cache_s rrd_cache_t;
52
53 enum rrd_queue_dir_e
54 {
55   QUEUE_INSERT_FRONT,
56   QUEUE_INSERT_BACK
57 };
58 typedef enum rrd_queue_dir_e rrd_queue_dir_t;
59
60 struct rrd_queue_s
61 {
62         char *filename;
63         struct rrd_queue_s *next;
64 };
65 typedef struct rrd_queue_s rrd_queue_t;
66
67 /*
68  * Private variables
69  */
70 static const char *config_keys[] =
71 {
72         "CacheTimeout",
73         "CacheFlush",
74         "DataDir",
75         "StepSize",
76         "HeartBeat",
77         "RRARows",
78         "RRATimespan",
79         "XFF",
80         "WritesPerSecond",
81         "RandomTimeout"
82 };
83 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
84
85 /* If datadir is zero, the daemon's basedir is used. If stepsize or heartbeat
86  * is zero a default, depending on the `interval' member of the value list is
87  * being used. */
88 static char *datadir   = NULL;
89 static double write_rate = 0.0;
90 static rrdcreate_config_t rrdcreate_config =
91 {
92         /* stepsize = */ 0,
93         /* heartbeat = */ 0,
94         /* rrarows = */ 1200,
95         /* xff = */ 0.1,
96
97         /* timespans = */ NULL,
98         /* timespans_num = */ 0,
99
100         /* consolidation_functions = */ NULL,
101         /* consolidation_functions_num = */ 0
102 };
103
104 /* XXX: If you need to lock both, cache_lock and queue_lock, at the same time,
105  * ALWAYS lock `cache_lock' first! */
106 static int         cache_timeout = 0;
107 static int         cache_flush_timeout = 0;
108 static int         random_timeout = 1;
109 static int         random_timeout_mod = 1;
110 static time_t      cache_flush_last;
111 static c_avl_tree_t *cache = NULL;
112 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
113
114 static rrd_queue_t    *queue_head = NULL;
115 static rrd_queue_t    *queue_tail = NULL;
116 static rrd_queue_t    *flushq_head = NULL;
117 static rrd_queue_t    *flushq_tail = NULL;
118 static pthread_t       queue_thread;
119 static int             queue_thread_running = 1;
120 static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER;
121 static pthread_cond_t  queue_cond = PTHREAD_COND_INITIALIZER;
122
123 #if !HAVE_THREADSAFE_LIBRRD
124 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
125 #endif
126
127 static int do_shutdown = 0;
128
129 #if HAVE_THREADSAFE_LIBRRD
130 static int srrd_update (char *filename, char *template,
131                 int argc, const char **argv)
132 {
133         int status;
134
135         optind = 0; /* bug in librrd? */
136         rrd_clear_error ();
137
138         status = rrd_update_r (filename, template, argc, (void *) argv);
139
140         if (status != 0)
141         {
142                 WARNING ("rrdtool plugin: rrd_update_r (%s) failed: %s",
143                                 filename, rrd_get_error ());
144         }
145
146         return (status);
147 } /* int srrd_update */
148 /* #endif HAVE_THREADSAFE_LIBRRD */
149
150 #else /* !HAVE_THREADSAFE_LIBRRD */
151 static int srrd_update (char *filename, char *template,
152                 int argc, const char **argv)
153 {
154         int status;
155
156         int new_argc;
157         char **new_argv;
158
159         assert (template == NULL);
160
161         new_argc = 2 + argc;
162         new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
163         if (new_argv == NULL)
164         {
165                 ERROR ("rrdtool plugin: malloc failed.");
166                 return (-1);
167         }
168
169         new_argv[0] = "update";
170         new_argv[1] = filename;
171
172         memcpy (new_argv + 2, argv, argc * sizeof (char *));
173         new_argv[new_argc] = NULL;
174
175         pthread_mutex_lock (&librrd_lock);
176         optind = 0; /* bug in librrd? */
177         rrd_clear_error ();
178
179         status = rrd_update (new_argc, new_argv);
180         pthread_mutex_unlock (&librrd_lock);
181
182         if (status != 0)
183         {
184                 WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
185                                 argv[1], rrd_get_error ());
186         }
187
188         sfree (new_argv);
189
190         return (status);
191 } /* int srrd_update */
192 #endif /* !HAVE_THREADSAFE_LIBRRD */
193
194 static int value_list_to_string (char *buffer, int buffer_len,
195                 const data_set_t *ds, const value_list_t *vl)
196 {
197         int offset;
198         int status;
199         int i;
200
201         memset (buffer, '\0', buffer_len);
202
203         status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) vl->time);
204         if ((status < 1) || (status >= buffer_len))
205                 return (-1);
206         offset = status;
207
208         for (i = 0; i < ds->ds_num; i++)
209         {
210                 if ((ds->ds[i].type != DS_TYPE_COUNTER)
211                                 && (ds->ds[i].type != DS_TYPE_GAUGE)
212                                 && (ds->ds[i].type != DS_TYPE_DERIVE)
213                                 && (ds->ds[i].type != DS_TYPE_ABSOLUTE))
214                         return (-1);
215
216                 if (ds->ds[i].type == DS_TYPE_COUNTER)
217                         status = ssnprintf (buffer + offset, buffer_len - offset,
218                                         ":%llu", vl->values[i].counter);
219                 else if (ds->ds[i].type == DS_TYPE_GAUGE)
220                         status = ssnprintf (buffer + offset, buffer_len - offset,
221                                         ":%lf", vl->values[i].gauge);
222                 else if (ds->ds[i].type == DS_TYPE_DERIVE)
223                         status = ssnprintf (buffer + offset, buffer_len - offset,
224                                         ":%"PRIi64, vl->values[i].derive);
225                 else /*if (ds->ds[i].type == DS_TYPE_ABSOLUTE) */
226                         status = ssnprintf (buffer + offset, buffer_len - offset,
227                                         ":%"PRIu64, vl->values[i].absolute);
228
229                 if ((status < 1) || (status >= (buffer_len - offset)))
230                         return (-1);
231
232                 offset += status;
233         } /* for ds->ds_num */
234
235         return (0);
236 } /* int value_list_to_string */
237
238 static int value_list_to_filename (char *buffer, int buffer_len,
239                 const data_set_t __attribute__((unused)) *ds, const value_list_t *vl)
240 {
241         int offset = 0;
242         int status;
243
244         if (datadir != NULL)
245         {
246                 status = ssnprintf (buffer + offset, buffer_len - offset,
247                                 "%s/", datadir);
248                 if ((status < 1) || (status >= buffer_len - offset))
249                         return (-1);
250                 offset += status;
251         }
252
253         status = ssnprintf (buffer + offset, buffer_len - offset,
254                         "%s/", vl->host);
255         if ((status < 1) || (status >= buffer_len - offset))
256                 return (-1);
257         offset += status;
258
259         if (strlen (vl->plugin_instance) > 0)
260                 status = ssnprintf (buffer + offset, buffer_len - offset,
261                                 "%s-%s/", vl->plugin, vl->plugin_instance);
262         else
263                 status = ssnprintf (buffer + offset, buffer_len - offset,
264                                 "%s/", vl->plugin);
265         if ((status < 1) || (status >= buffer_len - offset))
266                 return (-1);
267         offset += status;
268
269         if (strlen (vl->type_instance) > 0)
270                 status = ssnprintf (buffer + offset, buffer_len - offset,
271                                 "%s-%s.rrd", vl->type, vl->type_instance);
272         else
273                 status = ssnprintf (buffer + offset, buffer_len - offset,
274                                 "%s.rrd", vl->type);
275         if ((status < 1) || (status >= buffer_len - offset))
276                 return (-1);
277         offset += status;
278
279         return (0);
280 } /* int value_list_to_filename */
281
282 static void *rrd_queue_thread (void __attribute__((unused)) *data)
283 {
284         struct timeval tv_next_update;
285         struct timeval tv_now;
286
287         gettimeofday (&tv_next_update, /* timezone = */ NULL);
288
289         while (42)
290         {
291                 rrd_queue_t *queue_entry;
292                 rrd_cache_t *cache_entry;
293                 char **values;
294                 int    values_num;
295                 int    status;
296                 int    i;
297
298                 values = NULL;
299                 values_num = 0;
300
301                 pthread_mutex_lock (&queue_lock);
302                 /* Wait for values to arrive */
303                 while (true)
304                 {
305                   struct timespec ts_wait;
306
307                   while ((flushq_head == NULL) && (queue_head == NULL)
308                       && (do_shutdown == 0))
309                     pthread_cond_wait (&queue_cond, &queue_lock);
310
311                   if ((flushq_head == NULL) && (queue_head == NULL))
312                     break;
313
314                   /* Don't delay if there's something to flush */
315                   if (flushq_head != NULL)
316                     break;
317
318                   /* Don't delay if we're shutting down */
319                   if (do_shutdown != 0)
320                     break;
321
322                   /* Don't delay if no delay was configured. */
323                   if (write_rate <= 0.0)
324                     break;
325
326                   gettimeofday (&tv_now, /* timezone = */ NULL);
327                   status = timeval_cmp (tv_next_update, tv_now, NULL);
328                   /* We're good to go */
329                   if (status <= 0)
330                     break;
331
332                   /* We're supposed to wait a bit with this update, so we'll
333                    * wait for the next addition to the queue or to the end of
334                    * the wait period - whichever comes first. */
335                   ts_wait.tv_sec = tv_next_update.tv_sec;
336                   ts_wait.tv_nsec = 1000 * tv_next_update.tv_usec;
337
338                   status = pthread_cond_timedwait (&queue_cond, &queue_lock,
339                       &ts_wait);
340                   if (status == ETIMEDOUT)
341                     break;
342                 } /* while (true) */
343
344                 /* XXX: If you need to lock both, cache_lock and queue_lock, at
345                  * the same time, ALWAYS lock `cache_lock' first! */
346
347                 /* We're in the shutdown phase */
348                 if ((flushq_head == NULL) && (queue_head == NULL))
349                 {
350                   pthread_mutex_unlock (&queue_lock);
351                   break;
352                 }
353
354                 if (flushq_head != NULL)
355                 {
356                   /* Dequeue the first flush entry */
357                   queue_entry = flushq_head;
358                   if (flushq_head == flushq_tail)
359                     flushq_head = flushq_tail = NULL;
360                   else
361                     flushq_head = flushq_head->next;
362                 }
363                 else /* if (queue_head != NULL) */
364                 {
365                   /* Dequeue the first regular entry */
366                   queue_entry = queue_head;
367                   if (queue_head == queue_tail)
368                     queue_head = queue_tail = NULL;
369                   else
370                     queue_head = queue_head->next;
371                 }
372
373                 /* Unlock the queue again */
374                 pthread_mutex_unlock (&queue_lock);
375
376                 /* We now need the cache lock so the entry isn't updated while
377                  * we make a copy of it's values */
378                 pthread_mutex_lock (&cache_lock);
379
380                 status = c_avl_get (cache, queue_entry->filename,
381                                 (void *) &cache_entry);
382
383                 if (status == 0)
384                 {
385                         values = cache_entry->values;
386                         values_num = cache_entry->values_num;
387
388                         cache_entry->values = NULL;
389                         cache_entry->values_num = 0;
390                         cache_entry->flags = FLAG_NONE;
391                 }
392
393                 pthread_mutex_unlock (&cache_lock);
394
395                 if (status != 0)
396                 {
397                         sfree (queue_entry->filename);
398                         sfree (queue_entry);
399                         continue;
400                 }
401
402                 /* Update `tv_next_update' */
403                 if (write_rate > 0.0) 
404                 {
405                   gettimeofday (&tv_now, /* timezone = */ NULL);
406                   tv_next_update.tv_sec = tv_now.tv_sec;
407                   tv_next_update.tv_usec = tv_now.tv_usec
408                     + ((suseconds_t) (1000000 * write_rate));
409                   while (tv_next_update.tv_usec > 1000000)
410                   {
411                     tv_next_update.tv_sec++;
412                     tv_next_update.tv_usec -= 1000000;
413                   }
414                 }
415
416                 /* Write the values to the RRD-file */
417                 srrd_update (queue_entry->filename, NULL,
418                                 values_num, (const char **)values);
419                 DEBUG ("rrdtool plugin: queue thread: Wrote %i value%s to %s",
420                                 values_num, (values_num == 1) ? "" : "s",
421                                 queue_entry->filename);
422
423                 for (i = 0; i < values_num; i++)
424                 {
425                         sfree (values[i]);
426                 }
427                 sfree (values);
428                 sfree (queue_entry->filename);
429                 sfree (queue_entry);
430         } /* while (42) */
431
432         pthread_mutex_lock (&cache_lock);
433         c_avl_destroy (cache);
434         cache = NULL;
435         pthread_mutex_unlock (&cache_lock);
436
437         pthread_exit ((void *) 0);
438         return ((void *) 0);
439 } /* void *rrd_queue_thread */
440
441 static int rrd_queue_enqueue (const char *filename,
442     rrd_queue_t **head, rrd_queue_t **tail)
443 {
444   rrd_queue_t *queue_entry;
445
446   queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
447   if (queue_entry == NULL)
448     return (-1);
449
450   queue_entry->filename = strdup (filename);
451   if (queue_entry->filename == NULL)
452   {
453     free (queue_entry);
454     return (-1);
455   }
456
457   queue_entry->next = NULL;
458
459   pthread_mutex_lock (&queue_lock);
460
461   if (*tail == NULL)
462     *head = queue_entry;
463   else
464     (*tail)->next = queue_entry;
465   *tail = queue_entry;
466
467   pthread_cond_signal (&queue_cond);
468   pthread_mutex_unlock (&queue_lock);
469
470   return (0);
471 } /* int rrd_queue_enqueue */
472
473 static int rrd_queue_dequeue (const char *filename,
474     rrd_queue_t **head, rrd_queue_t **tail)
475 {
476   rrd_queue_t *this;
477   rrd_queue_t *prev;
478
479   pthread_mutex_lock (&queue_lock);
480
481   prev = NULL;
482   this = *head;
483
484   while (this != NULL)
485   {
486     if (strcmp (this->filename, filename) == 0)
487       break;
488     
489     prev = this;
490     this = this->next;
491   }
492
493   if (this == NULL)
494   {
495     pthread_mutex_unlock (&queue_lock);
496     return (-1);
497   }
498
499   if (prev == NULL)
500     *head = this->next;
501   else
502     prev->next = this->next;
503
504   if (this->next == NULL)
505     *tail = prev;
506
507   pthread_mutex_unlock (&queue_lock);
508
509   sfree (this->filename);
510   sfree (this);
511
512   return (0);
513 } /* int rrd_queue_dequeue */
514
515 static void rrd_cache_flush (int timeout)
516 {
517         rrd_cache_t *rc;
518         time_t       now;
519
520         char **keys = NULL;
521         int    keys_num = 0;
522
523         char *key;
524         c_avl_iterator_t *iter;
525         int i;
526
527         DEBUG ("rrdtool plugin: Flushing cache, timeout = %i", timeout);
528
529         now = time (NULL);
530
531         /* Build a list of entries to be flushed */
532         iter = c_avl_get_iterator (cache);
533         while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
534         {
535                 if (rc->flags != FLAG_NONE)
536                         continue;
537                 else if ((now - rc->first_value) < timeout)
538                         continue;
539                 else if (rc->values_num > 0)
540                 {
541                         int status;
542
543                         status = rrd_queue_enqueue (key, &queue_head,  &queue_tail);
544                         if (status == 0)
545                                 rc->flags = FLAG_QUEUED;
546                 }
547                 else /* ancient and no values -> waste of memory */
548                 {
549                         char **tmp = (char **) realloc ((void *) keys,
550                                         (keys_num + 1) * sizeof (char *));
551                         if (tmp == NULL)
552                         {
553                                 char errbuf[1024];
554                                 ERROR ("rrdtool plugin: "
555                                                 "realloc failed: %s",
556                                                 sstrerror (errno, errbuf,
557                                                         sizeof (errbuf)));
558                                 c_avl_iterator_destroy (iter);
559                                 sfree (keys);
560                                 return;
561                         }
562                         keys = tmp;
563                         keys[keys_num] = key;
564                         keys_num++;
565                 }
566         } /* while (c_avl_iterator_next) */
567         c_avl_iterator_destroy (iter);
568         
569         for (i = 0; i < keys_num; i++)
570         {
571                 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
572                 {
573                         DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
574                         continue;
575                 }
576
577                 assert (rc->values == NULL);
578                 assert (rc->values_num == 0);
579
580                 sfree (rc);
581                 sfree (key);
582                 keys[i] = NULL;
583         } /* for (i = 0..keys_num) */
584
585         sfree (keys);
586
587         cache_flush_last = now;
588 } /* void rrd_cache_flush */
589
590 static int rrd_cache_flush_identifier (int timeout, const char *identifier)
591 {
592   rrd_cache_t *rc;
593   time_t now;
594   int status;
595   char key[2048];
596
597   if (identifier == NULL)
598   {
599     rrd_cache_flush (timeout);
600     return (0);
601   }
602
603   now = time (NULL);
604
605   if (datadir == NULL)
606     snprintf (key, sizeof (key), "%s.rrd",
607         identifier);
608   else
609     snprintf (key, sizeof (key), "%s/%s.rrd",
610         datadir, identifier);
611   key[sizeof (key) - 1] = 0;
612
613   status = c_avl_get (cache, key, (void *) &rc);
614   if (status != 0)
615   {
616     INFO ("rrdtool plugin: rrd_cache_flush_identifier: "
617         "c_avl_get (%s) failed. Does that file really exist?",
618         key);
619     return (status);
620   }
621
622   if (rc->flags == FLAG_FLUSHQ)
623   {
624     status = 0;
625   }
626   else if (rc->flags == FLAG_QUEUED)
627   {
628     rrd_queue_dequeue (key, &queue_head, &queue_tail);
629     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
630     if (status == 0)
631       rc->flags = FLAG_FLUSHQ;
632   }
633   else if ((now - rc->first_value) < timeout)
634   {
635     status = 0;
636   }
637   else if (rc->values_num > 0)
638   {
639     status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
640     if (status == 0)
641       rc->flags = FLAG_FLUSHQ;
642   }
643
644   return (status);
645 } /* int rrd_cache_flush_identifier */
646
647 static int rrd_cache_insert (const char *filename,
648                 const char *value, time_t value_time)
649 {
650         rrd_cache_t *rc = NULL;
651         int new_rc = 0;
652         char **values_new;
653
654         pthread_mutex_lock (&cache_lock);
655
656         /* This shouldn't happen, but it did happen at least once, so we'll be
657          * careful. */
658         if (cache == NULL)
659         {
660                 pthread_mutex_unlock (&cache_lock);
661                 WARNING ("rrdtool plugin: cache == NULL.");
662                 return (-1);
663         }
664
665         c_avl_get (cache, filename, (void *) &rc);
666
667         if (rc == NULL)
668         {
669                 rc = (rrd_cache_t *) malloc (sizeof (rrd_cache_t));
670                 if (rc == NULL)
671                         return (-1);
672                 rc->values_num = 0;
673                 rc->values = NULL;
674                 rc->first_value = 0;
675                 rc->last_value = 0;
676                 rc->flags = FLAG_NONE;
677                 new_rc = 1;
678         }
679
680         if (rc->last_value >= value_time)
681         {
682                 pthread_mutex_unlock (&cache_lock);
683                 WARNING ("rrdtool plugin: (rc->last_value = %u) >= (value_time = %u)",
684                                 (unsigned int) rc->last_value,
685                                 (unsigned int) value_time);
686                 return (-1);
687         }
688
689         values_new = (char **) realloc ((void *) rc->values,
690                         (rc->values_num + 1) * sizeof (char *));
691         if (values_new == NULL)
692         {
693                 char errbuf[1024];
694                 void *cache_key = NULL;
695
696                 sstrerror (errno, errbuf, sizeof (errbuf));
697
698                 c_avl_remove (cache, filename, &cache_key, NULL);
699                 pthread_mutex_unlock (&cache_lock);
700
701                 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
702
703                 sfree (cache_key);
704                 sfree (rc->values);
705                 sfree (rc);
706                 return (-1);
707         }
708         rc->values = values_new;
709
710         rc->values[rc->values_num] = strdup (value);
711         if (rc->values[rc->values_num] != NULL)
712                 rc->values_num++;
713
714         if (rc->values_num == 1)
715                 rc->first_value = value_time;
716         rc->last_value = value_time;
717
718         /* Insert if this is the first value */
719         if (new_rc == 1)
720         {
721                 void *cache_key = strdup (filename);
722
723                 if (cache_key == NULL)
724                 {
725                         char errbuf[1024];
726                         sstrerror (errno, errbuf, sizeof (errbuf));
727
728                         pthread_mutex_unlock (&cache_lock);
729
730                         ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
731
732                         sfree (rc->values[0]);
733                         sfree (rc->values);
734                         sfree (rc);
735                         return (-1);
736                 }
737
738                 c_avl_insert (cache, cache_key, rc);
739         }
740
741         DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
742                         "values_num = %i; age = %lu;",
743                         filename, rc->values_num,
744                         (unsigned long)(rc->last_value - rc->first_value));
745
746         if ((rc->last_value - rc->first_value + rc->random_variation) >= cache_timeout)
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                         rc->random_variation = (random_timeout - (rand() % random_timeout_mod));
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 }