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 **/
26 #include "collectd.h"
27 #include "plugin.h"
28 #include "common.h"
29 #include "utils_avltree.h"
30 #include "utils_random.h"
31 #include "utils_rrdcreate.h"
33 #include <rrd.h>
35 #if HAVE_PTHREAD_H
36 # include <pthread.h>
37 #endif
39 /*
40 * Private types
41 */
42 struct rrd_cache_s
43 {
44 int values_num;
45 char **values;
46 cdtime_t first_value;
47 cdtime_t last_value;
48 int64_t random_variation;
49 enum
50 {
51 FLAG_NONE = 0x00,
52 FLAG_QUEUED = 0x01,
53 FLAG_FLUSHQ = 0x02
54 } flags;
55 };
56 typedef struct rrd_cache_s rrd_cache_t;
58 enum rrd_queue_dir_e
59 {
60 QUEUE_INSERT_FRONT,
61 QUEUE_INSERT_BACK
62 };
63 typedef enum rrd_queue_dir_e rrd_queue_dir_t;
65 struct rrd_queue_s
66 {
67 char *filename;
68 struct rrd_queue_s *next;
69 };
70 typedef struct rrd_queue_s rrd_queue_t;
72 /*
73 * Private variables
74 */
75 static const char *config_keys[] =
76 {
77 "CacheTimeout",
78 "CacheFlush",
79 "CreateFilesAsync",
80 "DataDir",
81 "StepSize",
82 "HeartBeat",
83 "RRARows",
84 "RRATimespan",
85 "XFF",
86 "WritesPerSecond",
87 "RandomTimeout"
88 };
89 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
91 /* If datadir is zero, the daemon's basedir is used. If stepsize or heartbeat
92 * is zero a default, depending on the `interval' member of the value list is
93 * being used. */
94 static char *datadir = NULL;
95 static double write_rate = 0.0;
96 static rrdcreate_config_t rrdcreate_config =
97 {
98 /* stepsize = */ 0,
99 /* heartbeat = */ 0,
100 /* rrarows = */ 1200,
101 /* xff = */ 0.1,
103 /* timespans = */ NULL,
104 /* timespans_num = */ 0,
106 /* consolidation_functions = */ NULL,
107 /* consolidation_functions_num = */ 0,
109 /* async = */ 0
110 };
112 /* XXX: If you need to lock both, cache_lock and queue_lock, at the same time,
113 * ALWAYS lock `cache_lock' first! */
114 static cdtime_t cache_timeout = 0;
115 static cdtime_t cache_flush_timeout = 0;
116 static cdtime_t random_timeout = TIME_T_TO_CDTIME_T (1);
117 static cdtime_t cache_flush_last;
118 static c_avl_tree_t *cache = NULL;
119 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
121 static rrd_queue_t *queue_head = NULL;
122 static rrd_queue_t *queue_tail = NULL;
123 static rrd_queue_t *flushq_head = NULL;
124 static rrd_queue_t *flushq_tail = NULL;
125 static pthread_t queue_thread;
126 static int queue_thread_running = 1;
127 static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER;
128 static pthread_cond_t queue_cond = PTHREAD_COND_INITIALIZER;
130 #if !HAVE_THREADSAFE_LIBRRD
131 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
132 #endif
134 static int do_shutdown = 0;
136 #if HAVE_THREADSAFE_LIBRRD
137 static int srrd_update (char *filename, char *template,
138 int argc, const char **argv)
139 {
140 int status;
142 optind = 0; /* bug in librrd? */
143 rrd_clear_error ();
145 status = rrd_update_r (filename, template, argc, (void *) argv);
147 if (status != 0)
148 {
149 WARNING ("rrdtool plugin: rrd_update_r (%s) failed: %s",
150 filename, rrd_get_error ());
151 }
153 return (status);
154 } /* int srrd_update */
155 /* #endif HAVE_THREADSAFE_LIBRRD */
157 #else /* !HAVE_THREADSAFE_LIBRRD */
158 static int srrd_update (char *filename, char *template,
159 int argc, const char **argv)
160 {
161 int status;
163 int new_argc;
164 char **new_argv;
166 assert (template == NULL);
168 new_argc = 2 + argc;
169 new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
170 if (new_argv == NULL)
171 {
172 ERROR ("rrdtool plugin: malloc failed.");
173 return (-1);
174 }
176 new_argv[0] = "update";
177 new_argv[1] = filename;
179 memcpy (new_argv + 2, argv, argc * sizeof (char *));
180 new_argv[new_argc] = NULL;
182 pthread_mutex_lock (&librrd_lock);
183 optind = 0; /* bug in librrd? */
184 rrd_clear_error ();
186 status = rrd_update (new_argc, new_argv);
187 pthread_mutex_unlock (&librrd_lock);
189 if (status != 0)
190 {
191 WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
192 filename, rrd_get_error ());
193 }
195 sfree (new_argv);
197 return (status);
198 } /* int srrd_update */
199 #endif /* !HAVE_THREADSAFE_LIBRRD */
201 static int value_list_to_string_multiple (char *buffer, int buffer_len,
202 const data_set_t *ds, const value_list_t *vl)
203 {
204 int offset;
205 int status;
206 time_t tt;
207 size_t i;
209 memset (buffer, '\0', buffer_len);
211 tt = CDTIME_T_TO_TIME_T (vl->time);
212 status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) tt);
213 if ((status < 1) || (status >= buffer_len))
214 return (-1);
215 offset = status;
217 for (i = 0; i < ds->ds_num; i++)
218 {
219 if ((ds->ds[i].type != DS_TYPE_COUNTER)
220 && (ds->ds[i].type != DS_TYPE_GAUGE)
221 && (ds->ds[i].type != DS_TYPE_DERIVE)
222 && (ds->ds[i].type != DS_TYPE_ABSOLUTE))
223 return (-1);
225 if (ds->ds[i].type == DS_TYPE_COUNTER)
226 status = ssnprintf (buffer + offset, buffer_len - offset,
227 ":%llu", vl->values[i].counter);
228 else if (ds->ds[i].type == DS_TYPE_GAUGE)
229 status = ssnprintf (buffer + offset, buffer_len - offset,
230 ":"GAUGE_FORMAT, vl->values[i].gauge);
231 else if (ds->ds[i].type == DS_TYPE_DERIVE)
232 status = ssnprintf (buffer + offset, buffer_len - offset,
233 ":%"PRIi64, vl->values[i].derive);
234 else /*if (ds->ds[i].type == DS_TYPE_ABSOLUTE) */
235 status = ssnprintf (buffer + offset, buffer_len - offset,
236 ":%"PRIu64, vl->values[i].absolute);
238 if ((status < 1) || (status >= (buffer_len - offset)))
239 return (-1);
241 offset += status;
242 } /* for ds->ds_num */
244 return (0);
245 } /* int value_list_to_string_multiple */
247 static int value_list_to_string (char *buffer, int buffer_len,
248 const data_set_t *ds, const value_list_t *vl)
249 {
250 int status;
251 time_t tt;
253 if (ds->ds_num != 1)
254 return (value_list_to_string_multiple (buffer, buffer_len,
255 ds, vl));
257 tt = CDTIME_T_TO_TIME_T (vl->time);
258 switch (ds->ds[0].type)
259 {
260 case DS_TYPE_DERIVE:
261 status = ssnprintf (buffer, buffer_len, "%u:%"PRIi64,
262 (unsigned) tt, vl->values[0].derive);
263 break;
264 case DS_TYPE_GAUGE:
265 status = ssnprintf (buffer, buffer_len, "%u:"GAUGE_FORMAT,
266 (unsigned) tt, vl->values[0].gauge);
267 break;
268 case DS_TYPE_COUNTER:
269 status = ssnprintf (buffer, buffer_len, "%u:%llu",
270 (unsigned) tt, vl->values[0].counter);
271 break;
272 case DS_TYPE_ABSOLUTE:
273 status = ssnprintf (buffer, buffer_len, "%u:%"PRIu64,
274 (unsigned) tt, vl->values[0].absolute);
275 break;
276 default:
277 return (EINVAL);
278 }
280 if ((status < 1) || (status >= buffer_len))
281 return (ENOMEM);
283 return (0);
284 } /* int value_list_to_string */
286 static int value_list_to_filename (char *buffer, size_t buffer_size,
287 value_list_t const *vl)
288 {
289 char const suffix[] = ".rrd";
290 int status;
291 size_t len;
293 if (datadir != NULL)
294 {
295 size_t datadir_len = strlen (datadir) + 1;
297 if (datadir_len >= buffer_size)
298 return (ENOMEM);
300 sstrncpy (buffer, datadir, buffer_size);
301 buffer[datadir_len - 1] = '/';
302 buffer[datadir_len] = 0;
304 buffer += datadir_len;
305 buffer_size -= datadir_len;
306 }
308 status = FORMAT_VL (buffer, buffer_size, vl);
309 if (status != 0)
310 return (status);
312 len = strlen (buffer);
313 assert (len < buffer_size);
314 buffer += len;
315 buffer_size -= len;
317 if (buffer_size <= sizeof (suffix))
318 return (ENOMEM);
320 memcpy (buffer, suffix, sizeof (suffix));
321 return (0);
322 } /* int value_list_to_filename */
324 static void *rrd_queue_thread (void __attribute__((unused)) *data)
325 {
326 struct timeval tv_next_update;
327 struct timeval tv_now;
329 gettimeofday (&tv_next_update, /* timezone = */ NULL);
331 while (42)
332 {
333 rrd_queue_t *queue_entry;
334 rrd_cache_t *cache_entry;
335 char **values;
336 int values_num;
337 int status;
338 int i;
340 values = NULL;
341 values_num = 0;
343 pthread_mutex_lock (&queue_lock);
344 /* Wait for values to arrive */
345 while (42)
346 {
347 struct timespec ts_wait;
349 while ((flushq_head == NULL) && (queue_head == NULL)
350 && (do_shutdown == 0))
351 pthread_cond_wait (&queue_cond, &queue_lock);
353 if ((flushq_head == NULL) && (queue_head == NULL))
354 break;
356 /* Don't delay if there's something to flush */
357 if (flushq_head != NULL)
358 break;
360 /* Don't delay if we're shutting down */
361 if (do_shutdown != 0)
362 break;
364 /* Don't delay if no delay was configured. */
365 if (write_rate <= 0.0)
366 break;
368 gettimeofday (&tv_now, /* timezone = */ NULL);
369 status = timeval_cmp (tv_next_update, tv_now, NULL);
370 /* We're good to go */
371 if (status <= 0)
372 break;
374 /* We're supposed to wait a bit with this update, so we'll
375 * wait for the next addition to the queue or to the end of
376 * the wait period - whichever comes first. */
377 ts_wait.tv_sec = tv_next_update.tv_sec;
378 ts_wait.tv_nsec = 1000 * tv_next_update.tv_usec;
380 status = pthread_cond_timedwait (&queue_cond, &queue_lock,
381 &ts_wait);
382 if (status == ETIMEDOUT)
383 break;
384 } /* while (42) */
386 /* XXX: If you need to lock both, cache_lock and queue_lock, at
387 * the same time, ALWAYS lock `cache_lock' first! */
389 /* We're in the shutdown phase */
390 if ((flushq_head == NULL) && (queue_head == NULL))
391 {
392 pthread_mutex_unlock (&queue_lock);
393 break;
394 }
396 if (flushq_head != NULL)
397 {
398 /* Dequeue the first flush entry */
399 queue_entry = flushq_head;
400 if (flushq_head == flushq_tail)
401 flushq_head = flushq_tail = NULL;
402 else
403 flushq_head = flushq_head->next;
404 }
405 else /* if (queue_head != NULL) */
406 {
407 /* Dequeue the first regular entry */
408 queue_entry = queue_head;
409 if (queue_head == queue_tail)
410 queue_head = queue_tail = NULL;
411 else
412 queue_head = queue_head->next;
413 }
415 /* Unlock the queue again */
416 pthread_mutex_unlock (&queue_lock);
418 /* We now need the cache lock so the entry isn't updated while
419 * we make a copy of it's values */
420 pthread_mutex_lock (&cache_lock);
422 status = c_avl_get (cache, queue_entry->filename,
423 (void *) &cache_entry);
425 if (status == 0)
426 {
427 values = cache_entry->values;
428 values_num = cache_entry->values_num;
430 cache_entry->values = NULL;
431 cache_entry->values_num = 0;
432 cache_entry->flags = FLAG_NONE;
433 }
435 pthread_mutex_unlock (&cache_lock);
437 if (status != 0)
438 {
439 sfree (queue_entry->filename);
440 sfree (queue_entry);
441 continue;
442 }
444 /* Update `tv_next_update' */
445 if (write_rate > 0.0)
446 {
447 gettimeofday (&tv_now, /* timezone = */ NULL);
448 tv_next_update.tv_sec = tv_now.tv_sec;
449 tv_next_update.tv_usec = tv_now.tv_usec
450 + ((suseconds_t) (1000000 * write_rate));
451 while (tv_next_update.tv_usec > 1000000)
452 {
453 tv_next_update.tv_sec++;
454 tv_next_update.tv_usec -= 1000000;
455 }
456 }
458 /* Write the values to the RRD-file */
459 srrd_update (queue_entry->filename, NULL,
460 values_num, (const char **)values);
461 DEBUG ("rrdtool plugin: queue thread: Wrote %i value%s to %s",
462 values_num, (values_num == 1) ? "" : "s",
463 queue_entry->filename);
465 for (i = 0; i < values_num; i++)
466 {
467 sfree (values[i]);
468 }
469 sfree (values);
470 sfree (queue_entry->filename);
471 sfree (queue_entry);
472 } /* while (42) */
474 pthread_exit ((void *) 0);
475 return ((void *) 0);
476 } /* void *rrd_queue_thread */
478 static int rrd_queue_enqueue (const char *filename,
479 rrd_queue_t **head, rrd_queue_t **tail)
480 {
481 rrd_queue_t *queue_entry;
483 queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
484 if (queue_entry == NULL)
485 return (-1);
487 queue_entry->filename = strdup (filename);
488 if (queue_entry->filename == NULL)
489 {
490 free (queue_entry);
491 return (-1);
492 }
494 queue_entry->next = NULL;
496 pthread_mutex_lock (&queue_lock);
498 if (*tail == NULL)
499 *head = queue_entry;
500 else
501 (*tail)->next = queue_entry;
502 *tail = queue_entry;
504 pthread_cond_signal (&queue_cond);
505 pthread_mutex_unlock (&queue_lock);
507 return (0);
508 } /* int rrd_queue_enqueue */
510 static int rrd_queue_dequeue (const char *filename,
511 rrd_queue_t **head, rrd_queue_t **tail)
512 {
513 rrd_queue_t *this;
514 rrd_queue_t *prev;
516 pthread_mutex_lock (&queue_lock);
518 prev = NULL;
519 this = *head;
521 while (this != NULL)
522 {
523 if (strcmp (this->filename, filename) == 0)
524 break;
526 prev = this;
527 this = this->next;
528 }
530 if (this == NULL)
531 {
532 pthread_mutex_unlock (&queue_lock);
533 return (-1);
534 }
536 if (prev == NULL)
537 *head = this->next;
538 else
539 prev->next = this->next;
541 if (this->next == NULL)
542 *tail = prev;
544 pthread_mutex_unlock (&queue_lock);
546 sfree (this->filename);
547 sfree (this);
549 return (0);
550 } /* int rrd_queue_dequeue */
552 /* XXX: You must hold "cache_lock" when calling this function! */
553 static void rrd_cache_flush (cdtime_t timeout)
554 {
555 rrd_cache_t *rc;
556 cdtime_t now;
558 char **keys = NULL;
559 int keys_num = 0;
561 char *key;
562 c_avl_iterator_t *iter;
563 int i;
565 DEBUG ("rrdtool plugin: Flushing cache, timeout = %.3f",
566 CDTIME_T_TO_DOUBLE (timeout));
568 now = cdtime ();
569 timeout = TIME_T_TO_CDTIME_T (timeout);
571 /* Build a list of entries to be flushed */
572 iter = c_avl_get_iterator (cache);
573 while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
574 {
575 if (rc->flags != FLAG_NONE)
576 continue;
577 /* timeout == 0 => flush everything */
578 else if ((timeout != 0)
579 && ((now - rc->first_value) < timeout))
580 continue;
581 else if (rc->values_num > 0)
582 {
583 int status;
585 status = rrd_queue_enqueue (key, &queue_head, &queue_tail);
586 if (status == 0)
587 rc->flags = FLAG_QUEUED;
588 }
589 else /* ancient and no values -> waste of memory */
590 {
591 char **tmp = (char **) realloc ((void *) keys,
592 (keys_num + 1) * sizeof (char *));
593 if (tmp == NULL)
594 {
595 char errbuf[1024];
596 ERROR ("rrdtool plugin: "
597 "realloc failed: %s",
598 sstrerror (errno, errbuf,
599 sizeof (errbuf)));
600 c_avl_iterator_destroy (iter);
601 sfree (keys);
602 return;
603 }
604 keys = tmp;
605 keys[keys_num] = key;
606 keys_num++;
607 }
608 } /* while (c_avl_iterator_next) */
609 c_avl_iterator_destroy (iter);
611 for (i = 0; i < keys_num; i++)
612 {
613 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
614 {
615 DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
616 continue;
617 }
619 assert (rc->values == NULL);
620 assert (rc->values_num == 0);
622 sfree (rc);
623 sfree (key);
624 keys[i] = NULL;
625 } /* for (i = 0..keys_num) */
627 sfree (keys);
629 cache_flush_last = now;
630 } /* void rrd_cache_flush */
632 static int rrd_cache_flush_identifier (cdtime_t timeout,
633 const char *identifier)
634 {
635 rrd_cache_t *rc;
636 cdtime_t now;
637 int status;
638 char key[2048];
640 if (identifier == NULL)
641 {
642 rrd_cache_flush (timeout);
643 return (0);
644 }
646 now = cdtime ();
648 if (datadir == NULL)
649 snprintf (key, sizeof (key), "%s.rrd",
650 identifier);
651 else
652 snprintf (key, sizeof (key), "%s/%s.rrd",
653 datadir, identifier);
654 key[sizeof (key) - 1] = 0;
656 status = c_avl_get (cache, key, (void *) &rc);
657 if (status != 0)
658 {
659 INFO ("rrdtool plugin: rrd_cache_flush_identifier: "
660 "c_avl_get (%s) failed. Does that file really exist?",
661 key);
662 return (status);
663 }
665 if (rc->flags == FLAG_FLUSHQ)
666 {
667 status = 0;
668 }
669 else if (rc->flags == FLAG_QUEUED)
670 {
671 rrd_queue_dequeue (key, &queue_head, &queue_tail);
672 status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
673 if (status == 0)
674 rc->flags = FLAG_FLUSHQ;
675 }
676 else if ((now - rc->first_value) < timeout)
677 {
678 status = 0;
679 }
680 else if (rc->values_num > 0)
681 {
682 status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
683 if (status == 0)
684 rc->flags = FLAG_FLUSHQ;
685 }
687 return (status);
688 } /* int rrd_cache_flush_identifier */
690 static int64_t rrd_get_random_variation (void)
691 {
692 long min;
693 long max;
695 if (random_timeout <= 0)
696 return (0);
698 /* Assure that "cache_timeout + random_variation" is never negative. */
699 if (random_timeout > cache_timeout)
700 {
701 INFO ("rrdtool plugin: Adjusting \"RandomTimeout\" to %.3f seconds.",
702 CDTIME_T_TO_DOUBLE (cache_timeout));
703 random_timeout = cache_timeout;
704 }
706 max = (long) (random_timeout / 2);
707 min = max - ((long) random_timeout);
709 return ((int64_t) cdrand_range (min, max));
710 } /* int64_t rrd_get_random_variation */
712 static int rrd_cache_insert (const char *filename,
713 const char *value, cdtime_t value_time)
714 {
715 rrd_cache_t *rc = NULL;
716 int new_rc = 0;
717 char **values_new;
719 pthread_mutex_lock (&cache_lock);
721 /* This shouldn't happen, but it did happen at least once, so we'll be
722 * careful. */
723 if (cache == NULL)
724 {
725 pthread_mutex_unlock (&cache_lock);
726 WARNING ("rrdtool plugin: cache == NULL.");
727 return (-1);
728 }
730 c_avl_get (cache, filename, (void *) &rc);
732 if (rc == NULL)
733 {
734 rc = malloc (sizeof (*rc));
735 if (rc == NULL)
736 return (-1);
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 }
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 }
756 values_new = (char **) 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;
763 sstrerror (errno, errbuf, sizeof (errbuf));
765 c_avl_remove (cache, filename, &cache_key, NULL);
766 pthread_mutex_unlock (&cache_lock);
768 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
770 sfree (cache_key);
771 sfree (rc->values);
772 sfree (rc);
773 return (-1);
774 }
775 rc->values = values_new;
777 rc->values[rc->values_num] = strdup (value);
778 if (rc->values[rc->values_num] != NULL)
779 rc->values_num++;
781 if (rc->values_num == 1)
782 rc->first_value = value_time;
783 rc->last_value = value_time;
785 /* Insert if this is the first value */
786 if (new_rc == 1)
787 {
788 void *cache_key = strdup (filename);
790 if (cache_key == NULL)
791 {
792 char errbuf[1024];
793 sstrerror (errno, errbuf, sizeof (errbuf));
795 pthread_mutex_unlock (&cache_lock);
797 ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
799 sfree (rc->values[0]);
800 sfree (rc->values);
801 sfree (rc);
802 return (-1);
803 }
805 c_avl_insert (cache, cache_key, rc);
806 }
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));
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;
821 status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
822 if (status == 0)
823 rc->flags = FLAG_QUEUED;
825 rc->random_variation = rrd_get_random_variation ();
826 }
827 else
828 {
829 DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
830 }
831 }
833 if ((cache_timeout > 0) &&
834 ((cdtime () - cache_flush_last) > cache_flush_timeout))
835 rrd_cache_flush (cache_flush_timeout);
837 pthread_mutex_unlock (&cache_lock);
839 return (0);
840 } /* int rrd_cache_insert */
842 static int rrd_cache_destroy (void) /* {{{ */
843 {
844 void *key = NULL;
845 void *value = NULL;
847 int non_empty = 0;
849 pthread_mutex_lock (&cache_lock);
851 if (cache == NULL)
852 {
853 pthread_mutex_unlock (&cache_lock);
854 return (0);
855 }
857 while (c_avl_pick (cache, &key, &value) == 0)
858 {
859 rrd_cache_t *rc;
860 int i;
862 sfree (key);
863 key = NULL;
865 rc = value;
866 value = NULL;
868 if (rc->values_num > 0)
869 non_empty++;
871 for (i = 0; i < rc->values_num; i++)
872 sfree (rc->values[i]);
873 sfree (rc->values);
874 sfree (rc);
875 }
877 c_avl_destroy (cache);
878 cache = NULL;
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 }
891 pthread_mutex_unlock (&cache_lock);
892 return (0);
893 } /* }}} int rrd_cache_destroy */
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);
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 */
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;
916 if (do_shutdown)
917 return (0);
919 if (0 != strcmp (ds->type, vl->type)) {
920 ERROR ("rrdtool plugin: DS type does not match value list type");
921 return -1;
922 }
924 if (value_list_to_filename (filename, sizeof (filename), vl) != 0)
925 return (-1);
927 if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
928 return (-1);
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 }
957 status = rrd_cache_insert (filename, values, vl->time);
959 return (status);
960 } /* int rrd_write */
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);
967 if (cache == NULL) {
968 pthread_mutex_unlock (&cache_lock);
969 return (0);
970 }
972 rrd_cache_flush_identifier (timeout, identifier);
974 pthread_mutex_unlock (&cache_lock);
975 return (0);
976 } /* int rrd_flush */
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 if (datadir != NULL)
1009 free (datadir);
1010 datadir = strdup (value);
1011 if (datadir != NULL)
1012 {
1013 int len = strlen (datadir);
1014 while ((len > 0) && (datadir[len - 1] == '/'))
1015 {
1016 len--;
1017 datadir[len] = '\0';
1018 }
1019 if (len <= 0)
1020 {
1021 free (datadir);
1022 datadir = NULL;
1023 }
1024 }
1025 }
1026 else if (strcasecmp ("StepSize", key) == 0)
1027 {
1028 unsigned long temp = strtoul (value, NULL, 0);
1029 if (temp > 0)
1030 rrdcreate_config.stepsize = temp;
1031 }
1032 else if (strcasecmp ("HeartBeat", key) == 0)
1033 {
1034 int temp = atoi (value);
1035 if (temp > 0)
1036 rrdcreate_config.heartbeat = temp;
1037 }
1038 else if (strcasecmp ("CreateFilesAsync", key) == 0)
1039 {
1040 if (IS_TRUE (value))
1041 rrdcreate_config.async = 1;
1042 else
1043 rrdcreate_config.async = 0;
1044 }
1045 else if (strcasecmp ("RRARows", key) == 0)
1046 {
1047 int tmp = atoi (value);
1048 if (tmp <= 0)
1049 {
1050 fprintf (stderr, "rrdtool: `RRARows' must "
1051 "be greater than 0.\n");
1052 ERROR ("rrdtool: `RRARows' must "
1053 "be greater than 0.\n");
1054 return (1);
1055 }
1056 rrdcreate_config.rrarows = tmp;
1057 }
1058 else if (strcasecmp ("RRATimespan", key) == 0)
1059 {
1060 char *saveptr = NULL;
1061 char *dummy;
1062 char *ptr;
1063 char *value_copy;
1064 int *tmp_alloc;
1066 value_copy = strdup (value);
1067 if (value_copy == NULL)
1068 return (1);
1070 dummy = value_copy;
1071 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
1072 {
1073 dummy = NULL;
1075 tmp_alloc = realloc (rrdcreate_config.timespans,
1076 sizeof (int) * (rrdcreate_config.timespans_num + 1));
1077 if (tmp_alloc == NULL)
1078 {
1079 fprintf (stderr, "rrdtool: realloc failed.\n");
1080 ERROR ("rrdtool: realloc failed.\n");
1081 free (value_copy);
1082 return (1);
1083 }
1084 rrdcreate_config.timespans = tmp_alloc;
1085 rrdcreate_config.timespans[rrdcreate_config.timespans_num] = atoi (ptr);
1086 if (rrdcreate_config.timespans[rrdcreate_config.timespans_num] != 0)
1087 rrdcreate_config.timespans_num++;
1088 } /* while (strtok_r) */
1090 qsort (/* base = */ rrdcreate_config.timespans,
1091 /* nmemb = */ rrdcreate_config.timespans_num,
1092 /* size = */ sizeof (rrdcreate_config.timespans[0]),
1093 /* compar = */ rrd_compare_numeric);
1095 free (value_copy);
1096 }
1097 else if (strcasecmp ("XFF", key) == 0)
1098 {
1099 double tmp = atof (value);
1100 if ((tmp < 0.0) || (tmp >= 1.0))
1101 {
1102 fprintf (stderr, "rrdtool: `XFF' must "
1103 "be in the range 0 to 1 (exclusive).");
1104 ERROR ("rrdtool: `XFF' must "
1105 "be in the range 0 to 1 (exclusive).");
1106 return (1);
1107 }
1108 rrdcreate_config.xff = tmp;
1109 }
1110 else if (strcasecmp ("WritesPerSecond", key) == 0)
1111 {
1112 double wps = atof (value);
1114 if (wps < 0.0)
1115 {
1116 fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
1117 "greater than or equal to zero.");
1118 return (1);
1119 }
1120 else if (wps == 0.0)
1121 {
1122 write_rate = 0.0;
1123 }
1124 else
1125 {
1126 write_rate = 1.0 / wps;
1127 }
1128 }
1129 else if (strcasecmp ("RandomTimeout", key) == 0)
1130 {
1131 double tmp;
1133 tmp = atof (value);
1134 if (tmp < 0.0)
1135 {
1136 fprintf (stderr, "rrdtool: `RandomTimeout' must "
1137 "be greater than or equal to zero.\n");
1138 ERROR ("rrdtool: `RandomTimeout' must "
1139 "be greater then or equal to zero.");
1140 }
1141 else
1142 {
1143 random_timeout = DOUBLE_TO_CDTIME_T (tmp);
1144 }
1145 }
1146 else
1147 {
1148 return (-1);
1149 }
1150 return (0);
1151 } /* int rrd_config */
1153 static int rrd_shutdown (void)
1154 {
1155 pthread_mutex_lock (&cache_lock);
1156 rrd_cache_flush (0);
1157 pthread_mutex_unlock (&cache_lock);
1159 pthread_mutex_lock (&queue_lock);
1160 do_shutdown = 1;
1161 pthread_cond_signal (&queue_cond);
1162 pthread_mutex_unlock (&queue_lock);
1164 if ((queue_thread_running != 0)
1165 && ((queue_head != NULL) || (flushq_head != NULL)))
1166 {
1167 INFO ("rrdtool plugin: Shutting down the queue thread. "
1168 "This may take a while.");
1169 }
1170 else if (queue_thread_running != 0)
1171 {
1172 INFO ("rrdtool plugin: Shutting down the queue thread.");
1173 }
1175 /* Wait for all the values to be written to disk before returning. */
1176 if (queue_thread_running != 0)
1177 {
1178 pthread_join (queue_thread, NULL);
1179 memset (&queue_thread, 0, sizeof (queue_thread));
1180 queue_thread_running = 0;
1181 DEBUG ("rrdtool plugin: queue_thread exited.");
1182 }
1184 rrd_cache_destroy ();
1186 return (0);
1187 } /* int rrd_shutdown */
1189 static int rrd_init (void)
1190 {
1191 static int init_once = 0;
1192 int status;
1194 if (init_once != 0)
1195 return (0);
1196 init_once = 1;
1198 if (rrdcreate_config.heartbeat <= 0)
1199 rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
1201 /* Set the cache up */
1202 pthread_mutex_lock (&cache_lock);
1204 cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1205 if (cache == NULL)
1206 {
1207 ERROR ("rrdtool plugin: c_avl_create failed.");
1208 return (-1);
1209 }
1211 cache_flush_last = cdtime ();
1212 if (cache_timeout == 0)
1213 {
1214 cache_flush_timeout = 0;
1215 }
1216 else if (cache_flush_timeout < cache_timeout)
1217 cache_flush_timeout = 10 * cache_timeout;
1219 pthread_mutex_unlock (&cache_lock);
1221 status = plugin_thread_create (&queue_thread, /* attr = */ NULL,
1222 rrd_queue_thread, /* args = */ NULL);
1223 if (status != 0)
1224 {
1225 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1226 return (-1);
1227 }
1228 queue_thread_running = 1;
1230 DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %lu;"
1231 " heartbeat = %i; rrarows = %i; xff = %lf;",
1232 (datadir == NULL) ? "(null)" : datadir,
1233 rrdcreate_config.stepsize,
1234 rrdcreate_config.heartbeat,
1235 rrdcreate_config.rrarows,
1236 rrdcreate_config.xff);
1238 return (0);
1239 } /* int rrd_init */
1241 void module_register (void)
1242 {
1243 plugin_register_config ("rrdtool", rrd_config,
1244 config_keys, config_keys_num);
1245 plugin_register_init ("rrdtool", rrd_init);
1246 plugin_register_write ("rrdtool", rrd_write, /* user_data = */ NULL);
1247 plugin_register_flush ("rrdtool", rrd_flush, /* user_data = */ NULL);
1248 plugin_register_shutdown ("rrdtool", rrd_shutdown);
1249 }